plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
mc225/Softwares_Tom-master
|
correctShear.m
|
.m
|
Softwares_Tom-master/LightSheet/correctShear.m
| 705 |
utf_8
|
f64b7fdc0a6df81e26117d8162d9573d
|
% correctedDataCube=correctShear(dataCube,shearFactor)
%
% dataCube: a three-dimensional matrix
% shearFactor: the shear to be undone in units of pixels for the first and second dimension, respectively.
function dataCube=correctShear(dataCube,shearFactor)
if (~isempty(shearFactor) && ~all(shearFactor==0))
logMessage('Correcting a shear of (%0.3f,%0.3f) pixels...',shearFactor);
xRange=[1:size(dataCube,1)];
yRange=[1:size(dataCube,2)];
for zIdx=1:size(dataCube,3)
shearing=shearFactor*(zIdx-floor(1+size(dataCube,3)/2));
dataCube(:,:,zIdx)=interp2(dataCube(:,:,zIdx),yRange+shearing(2),xRange.'+shearing(1),'*cubic',0);
end
end
end
|
github
|
mc225/Softwares_Tom-master
|
lightSheet3DShapeSimulation.m
|
.m
|
Softwares_Tom-master/LightSheet/lightSheet3DShapeSimulation.m
| 5,746 |
utf_8
|
e8d3642b3c622cb2fa641586beb5c172
|
function lightSheet3DShapeSimulation()
close all;
outputFolderName=[pwd(),'/'];
stepSize=[1 1 1]*.1e-6;
%
% Create figures
%
colorMap=jet(1024);
% colorMap=interpolatedColorMap(1024,[.5 1 .5; .5 .5 1; 0 0 1; 1 1 0; 1 0 0],[0 0.25 .5 .75 1]);
% colorMap=hot(1024);
figures=createFigure(0,1,true,9,true,15,@max,[0.2 0.4],stepSize,.001); colormap(colorMap);
figures(2)=createFigure(0,0.01,true,9,true,15,@plus,[0.2 0.4],stepSize,.001); colormap(colorMap);
figures(3)=createFigure(5,1,false,.12,false,0,@max,[0.05 0.2],stepSize,-1); colormap(colorMap);
% Output
saveWithTransparency(figures(1),strcat(outputFolderName,'GaussianBeamSwipedIntoLightSheet.png'));
saveWithTransparency(figures(2),strcat(outputFolderName,'BesselBeamSwipedIntoLightSheet.png'));
saveWithTransparency(figures(3),strcat(outputFolderName,'AiryBeamSwipedIntoLightSheet.png'));
end
function fig=createFigure(alpha,beta,circularSymmetric,isoValues,logScale,colorMapOffset,projector,opaquenessLightSheet,stepSize,noiseLevel)
% Generates the light sheets
[psf lightSheet X Y Z]=generateLightSheet(alpha,beta,circularSymmetric,projector,stepSize,noiseLevel);
if (logScale)
psf=log(max(psf,eps(1)));
lightSheet=log(max(lightSheet,eps(1)));
end
psf=psf+colorMapOffset;
lightSheet=lightSheet+colorMapOffset;
% Draw the figures
fig=figure('Position',[50 50 1024 768],'Color','white');
% Draw beam
if (circularSymmetric)
beamCenterIdx=1+floor(size(psf,1)/2);
psfSlice=squeeze(psf(1+floor(end/2):end,beamCenterIdx,:));
pRange=2*pi*[0:.01:1];
rRange=Y(1+floor(end/2):end,1,1);
zRange=squeeze(Z(1,1,:));
[P,R,Zpolar]=meshgrid(pRange,rRange,zRange);
[Xpolar,Ypolar,Zpolar]=pol2cart(P,R,Zpolar);
psfSlice=repmat(permute(psfSlice,[1 3 2]),[1 length(pRange) 1]);
fv=isosurface(Xpolar,Ypolar,Zpolar,psfSlice,isoValues(1));
if (~isempty(fv.faces))
p1=patch(fv,'FaceColor','interp','EdgeColor','none');
patch(isocaps(Xpolar,Ypolar,Zpolar*1.005,psfSlice,isoValues(1)),'FaceColor','interp','EdgeColor','none');
faceNormals=cross(fv.vertices(fv.faces(:,1),:)-fv.vertices(fv.faces(:,2),:),fv.vertices(fv.faces(:,1),:)-fv.vertices(fv.faces(:,3),:));
vertexNormals=zeros(size(fv.vertices));
for (faceIdx=1:size(faceNormals,1))
vertexNormals(fv.faces(faceIdx,:),:)=vertexNormals(fv.faces(faceIdx,:),:)+repmat(faceNormals(faceIdx,:),[3 1]);
end
vertexNormals=-vertexNormals./repmat(sum(abs(vertexNormals).^2,2),[1 3]);
set(p1,'VertexNormals',vertexNormals);
end
clear psfSlice Xpolar Ypolar Zpolar;
else
p1=patch(isosurface(X,Y,Z,psf,isoValues(1)),'FaceColor','white','EdgeColor','none');
patch(isocaps(X,Y,Z*1.005,psf,isoValues(1)),'FaceColor','interp','EdgeColor','none');
isonormals(X,Y,Z,psf,p1);
end
set(p1,'FaceColor','flat','CData',isoValues(1),'CDataMapping','scaled');
%Draw light sheet
p2=patch(isosurface(X,Y,Z,lightSheet,isoValues(end)),'FaceColor','white','EdgeColor','none','FaceAlpha',opaquenessLightSheet(1));
patch(isocaps(X,Y,Z,lightSheet,isoValues(end)),'FaceColor','interp','EdgeColor','none','FaceAlpha',opaquenessLightSheet(2));
axis equal;
camtarget([mean(X(:)) mean(Y(:)) mean(Z(:))]);
camup([0 1 0]);
campos([40 15 -25]);
camva(33);
camproj('orthographic');
camlight(60,30); camlight; lighting gouraud;
isonormals(X,Y,Z,lightSheet,p2);
set(p2,'FaceColor','flat','CData',isoValues(end),'CDataMapping','scaled');
set(gca,'Visible','Off');
xlim(X([1 end]));ylim(Y([1 end]));zlim(Z([1 end]));
drawnow();
end
function [psf lightSheet X Y Z]=generateLightSheet(alpha,beta,circularSymmetric,projector,stepSize,noiseLevel)
xRange=[-10e-6:stepSize(1):25e-6]; yRange=[-10e-6:stepSize(2):10e-6]; zRange=[-10e-6:stepSize(3):10e-6];
xRangeShort=xRange(1:length(yRange));
[X,Y,Z]=ndgrid(xRange,yRange,zRange);
wavelength=532e-9;
pupilFunctor=@(U,V) (sqrt(U.^2+V.^2)<=1 & sqrt(U.^2+V.^2)>(1-beta)).*exp(2i*pi*alpha*(U.^3-V.^3-2/3*(U-V)));
objectiveNumericalAperture=0.42;
refractiveIndex=1.4;
magnification=20;
tubeLength=Inf; % Infinite focal length lens simulated, more typically this should be 200e-3;
psf=calcVectorialPsf(xRangeShort,yRange,zRange,wavelength,...
@(U,V) pupilFunctor(U,V)/sqrt(2),@(U,V) 1i*pupilFunctor(U,V)/sqrt(2), ... % Circ polariz
objectiveNumericalAperture,refractiveIndex,magnification,tubeLength);
psf=psf./max(psf(:));
psf(psf<noiseLevel)=0;
if (circularSymmetric)
[XShort YShort]=ndgrid(xRangeShort,yRange,zRange);
R=sqrt(XShort.^2+YShort.^2);
maxRadius=R(1+floor(end/2),find(psf(1+floor(end/2),:,1)>0,1,'first'));
psf(R>maxRadius)=0;
clear XShort YShort;
end
% Calculate the light-sheet
beamSize=size(psf);
swipeLength=beamSize(1);
lightSheet=psf;
for swipeIdx=2:swipeLength,
lightSheet(swipeIdx:end,:,:)=projector(lightSheet(swipeIdx:end,:,:),psf(1:(end-(swipeIdx-1)),:,:));
end
extension=length(xRange)-length(xRangeShort);
lightSheet(end+[1:extension],:,:)=repmat(lightSheet(end,:,:),[extension 1 1]);
lightSheet=lightSheet/max(lightSheet(:));
psf(end+extension,1,1)=0;
psf=permute(psf,[2 1 3]);
lightSheet=permute(lightSheet,[2 1 3]);
X=permute(X,[2 1 3])*1e6;
Y=permute(Y,[2 1 3])*1e6;
Z=permute(Z,[2 1 3])*1e6;
end
|
github
|
mc225/Softwares_Tom-master
|
displayDataCubeSlices.m
|
.m
|
Softwares_Tom-master/LightSheet/displayDataCubeSlices.m
| 35,999 |
utf_8
|
888aa32cd3de3dbc6c680870bcff7db8
|
function displayDataCubeSlices(folderNames)
close all;
if (nargin<1 || isempty(folderNames))
% folderNames='Z:\RESULTS\2013-05-14_cellspheroidsWGA\2013-05-14_cellspheroidsWGA_nofilter_ap1-3\cropped'; % Cell cluster section at -27.5um
% % folderNames='Z:\RESULTS\2013-05-14_cellspheroidsWGA\2013-05-14_cellspheroidsWGA_filter_ap1-3'; %,'Z:\RESULTS\2013-05-14_cellspheroidsWGA_nofilter_ap1-3'}; % Cell cluster section at -32um
% folderNames='Z:\RESULTS\2013-05-14_cellspheroidsWGA\2013-05-14_cellspheroidsWGA_filter_ap1-2B'; % 5-cell cluster
%folderNames={'Z:\RESULTS\2013-04-26HEK_ApOneThird\2013-04-26 13_03_52.075_blue1','Z:\RESULTS\2013-04-26HEK_ApOneThird\2013-04-26 12_49_28.119_green1'};
%folderNames={'Z:\RESULTS\2013-05-09_HEK_transientTransfected_apOneThird\2013-05-09 16_15_24.228_filter_nodichr','Z:\RESULTS\2013-05-09_HEK_transientTransfected_apOneThird\2013-05-09 16_37_05.814_nofilter_dichroic'};
% folderNames='Z:\RESULTS\2013-05-09_HEK_transientTransfected_apOneThird\2013-05-09 16_37_05.814_nofilter_dichroic';
% folderNames='Z:\RESULTS\2013-05-14_cellspheroidsWGA\2013-05-14_cellspheroidsWGA_filter_ap1-3'; %,'Z:\RESULTS\2013-05-14_cellspheroidsWGA_nofilter_ap1-3'}; % Cell cluster section at -35um
% folderNames='Z:\RESULTS\2013-05-14_cellspheroidsWGA\2013-05-14_cellspheroidsWGA_filter_ap1-2B'; % 5-cell cluster
% folderNames='Z:\RESULTS\2013-05-14_cellspheroidsWGA\2013-05-14_cellspheroidsWGA_filter_ap1-3B'; % 5 cell cluster (not used?)
% folderNames={'Z:\RESULTS\2013-05-15\2013-05-15_cellspheroidsWGA_apOneHalf\2013-05-15 17_31_34.698_A','Z:\RESULTS\2013-05-15\2013-05-15_cellspheroidsWGA_apOneHalf\2013-05-15 17_45_03.053_A'};
% folderNames={'Z:\RESULTS\2013-05-15\2013-05-15_HEKsWGA_apOneHalf\2013-05-15 16_52_04.156','Z:\RESULTS\2013-05-15\2013-05-15_HEKsWGA_apOneHalf\2013-05-15 17_11_39.629'};
% folderNames={'Z:\RESULTS\2013-05-15\2013-05-15_HEKWGA_apOneHalf\2013-05-15 19_16_41.859_A','Z:\RESULTS\2013-05-15\2013-05-15_HEKWGA_apOneHalf\2013-05-15 19_26_28.113_A'};
% folderNames={'Z:\RESULTS\2013-05-15\2013-05-15_HEKWGA_apOneHalf\2013-05-15 19_43_10.533_B','Z:\RESULTS\2013-05-15\2013-05-15_HEKWGA_apOneHalf\2013-05-15 19_52_04.788_B_changedLambda'};
% folderNames={'Z:\RESULTS\2013-05-15\2013-05-15_HEKWGA_apOneThird\2013-05-15 18_54_03.883','Z:\RESULTS\2013-05-15\2013-05-15_HEKWGA_apOneThird\2013-05-15 19_04_11.913'};
% folderNames={'Z:\RESULTS\2013-05-15\2013-05-15_cellspheroidsWGA_apOneThird\2013-05-15 18_12_45.370','Z:\RESULTS\2013-05-15\2013-05-15_cellspheroidsWGA_apOneThird\2013-05-15 18_23_14.789_changedColor'}; % Dual color
% folderNames={'C:\Users\Tom\Dropbox\AirySheetData\DataCubes\2013-05-14_cellspheroidsWGA\2013-05-14_cellspheroidsWGA_filter_ap1-2B'}; % 5 cells
% folderNames={'E:\Stored Files\RESULTS\2013-08-08\HEK2\2013-08-08 15_57_16.566\'};
% folderNames={'Z:\RESULTS\2013-09-09\2013-09-09 17_20_19.909 at0um_sliced'};
% folderNames={'Z:\RESULTS\2013-09-09\2013-09-09 17_28_37.355 at_50um_sliced'};
% folderNames={'Z:\RESULTS\2013-09-09\2013-09-09 17_38_06.531 at_85um_sliced'};
% folderNames={'Z:\RESULTS\2013-09-13_Amphioxus\Run_1\2013-09-13 12_31_28.686'}; % 488 nm
% folderNames={'Z:\RESULTS\2013-09-13_Amphioxus\Run_1\2013-09-13 12_34_55.726'}; % 532 nm
% folderNames={'Z:\RESULTS\2013-09-13_Amphioxus\Run_2\2013-09-13 12_44_38.570'}; % 488 nm
% folderNames={'Z:\RESULTS\2013-09-13_Amphioxus\Run_2\2013-09-13 12_47_53.135'}; % 532 nm
% folderNames={'Z:\RESULTS\2013-10-10_200nmBeadsNearEntranceInSmallAgaroseDroplet\sample5ApLarge\2013-10-10 18_41_27.129\'};
% folderNames={'Z:\RESULTS\2013-10-10_200nmBeadsNearEntranceInSmallAgaroseDroplet\sample5ApSmall\2013-10-10 18_16_34.014\'};
% folderNames={'Z:\RESULTS\600nmBeadsApOneThird\B\at0\'};
% folderNames={'Z:\RESULTS\2013-01-17 16_59_54.447_Green_2W_Andor_0.05um_(1)\'};
% folderNames={'Z:\RESULTS\2013-01-17 17_07_40.377_Blue_30A_Andor_0.2um_(1)'};
% folderNames={'Z:\RESULTS\2013-04-10_Beads200nm\2013-04-10 16_27_33.222_ApOneQuarter'};
% folderNames={'Z:\RESULTS\2013-04-10_Beads200nm\2013-04-10 16_10_20.097_ApOneHalf'};
% folderNames={'Z:\RESULTS\20120501_alpha7_int1000_g1_morepower_beads_leftofprobe\'};
% folderNames={'Z:\RESULTS\20120501_alpha7_int1000_g1_littlemorepower_betterfocus_beads_leftofprobe\forwardScans\'};
% folderNames={'Z:\RESULTS\20120501_alpha7_int1000_g1_littlemorepower_betterfocus_beads_leftofprobe\forwardScans\'};
folderNames={'H:\RESULTS\2013-09-13_Amphioxus\Run_1\2013-09-13 12_31_28.686'}; % 488 nm
% folderNames={'Z:\RESULTS\2013-09-13_Amphioxus_colorCombined\Run_2'};
end
if (~iscell(folderNames))
folderNames={folderNames};
end
% Load the default values
fig=figure('Visible','off','CloseRequestFcn',@(obj,event) shutDown(obj));
getBaseFigureHandle(fig); % Set permanent reference
loadStatus([folderNames{1},'/displayDataCubeSlices.mat']);
set(fig,'ResizeFcn',@(obj,event) updateStatus('windowPosition',get(obj,'Position')));
updateStatus('version',0.10);
dataCubeNames={};
for (folderName=folderNames)
folderName=folderName{1};
namesInStructs=dir([folderName,'/*.mat']);
if (~isempty(namesInStructs))
for fileName={namesInStructs.name}
fileName=fileName{1};
dataCubeNames{end+1}=[folderName,'/',fileName];
end
else
logMessage('No files found in folder %s.',folderName);
end
end
% Make a list of available data sorted by alpha value
fileDescriptors=struct(); % Use a struct as a hash table
for (fullFileName=dataCubeNames)
fullFileName=fullFileName{1};
try
% Determine the wavelength
wavelength=regexpi(fullFileName,'lambda([\d]*)nm_alpha[^\\/]+','tokens');
if (~isempty(wavelength))
wavelength=str2double(wavelength{1})*1e-9;
% Determine the light sheet type
alpha=regexpi(fullFileName,'alpha([\d]*)_[^\\/]+','tokens');
alpha=str2double(alpha{1});
beta=regexpi(fullFileName,'beta([\d]*)[\D\s]','tokens');
beta=str2double(beta{1})/100;
else
configFile=strcat(fullFileName(1:end-4),'.json');
specificConfig=loadjson(configFile);
alpha=specificConfig.modulation.alpha;
beta=specificConfig.modulation.beta;
wavelength=532e-9;
end
fileDescriptorTag=sprintf('alpha%06.0f_beta%03.0f',[abs(alpha)*1000 beta*1000]);
if (isfield(fileDescriptors,fileDescriptorTag))
fileDescriptor=getfield(fileDescriptors,fileDescriptorTag);
else
fileDescriptor={};
fileDescriptor.fullFileNameGreen=[];
fileDescriptor.fullFileNameRed=[];
end
if (abs(wavelength-488e-9)<20e-9)
fileDescriptor.fullFileNameGreen=fullFileName;
else
fileDescriptor.fullFileNameRed=fullFileName;
end
fileDescriptor.alpha=alpha;
fileDescriptor.beta=beta;
if (fileDescriptor.alpha==0)
if (fileDescriptor.beta==1)
lightSheetType='Gaussian';
else
lightSheetType=sprintf('Bessel %0.0f%%',fileDescriptor.beta*100);
end
else
if (fileDescriptor.beta==1)
lightSheetType=sprintf('Airy %0.1f',fileDescriptor.alpha);
else
lightSheetType=sprintf('a=%0.1f,b=%0.0f%%',[fileDescriptor.alpha fileDescriptor.beta*100]);
end
end
fileDescriptor.lightSheetType=lightSheetType;
fileDescriptors=setfield(fileDescriptors,fileDescriptorTag,fileDescriptor);
catch Exc
logMessage('Skipping %s.',fullFileName);
end
end
% Convert hash table to a sorted array of structs
[~, sortI]=sort(fieldnames(fileDescriptors));
fileDescriptors=cell2mat(struct2cell(fileDescriptors));
fileDescriptors=fileDescriptors(sortI);
% Create the dynamic figure
drawFigure(fig,fileDescriptors,folderNames{1});
end
function drawFigure(fig,fileDescriptors,description)
nbPanels=2;
% Open the figure window
windowMargins=[1 1]*128;
initialPosition=get(0,'ScreenSize')+[windowMargins -2*windowMargins];
set(fig,'Name',description,'Position',getStatus('windowPosition',initialPosition),'Visible','on');
panelSpacing=0*[1/30 1/30]; % Of complete box
axesSpacing=[1/20 1/7]; % Of complete box
projectionsPanel=uipanel('Parent',fig,'BackgroundColor',[1 1 1],'Units','normalized','Position',[0.15 0 0.85 1]);
lightSheetTypes={'<select>', fileDescriptors.lightSheetType};
setUserData('fileDescriptors',fileDescriptors);
panelInfos=[];
for panelIdx=1:nbPanels,
panelInfo=struct();
panelInfo.panel=uipanel('Parent',projectionsPanel,'BackgroundColor',[1 1 1],'BorderWidth',0,'Units','normalized','Position',[panelSpacing(1) panelSpacing(2)+(nbPanels-panelIdx)/nbPanels 1-panelSpacing(1) 1/nbPanels-panelSpacing(2)]);
panelInfo.createMovieButton=uicontrol('Parent',panelInfo.panel,'Position',[10 130 80 20], 'Style','pushbutton', 'String','Create Movie', 'Callback', {@createMovie,fig,panelIdx});
panelInfo.rawDeconvPopup=uicontrol('Parent',panelInfo.panel,'Position',[10 100 80 20], 'Style','popupmenu', 'String', {'raw','deconvolved'}, 'Value',getStatus(sprintf('rawDeconvPopupValue%i',panelIdx),2), 'Callback', {@reloadData,fig});
% beamTypePopupValue=find(strcmp(lightSheetTypes,getStatus(sprintf('beamTypePopupString%i',panelIdx),'<select>')),1,'first');
beamTypePopupValue=1; % Don't preselect
if (isempty(beamTypePopupValue))
beamTypePopupValue=1;
end
panelInfo.beamTypePopup=uicontrol('Parent',panelInfo.panel,'Position',[10 70 80 20], 'Style','popupmenu', 'String',lightSheetTypes, 'Value',beamTypePopupValue, 'Callback', {@reloadData,fig});
panelInfo.axes=[];
panelInfo.axes(1)=axes('Parent',panelInfo.panel,'Units','normalized','Position',[1/6+axesSpacing(1) axesSpacing(2) 2/6-axesSpacing(1) 1-axesSpacing(2)]);
panelInfo.axes(2)=axes('Parent',panelInfo.panel,'Units','normalized','Position',[3/6+axesSpacing(1) axesSpacing(2) 2/6-axesSpacing(1) 1-axesSpacing(2)]);
panelInfo.axes(3)=axes('Parent',panelInfo.panel,'Units','normalized','Position',[5/6+axesSpacing(1) axesSpacing(2) 1/6-axesSpacing(1) 1-axesSpacing(2)]);
if (isempty(panelInfos))
panelInfos=panelInfo;
else
panelInfos(end+1)=panelInfo;
end
end
setUserData('panelInfos',panelInfos);
linkaxes(arrayfun(@(x) x.axes(1),panelInfos));
linkaxes(arrayfun(@(x) x.axes(2),panelInfos));
linkaxes(arrayfun(@(x) x.axes(3),panelInfos));
% Draw the controls
controlsPanel=uipanel('Parent',fig,'Units','normalized','Position',[0 0 0.15 1],'Title','Controls');
uicontrol('Parent',controlsPanel,'Style','text','String','Colormap:','Position',[10,240,80,20]);
setUserData('colorMapPopup',uicontrol('Parent',controlsPanel,'Position',[100 240 80 20], 'Style','popupmenu', ...
'String', {'Screen','Print'}, 'Value',getStatus('colorMapPopupValue',1), 'Callback', {@updateProjections,fig}));
uicontrol('Parent',controlsPanel,'Style','text','String','Background red:','Position',[10,210,100,20]);
setUserData('redBackgroundEdit',uicontrol('Style','edit','String',getStatus('redBackgroundString','0'),'Position',...
[100,210,45,20],'Callback',{@updateProjections,fig}));
uicontrol('Parent',controlsPanel,'Style','text','String','%, green:','Position',[140,210,50,20]);
setUserData('greenBackgroundEdit',uicontrol('Style','edit','String',getStatus('greenBackgroundString','0'),'Position',...
[190,210,45,20],'Callback',{@updateProjections,fig}));
uicontrol('Parent',controlsPanel,'Style','text','String','%','Position',[235,210,20,20]);
uicontrol('Parent',controlsPanel,'Style','text','String','Rel. Int. red:','Position',[10,180,100,20]);
setUserData('redRelativeDisplayIntensityEdit',uicontrol('Style','edit','String',getStatus('redRelativeDisplayIntensityString','1000'),'Position',...
[100,180,45,20],'Callback',{@updateProjections,fig}));
uicontrol('Parent',controlsPanel,'Style','text','String','%, green:','Position',[140,180,50,20]);
setUserData('greenRelativeDisplayIntensityEdit',uicontrol('Style','edit','String',getStatus('greenRelativeDisplayIntensityString','1000'),'Position',...
[190,180,45,20],'Callback',{@updateProjections,fig}));
uicontrol('Parent',controlsPanel,'Style','text','String','%','Position',[235,180,20,20]);
uicontrol('Parent',controlsPanel,'Style','text','String','Green X-shift','Position',[10,150,80,20]);
setUserData('yShiftEdit',uicontrol('Style','edit','String',getStatus('yShiftString','0'),'Position',...
[100,150,40,20],'Callback',{@updateDataCubeSection,fig}));
uicontrol('Parent',controlsPanel,'Style','text','String','Green Y-shift','Position',[10,130,80,20]);
setUserData('xShiftEdit',uicontrol('Style','edit','String',getStatus('xShiftString','0'),'Position',...
[100,130,40,20],'Callback',{@updateDataCubeSection,fig}));
uicontrol('Parent',controlsPanel,'Style','text','String','Green Z-shift','Position',[10,110,80,20]);
setUserData('zShiftEdit',uicontrol('Style','edit','String',getStatus('zShiftString','0'),'Position',...
[100,110,40,20],'Callback',{@updateDataCubeSection,fig}));
% sectioning controls
uicontrol('Parent',controlsPanel,'Style','text','String','X-stack position','Position',[10,50,80,20]);
setUserData('yRangeSelEdit',uicontrol('Style','edit','String',getStatus('yRangeSelString',''),'Position',[100,50,90,20],'Callback',{@updateDataCubeSection,fig}));
uicontrol('Parent',controlsPanel,'Style','text','String','Y-stack position','Position',[10,30,80,20]);
setUserData('xRangeSelEdit',uicontrol('Style','edit','String',getStatus('xRangeSelString',''),'Position',[100,30,90,20],'Callback',{@updateDataCubeSection,fig}));
uicontrol('Parent',controlsPanel,'Style','text','String','Z-stack position','Position',[10,10,80,20]);
setUserData('zRangeSelEdit',uicontrol('Style','edit','String',getStatus('zRangeSelString',''),'Position',[100,10,90,20],'Callback',{@updateDataCubeSection,fig}));
set(fig,'Toolbar','figure');
drawnow();
reloadData([],[],fig);
end
function createMovie(obj,event,fig,panelIdx)
end
function reloadData(obj,event,fig)
flipPropagationAxis=false;
fig=getBaseFigureHandle();
fileDescriptors=getUserData('fileDescriptors');
panelInfos=getUserData('panelInfos');
experimentalSettings=[];
for panelIdx=1:numel(panelInfos),
panelInfo=panelInfos(panelIdx);
beamTypeValue=get(panelInfo.beamTypePopup,'Value')-1; % skip <select>
if (beamTypeValue>0) % skip the <select>
beamTypes=get(panelInfo.beamTypePopup,'String');
if (beamTypeValue<=length(beamTypes))
beamType=beamTypes{beamTypeValue};
updateStatus(sprintf('beamTypePopupString%i',panelIdx),beamType);
set(panelInfo.panel,'Title',beamType);
beamTypeValue=find(strcmp(beamTypes,beamType),1);
fileDescriptor=fileDescriptors(beamTypeValue);
if (isempty(experimentalSettings))
% Load the experimental settings first
if (~isempty(fileDescriptor.fullFileNameGreen))
logMessage(['Loading settings from ',fileDescriptor.fullFileNameGreen,'.']);
experimentalSettings=load(fileDescriptor.fullFileNameGreen,'xRange','yRange','zRange','tRange','setupConfig');
else
logMessage(['Loading settings from ',fileDescriptor.fullFileNameRed,'.']);
experimentalSettings=load(fileDescriptor.fullFileNameRed,'xRange','yRange','zRange','tRange','setupConfig');
end
if (flipPropagationAxis)
experimentalSettings.yRange=-experimentalSettings.yRange(end:-1:1);
end
stageTranslationStepSize=norm(median(diff(experimentalSettings.setupConfig.stagePositions.target)));
if isempty(experimentalSettings.setupConfig.detector.center)
experimentalSettings.setupConfig.detector.center=[0 0];
end
% if (~isfield(experimentalSettings,'xRange'))
% realMagnification=experimentalSettings.setupConfig.detection.objective.magnification*experimentalSettings.setupConfig.detection.tubeLength/experimentalSettings.setupConfig.detection.objective.tubeLength;
% experimentalSettings.xRange=-experimentalSettings.setupConfig.detector.center(1)+experimentalSettings.setupConfig.detector.pixelSize(1)*([1:size(recordedImageStack,1)]-floor(size(recordedImageStack,1)/2)-1)/realMagnification; % up/down
% experimentalSettings.yRange=-experimentalSettings.setupConfig.detector.center(2)+experimentalSettings.setupConfig.detector.pixelSize(2)*([1:size(recordedImageStack,2)]-floor(size(recordedImageStack,2)/2)-1)/realMagnification; % left/right
% experimentalSettings.tRange=stageTranslationStepSize*([1:size(recordedImageStack,3)]-floor(size(recordedImageStack,3)/2+1))/experimentalSettings.setupConfig.detector.framesPerSecond; %Translation range (along z-axis)
% experimentalSettings.zRange=tRange; % detection axis, zero centered
% end
setUserData('xRange',experimentalSettings.xRange);
setUserData('yRange',experimentalSettings.yRange);
setUserData('zRange',experimentalSettings.zRange);
% if (isfield(experimentalSettings,'tRange'))
setUserData('tRange',experimentalSettings.tRange);
% else
% setUserData('tRange',experimentalSettings.zRange);
% end
end
dropDownValue=get(panelInfo.rawDeconvPopup,'Value');
updateStatus(sprintf('rawDeconvPopupValue%i',panelIdx),dropDownValue);
restored=dropDownValue>1;
if (restored)
dataCubeField='restoredDataCube';
else
dataCubeField='recordedImageStack';
end
% Free memory
panelUserData.dataCube=[]; set(panelInfo.panel,'UserData',panelUserData);
if (~isempty(fileDescriptor.fullFileNameRed))
logMessage(['Loading RED channel from ',fileDescriptor.fullFileNameRed,'...']);
loadedData=load(fileDescriptor.fullFileNameRed,dataCubeField);
panelUserData.dataCube=getfield(loadedData,dataCubeField);
clear loadedData;
panelUserData.channels={'red'};
if (~isempty(fileDescriptor.fullFileNameGreen))
logMessage(['Loading GREEN channel from ',fileDescriptor.fullFileNameGreen,'...']);
loadedData=load(fileDescriptor.fullFileNameGreen,dataCubeField);
panelUserData.dataCube(:,:,:,2)=getfield(loadedData,dataCubeField);
clear loadedData;
panelUserData.channels{end+1}='green';
end
else
logMessage(['Loading SINGLE GREEN channel from ',fileDescriptor.fullFileNameGreen,'...']);
loadedData=load(fileDescriptor.fullFileNameGreen,dataCubeField);
panelUserData.dataCube=getfield(loadedData,dataCubeField);
clear loadedData;
panelUserData.channels={'green'};
end
if (flipPropagationAxis)
for (colIdx=1:floor(size(panelUserData.dataCube,2)/2))
panelUserData.dataCube(:,[colIdx end-(colIdx-1)],:,:)=panelUserData.dataCube(:,[end-(colIdx-1) colIdx],:,:);
end
end
else
logMessage('No beams found on disk.');
end
else
panelUserData={};
panelUserData.dataCube=[];
panelUserData.channels={'black'};
end % of if beamTypeValue>0
set(panelInfo.panel,'UserData',panelUserData);
end % of for
updateDataCubeSection([],[],fig);
end
function fig=updateDataCubeSection(hObj,event,fig)
% projector=@mean;
projector=@(X,dim) max(X,[],dim); % Maximum intensity projection
% Interpret the sectioning controls
xRange=getUserData('xRange');
yRange=getUserData('yRange');
zRange=getUserData('zRange');
tRange=getUserData('tRange');
if (~isempty(xRange))
xRangeSel=readDefaultAndConvertToIndexRange(getUserData('xRangeSelEdit'),xRange,xRange([1 end]));
yRangeSel=readDefaultAndConvertToIndexRange(getUserData('yRangeSelEdit'),yRange,yRange([1 end]));
zRangeSel=readDefaultAndConvertToIndexRange(getUserData('zRangeSelEdit'),zRange,zRange([1 end]));
tRangeSel=zRangeSel;
xShift=readDefaultAndConvertToIndices(getUserData('xShiftEdit'),xRange,0);
yShift=readDefaultAndConvertToIndices(getUserData('yShiftEdit'),yRange,0);
zShift=readDefaultAndConvertToIndices(getUserData('zShiftEdit'),zRange,0);
[~, dataCubeCenter(1)]=min(abs(xRange));
[~, dataCubeCenter(2)]=min(abs(yRange));
[~, dataCubeCenter(3)]=min(abs(zRange));
greenShiftInPixels=[xShift yShift zShift]-dataCubeCenter;
% Save the settings for next time we run
updateStatus('xRangeSelString',get(getUserData('xRangeSelEdit'),'String'));
updateStatus('yRangeSelString',get(getUserData('yRangeSelEdit'),'String'));
updateStatus('zRangeSelString',get(getUserData('zRangeSelEdit'),'String'));
updateStatus('xShiftString',get(getUserData('xShiftEdit'),'String'));
updateStatus('yShiftString',get(getUserData('yShiftEdit'),'String'));
updateStatus('zShiftString',get(getUserData('zShiftEdit'),'String'));
% Shift the Green channel
xRangeSelGreen=min(length(xRange),max(1,xRangeSel-greenShiftInPixels(1)));
yRangeSelGreen=min(length(yRange),max(1,yRangeSel-greenShiftInPixels(2)));
zRangeSelGreen=min(length(zRange),max(1,zRangeSel-greenShiftInPixels(3)));
for (panelInfo=getUserData('panelInfos'))
panelUserData=get(panelInfo.panel,'UserData');
if (~isempty(panelUserData.dataCube))
% Calculate the projections
panelUserData.projZY=projector(panelUserData.dataCube(xRangeSel,yRangeSel,zRangeSel,1),1);
panelUserData.projYX=projector(panelUserData.dataCube(xRangeSel,yRangeSel,zRangeSel,1),3);
panelUserData.projZX=projector(panelUserData.dataCube(xRangeSel,yRangeSel,zRangeSel,1),2);
if (ndims(panelUserData.dataCube)>=4)
panelUserData.projZY(:,:,:,2)=projector(panelUserData.dataCube(xRangeSelGreen,yRangeSelGreen,zRangeSelGreen,2),1);
panelUserData.projYX(:,:,:,2)=projector(panelUserData.dataCube(xRangeSelGreen,yRangeSelGreen,zRangeSelGreen,2),3);
panelUserData.projZX(:,:,:,2)=projector(panelUserData.dataCube(xRangeSelGreen,yRangeSelGreen,zRangeSelGreen,2),2);
end
panelUserData.projZY=shiftdim(panelUserData.projZY,1); %Remove new singleton dimension
panelUserData.projZY=permute(panelUserData.projZY,[2 1 3:ndims(panelUserData.projZY)]);
panelUserData.projYX=permute(panelUserData.projYX,[1 2 4:ndims(panelUserData.projYX) 3]); %Remove new singleton dimension
panelUserData.projZX=permute(panelUserData.projZX,[1 3:ndims(panelUserData.projZX) 2]); %Remove new singleton dimension
panelUserData.projZX=permute(panelUserData.projZX,[2 1 3:ndims(panelUserData.projZX)]);
else
% Fake the projections
panelUserData.projZY=zeros(length(yRangeSel),length(zRangeSel),length(panelUserData.channels));
panelUserData.projZY=permute(panelUserData.projZY,[2 1 3:ndims(panelUserData.projZY)]);
panelUserData.projYX=zeros(length(xRangeSel),length(yRangeSel),length(panelUserData.channels));
panelUserData.projZX=zeros(length(xRangeSel),length(zRangeSel),length(panelUserData.channels));
panelUserData.projZX=permute(panelUserData.projZX,[2 1 3:ndims(panelUserData.projZX)]);
end
set(panelInfo.panel,'UserData',panelUserData);
end
fig=updateProjections(hObj,event,fig);
end
end
function fig=updateProjections(obj,event,fig)
colorMapPopupValue=get(getUserData('colorMapPopup'),'Value');
updateStatus('colorMapPopupValue',colorMapPopupValue);
redBackground=str2double(get(getUserData('redBackgroundEdit'),'String'));
if (isempty(redBackground) || isnan(redBackground))
redBackground=0;
end
redBackground=redBackground(1)/100;
set(getUserData('redBackgroundEdit'),'String',sprintf('%0.3f',redBackground*100));
updateStatus('redBackgroundString',sprintf('%0.3f',redBackground*100));
greenBackground=str2double(get(getUserData('greenBackgroundEdit'),'String'));
if (isempty(greenBackground) || isnan(greenBackground))
greenBackground=0;
end
greenBackground=greenBackground(1)/100;
set(getUserData('greenBackgroundEdit'),'String',sprintf('%0.3f',greenBackground*100));
updateStatus('greenBackgroundString',sprintf('%0.3f',greenBackground*100));
colorsForPrint=colorMapPopupValue==2;
colorMapGreen=@(values) interpolatedColorMap(values,[0 0 0; 0 1 0; 1 1 1],[0 .5 1]);
colorMapRed=@(values) interpolatedColorMap(values,[0 0 0; 1 0 0; 1 1 1],[0 .5 1]);
% colorMapImageSize=[1024 64];
% colorMapSingleColorImage=mapColor(repmat([1:colorMapImageSize(1)].',[1 colorMapImageSize(2)]),colorMapSingleColor);
% imwrite('colorMapSingleColorImage.png',colorMapSingleColorImage);
% Normalize
redRelativeDisplayIntensity=str2double(get(getUserData('redRelativeDisplayIntensityEdit'),'String'));
if (isempty(redRelativeDisplayIntensity))
redRelativeDisplayIntensity=100;
set(getUserData('redRelativeDisplayIntensityEdit'),'String',sprintf('%0.0f',redRelativeDisplayIntensityString));
end
redRelativeDisplayIntensity=redRelativeDisplayIntensity/100;
updateStatus('redRelativeDisplayIntensityString',get(getUserData('redRelativeDisplayIntensityEdit'),'String'));
greenRelativeDisplayIntensity=str2double(get(getUserData('greenRelativeDisplayIntensityEdit'),'String'));
if (isempty(greenRelativeDisplayIntensity))
greenRelativeDisplayIntensity=100;
set(getUserData('greenRelativeDisplayIntensityEdit'),'String',sprintf('%0.0f',greenRelativeDisplayIntensityString));
end
greenRelativeDisplayIntensity=greenRelativeDisplayIntensity/100;
updateStatus('greenRelativeDisplayIntensityString',get(getUserData('greenRelativeDisplayIntensityEdit'),'String'));
panelIdx=1;
for (panelInfo=getUserData('panelInfos'))
panelUserData=get(panelInfo.panel,'UserData');
projZY=panelUserData.projZY;
projYX=panelUserData.projYX;
projZX=panelUserData.projZX;
% Remove background and normalize
normalization=ones(1,1,length(panelUserData.channels));
for channelIdx=1:length(panelUserData.channels)
if (strcmp(panelUserData.channels{channelIdx},'red'))
backgroundOffset=redBackground;
relativeDisplayIntensity=redRelativeDisplayIntensity;
else
backgroundOffset=greenBackground;
relativeDisplayIntensity=greenRelativeDisplayIntensity;
end
projZY(:,:,channelIdx)=projZY(:,:,channelIdx)-backgroundOffset;
projYX(:,:,channelIdx)=projYX(:,:,channelIdx)-backgroundOffset;
projZX(:,:,channelIdx)=projZX(:,:,channelIdx)-backgroundOffset;
normalization(channelIdx)=relativeDisplayIntensity;
end
% normalization=max([max(max(projZY)), max(max(projYX)), max(max(projZX))]);
% if (length(normalization)>=2)
% normalization(2)=normalization(2)/greenRelativeDisplayIntensity;
% end
projZY=projZY.*repmat(normalization,[size(projZY,1) size(projZY,2)]);
projYX=projYX.*repmat(normalization,[size(projYX,1) size(projYX,2)]);
projZX=projZX.*repmat(normalization,[size(projZX,1) size(projZX,2)]);
% Add blue channel, or user colormap in case only one channel is present
if (ndims(projZY)>2)
projZY=colorMapChannels(projZY,{colorMapRed,colorMapGreen},colorsForPrint);
projYX=colorMapChannels(projYX,{colorMapRed,colorMapGreen},colorsForPrint);
projZX=colorMapChannels(projZX,{colorMapRed,colorMapGreen},colorsForPrint);
else
if (strcmp(panelUserData.channels{1},'red'))
colorMapSingleColor=colorMapRed;
else
colorMapSingleColor=colorMapGreen;
end
projZY=colorMapChannels(projZY,colorMapSingleColor,colorsForPrint);
projYX=colorMapChannels(projYX,colorMapSingleColor,colorsForPrint);
projZX=colorMapChannels(projZX,colorMapSingleColor,colorsForPrint);
end
% Draw the projections
xRange=getUserData('xRange');
yRange=getUserData('yRange');
zRange=getUserData('zRange');
tRange=getUserData('tRange');
xRangeSel=readDefaultAndConvertToIndexRange(getUserData('xRangeSelEdit'),xRange,xRange([1 end]));
yRangeSel=readDefaultAndConvertToIndexRange(getUserData('yRangeSelEdit'),yRange,yRange([1 end]));
zRangeSel=readDefaultAndConvertToIndexRange(getUserData('zRangeSelEdit'),zRange,zRange([1 end]));
tRangeSel=zRangeSel;
axesColor=[0 0 0];
showImage(projYX,[],yRange(yRangeSel)*1e6,xRange(xRangeSel)*1e6,panelInfo.axes(1));
axis equal;
set(panelInfo.axes(1),'TickDir','out','TickLength',[0.01 0.025]*3,'Color',axesColor,'XColor',axesColor,'YColor',axesColor,'LineWidth',3,'FontSize',16,'FontWeight','bold');
xlabel('Parent',panelInfo.axes(1),'X (propagation) [\mum]','LineWidth',3,'FontSize',22,'FontWeight','bold');
ylabel('Parent',panelInfo.axes(1),'Y (swipe) [\mum]','LineWidth',3,'FontSize',22,'FontWeight','bold');
showImage(projZY,[],yRange(yRangeSel)*1e6,zRange(zRangeSel)*1e6,panelInfo.axes(2));
axis equal;
set(panelInfo.axes(2),'TickDir','out','TickLength',[0.01 0.025]*3,'Color',axesColor,'XColor',axesColor,'YColor',axesColor,'LineWidth',3,'FontSize',16,'FontWeight','bold');
xlabel('Parent',panelInfo.axes(2),'X (propagation) [\mum]','LineWidth',3,'FontSize',22,'FontWeight','bold');
ylabel('Parent',panelInfo.axes(2),'Z (axial) [\mum]','LineWidth',3,'FontSize',22,'FontWeight','bold');
showImage(projZX,[],xRange(xRangeSel)*1e6,tRange(tRangeSel)*1e6,panelInfo.axes(3));
axis equal;
set(panelInfo.axes(3),'TickDir','out','TickLength',[0.01 0.025]*3,'Color',axesColor,'XColor',axesColor,'YColor',axesColor,'LineWidth',3,'FontSize',16,'FontWeight','bold');
xlabel('Parent',panelInfo.axes(3),'Y (swipe) [\mum]','LineWidth',3,'FontSize',22,'FontWeight','bold');
ylabel('Parent',panelInfo.axes(3),'Z (axial) [\mum]','LineWidth',3,'FontSize',22,'FontWeight','bold');
imwrite(projYX,sprintf('projXY%0.0f.png',panelIdx));
imwrite(projZY,sprintf('projZX%0.0f.png',panelIdx));
imwrite(projZX,sprintf('projZY%0.0f.png',panelIdx));
panelIdx=panelIdx+1;
end
end
function [rangeSelStart rangeSelEnd]=readDefaultAndConvertToIndices(rangeSelEdit,range,defaultValues)
rangeSel=str2num(get(rangeSelEdit,'String'))*1e-6;
if (isempty(rangeSel))
rangeSel=defaultValues(1);
end
if (length(rangeSel)<2 && length(defaultValues)>=2)
rangeSel(2)=defaultValues(end);
end
set(rangeSelEdit,'String',sprintf('%0.3f ',rangeSel*1e6));
% Convert metric to indexes
[~, rangeSelStart]=min(abs(range-min(rangeSel)));
[~, rangeSelEnd]=min(abs(range-max(rangeSel)));
end
function rangeSel=readDefaultAndConvertToIndexRange(rangeSelEdit,range,defaultValues)
[rangeSelStart rangeSelEnd]=readDefaultAndConvertToIndices(rangeSelEdit,range,defaultValues);
rangeSel=[rangeSelStart:rangeSelEnd];
end
function RGB=colorMapChannels(imageChannels,colorMaps,colorsForPrint)
if ~iscell(colorMaps)
colorMaps={colorMaps};
end
if (nargin<3)
colorsForPrint=false;
end
inputSize=size(imageChannels);
if (length(inputSize)<3)
inputSize(3)=1;
end
RGB=zeros([inputSize(1:2) 3]);
for channelIdx=1:inputSize(3),
RGB=RGB+mapColor(imageChannels(:,:,channelIdx),colorMaps{channelIdx});
end
if (colorsForPrint),
HSV=rgb2hsv(RGB);
HSV(:,:,3)=1-HSV(:,:,3); % Swap the intensity
RGB=hsv2rgb(HSV);
end
end
function shutDown(obj,event)
getBaseFigureHandle([]); % Clear the permanent reference
closereq();
end
%
% Data access functions
%
%
% User data function are 'global' variables linked to this GUI, though not
% persistent between program shutdowns.
%
function value=getUserData(fieldName)
fig=getBaseFigureHandle();
userData=get(fig,'UserData');
if (isfield(userData,fieldName))
value=userData.(fieldName);
else
value=[];
end
end
function setUserData(fieldName,value)
if (nargin<2)
value=fieldName;
fieldName=inputname(1);
end
fig=getBaseFigureHandle();
userData=get(fig,'UserData');
userData.(fieldName)=value;
set(fig,'UserData',userData);
end
function fig=getBaseFigureHandle(fig)
persistent persistentFig;
if (nargin>=1)
if (~isempty(fig))
persistentFig=fig;
else
clear persistentFig;
end
else
fig=persistentFig;
end
end
%
% 'Status' variables are stored persistently to disk and reloaded next time
%
function loadStatus(pathToStatusFile)
if (nargin<1 || isempty(pathToStatusFile))
pathToStatusFile=[mfilename('fullpath'),'.mat'];
end
try
load(pathToStatusFile,'status');
catch Exc
status={};
status.version=-1;
end
status.pathToStatusFile=pathToStatusFile;
setUserData('status',status);
end
function value=getStatus(fieldName,defaultValue)
status=getUserData('status');
if (isfield(status,fieldName))
value=status.(fieldName);
else
if (nargin<2)
defaultValue=[];
end
value=defaultValue;
end
end
function updateStatus(fieldName,value)
status=getUserData('status');
status.(fieldName)=value;
setUserData('status',status);
saveStatus();
end
function saveStatus()
status=getUserData('status');
save(status.pathToStatusFile,'status');
end
|
github
|
mc225/Softwares_Tom-master
|
copyMatFilesOnly.m
|
.m
|
Softwares_Tom-master/LightSheet/copyMatFilesOnly.m
| 2,403 |
utf_8
|
720bb47b2fa9577991dbb81890e7a856
|
% copyMatFilesOnly(sourceFolder,targetFolder)
%
% Copies only the .mat files and removes the date-time folders, combining everything into the parent folder.
%
function status=copyMatFilesOnly(sourceFolder,targetFolder)
if nargin<1 || isempty(sourceFolder)
sourceFolder=uigetdir(pwd(),'Select Source Folder...');
if (sourceFolder==0)
logMessage('No source folder selected.');
return;
end
end
if nargin<2 || isempty(targetFolder)
targetFolder=uigetdir('D:\Stored Files\RESULTS','Select Destination...');
if (targetFolder==0)
logMessage('No target folder selected.');
return;
end
end
status=true;
% Copy all files
fileNameList=dir(fullfile(sourceFolder,'*.mat'));
for (fileName={fileNameList.name})
fileName=fileName{1};
filePathAndName=fullfile(sourceFolder,fileName);
logMessage(['Copying ',filePathAndName,' to ',targetFolder,'...']);
if ~exist(fullfile(targetFolder,fileName),'file')
status=copyfile(filePathAndName,targetFolder);
if (~status)
logMessage('Error copying file %s!',filePathAndName);
return;
end
else
logMessage('The file %s is already copied.',fullfile(targetFolder,fileName));
end
end
% Recurse through folders
fileDescList=dir(sourceFolder);
for fileDescIdx=1:length(fileDescList)
fileDesc=fileDescList(fileDescIdx);
if fileDesc.isdir && ~strcmp(fileDesc.name,'.') && ~strcmp(fileDesc.name,'..')
if regexp(fileDesc.name,'^\d\d\d\d-\d\d-\d\d\ \d\d_\d\d_\d\d.\d\d\d$')
targetFolderRecursive=targetFolder;
else
targetFolderRecursive=fullfile(targetFolder,fileDesc.name);
[status message]=mkdir(targetFolderRecursive);
if ~status
logMessage(message);
end
end
status=copyMatFilesOnly(fullfile(sourceFolder,fileDesc.name),targetFolderRecursive);
if (~status)
return;
end
end
end
% Results
if nargout==0
if status
logMessage('Copied all files.');
else
logMessage('Could not copy (all) files.');
end
clear status;
end
end
|
github
|
mc225/Softwares_Tom-master
|
simulateAiryAndBesselSI.m
|
.m
|
Softwares_Tom-master/LightSheet/simulateAiryAndBesselSI.m
| 9,858 |
utf_8
|
e500dee14c2547d5c544bcbd4f8e6a1a
|
%
%
%
function [sample xRange yRange zRange]=simulateAiryAndBesselSI()
alpha=7;
beta=5/100;
xRange=single([-25:.15:25]*1e-6); % propagation
yRange=single([-20:.15:20]*1e-6); % swipe
zRange=single([-21:.15:21]*1e-6); % scan
config=struct();
config.excitation=struct();
config.excitation.objective=struct();
config.excitation.objective.refractiveIndex=1.00;
% config.excitation.objective.numericalAperture=0.42;
config.excitation.objective.numericalAperture=0.43; % Fig 1C
config.excitation.objective.magnification=20;
config.excitation.objective.tubeLength=0.200;
% config.excitation.wavelength=532e-9;
config.excitation.wavelength=488e-9; % Fig 1C
config.excitation.fractionOfNumericalApertureUsed=1;
% config.sample.refractiveIndex=1.40;
config.sample.refractiveIndex=1.33; % Fig 1C
config.detection=struct();
config.detection.objective=struct();
config.detection.objective.refractiveIndex=1.00;
% config.detection.objective.numericalAperture=0.40;
config.detection.objective.numericalAperture=0.80; % Fig 1C
config.detection.objective.magnification=20;
config.detection.objective.tubeLength=0.160;
config.detection.tubeLength=0.176;
% config.detection.wavelength=600e-9; %6.12e-7;
config.detection.wavelength=509e-9; % eGFP, Fig 1C
config.detection.fractionOfNumericalApertureUsed=1;
config.detector=struct();
config.detector.pixelSize=[1 1]*7.4e-6;
% Load synthetic sample
sample=getTetraedronDensity(xRange,yRange,zRange);
% sample=getSpiralDensity(xRange,yRange,zRange);
% Calculate light sheet
pupilFunctor=@(U,V) U.^2+V.^2>(1-beta)^2;
[~,psfField]=calcVectorialPsf(yRange,zRange,xRange,config.excitation.wavelength,pupilFunctor,@(U,V) 1i*pupilFunctor(U,V),...
config.excitation.objective.numericalAperture,config.sample.refractiveIndex,...
config.excitation.objective.magnification,config.excitation.objective.tubeLength);
psfField=ipermute(psfField,[2 3 1 4]);
psfFieldSize=size(psfField);
psfField(1,end*2,1,1)=0; % Pad
psfFieldFftY=fft(psfField,[],2);
clear psfField;
yRangeExt=[yRange yRange(end)+diff(yRange(1:2))*[1:length(yRange)]];
nbBeams=7;
nbPhases=5;
period=1.02e-6*config.excitation.wavelength/488e-9;
diffractionPeriod=ceil(10e-6/period)*period;
% Create diffractive grating of nbBeams beams
logMessage('Passing beam through diffraction grating...');
gratingFft=0*yRange;
gratingFft(end*2)=0;
for diffBeamPos=diffractionPeriod*([1:nbBeams]-floor(1+nbBeams/2)),
if abs(diffBeamPos)<-2*yRange(1),
gratingFft=gratingFft+exp(2i*pi*(([1:2*length(yRange)]-1-length(yRange))/(2*length(yRange)))*diffBeamPos/diff(yRange(1:2)));
end
end
gratingFft=ifftshift(gratingFft)./nbBeams;
psf=ifft(psfFieldFftY.*repmat(gratingFft(:).',[psfFieldSize(1) 1 psfFieldSize(3:end)]),[],2);
clear psfFieldFftY gratingFft;
psf=sum(abs(psf).^2,4);
% showImage(squeeze(psf(1+floor(end/2),:,:)),-1,zRange*1e6,yRangeExt*1e6);axis equal;
% Create intensity structured illumination and phase shifts
logMessage('Patterning light sheet intensity...');
psfFft=fft(psf,[],2);
clear psf;
lightSheetFft=zeros([size(psfFft) nbPhases],'single');
for phaseIdx=1:nbPhases, % Generate phases
phaseOffset=(phaseIdx-1)/nbPhases;
pulseFft=0*yRange;
pulseFft(end*2)=0;
beamPositions=period*(phaseOffset+[1:round(diffractionPeriod/period)]-1-floor(round(diffractionPeriod/period)/2));
for beamPos=beamPositions,
pulseFft=pulseFft+exp(2i*pi*(([1:2*length(yRange)]-1-length(yRange))/(2*length(yRange)))*beamPos/diff(yRange(1:2)));
end
pulseFft=ifftshift(pulseFft)./length(beamPositions);
lightSheetFft(:,:,:,phaseIdx)=psfFft.*repmat(pulseFft(:).',[psfFieldSize(1) 1 psfFieldSize(3)]);
end
clear psfFft;
lightSheet=ifft(lightSheetFft,[],2,'symmetric');
clear lightSheetFft;
% for phaseIdx=repmat(1:nbPhases,[1 10])
% showImage(squeeze(lightSheet(1+floor(end/2),1:end/2,:,phaseIdx)),-1,zRange*1e6,yRange*1e6);axis equal;
% drawnow();
% pause(.1);
% end
lightSheet=lightSheet(:,1:end/2,:,:); % Crop again
%
% Calculate detection PSF
%
logMessage('Calculating detection PSF...');
detectionPsf=calcVectorialPsf(xRange,yRange,zRange,config.detection.wavelength,1/sqrt(2),1/sqrt(2),...
config.detection.objective.numericalAperture,config.sample.refractiveIndex,...
config.detection.objective.magnification,config.detection.objective.tubeLength);
detectionPsfFft=fft2(ifftshift(ifftshift(detectionPsf,1),2));
%
% Do the light sheet imaging
%
logMessage('Starting light sheet recording...');
img=zeros([psfFieldSize(1:3) nbPhases]);
for zIdx=1:length(zRange),
logMessage('z=%0.1fum in interval [%0.1fum %0.1fum]',[zRange(zIdx)*1e6,zRange([1 end])*1e6]);
for phaseIdx=1:nbPhases,
fluorescence=sample(:,:,max(1,min(end,[1:end]+(zIdx-1)-floor(length(zRange)/2)))).*lightSheet(:,:,:,phaseIdx);
imgSlice=sum(ifft2(fft2(fluorescence).*detectionPsfFft,'symmetric'),3);
img(:,:,zIdx,phaseIdx)=imgSlice;
end
end
save('img2.mat');
%
% Deconvolve slice by slice
%
[XOtf,YOtf,fRel]=calcOtfGridFromSampleFrequencies(1./[diff(xRange(1:2)) diff(yRange(1:2))],[length(xRange) length(yRange)],(2*config.detection.objective.numericalAperture)/config.detection.wavelength);
deconvolvedImg=zeros([size(img,1) size(img,2) size(img,3)],'single');
for zIdx=1:length(zRange),
slice=img(:,:,zIdx,:);
orders=[-floor(nbPhases/2):floor(nbPhases/2)];
order=zeros([size(slice,1) size(slice,2) 1 length(orders)]);
for orderIdx=1:length(orders),
grating=repmat((yRange/period),[1 1 1 nbPhases])+repmat(permute(([1:nbPhases]-1)/nbPhases,[1 4 3 2]),[1 length(yRange) 1 1]);
grating=exp(2i*pi*grating*orders(orderIdx));
grating=repmat(grating,[length(xRange) 1 1 1]);
sliceFft=fft2(slice.*grating); %,[],2);
sliceFft=sum(sliceFft,4); % Remove other orders
sliceFft=sliceFft.*repmat(ifftshift(fRel)<=1,[1 1 1 size(sliceFft,4)]); % Remove high frequency noise
order(:,:,1,orderIdx)=fft2(ifft2(sliceFft).*conj(grating(:,:,1,1))); % Shift back
end
deconvolvedSlice=ifft(deconvolvedSliceFft,[],2,'symmetric');
deconvolvedImg(:,:,zIdx)=deconvolvedSlice;
end
%
% Output
%
if (nargout==0)
fig=figure();
% for zIdx=1:size(sample,3),
% imagesc(xRange*1e6,yRange*1e6,sample(:,:,zIdx).');
% axis equal;
% title(zRange(zIdx)*1e6);
% drawnow();
% pause(.1);
% end
[X,Y,Z]=ndgrid(xRange,yRange,zRange);
[X,Y,Z, redSample]=reducevolume(X,Y,Z,smooth3(sample,'gaussian',11),[1 1 1]*2);
isoVal=double(max(redSample(:))/2);
fv=isosurface(X*1e6,Y*1e6,Z*1e6,redSample,isoVal);
fvCaps=isocaps(X*1e6,Y*1e6,Z*1e6,redSample,isoVal);
rfv=reducepatch(fv,0.1);
rfvCaps=reducepatch(fvCaps,0.1);
patch(rfv,'FaceColor',[1 0 0],'EdgeColor','none');
patch(rfvCaps,'FaceColor',[0.5 0 0],'EdgeColor','none');
axis equal;
lighting phong;
% shading interp;
camlight(30,30);
camlight(30+180,30);
% close(fig);
clear sample;
end
end
function sample=getSpiralDensity(xRange,yRange,zRange)
diameter=20e-6;
period=2*diameter;
tubeDiameter=10e-6;
thickness=1e-6;
nbSpirals=3;
innerR2=abs(tubeDiameter/2-thickness/2)^2;
outerR2=abs(tubeDiameter/2+thickness/2)^2;
% Make all horizontal
xRange=xRange(:).'; yRange=yRange(:).'; zRange=zRange(:).';
outputSize=[numel(xRange) numel(yRange) numel(zRange)];
sample=false(outputSize);
for xIdx=1:outputSize(1),
thetas=2*pi*(xRange(xIdx)/period+([1:nbSpirals].'-1)./nbSpirals);
spiralPos=[thetas*0 cos(thetas) sin(thetas)]*diameter/2;
inAnySpiral=false(outputSize(2:3));
for spiralIdx=1:size(spiralPos,1),
R2=repmat(abs(yRange-spiralPos(spiralIdx,2)).^2.',[1 outputSize(3)])+repmat(abs(zRange-spiralPos(spiralIdx,3)).^2,[outputSize(2) 1]);
inSpiral=R2>=innerR2 & R2<=outerR2;
inAnySpiral=inAnySpiral|inSpiral;
end
sample(xIdx,:,:)=inAnySpiral;
end
end
function sample=getTetraedronDensity(xRange,yRange,zRange)
diameter=20e-6;
thickness=1e-6;
centerOffset=[0 -5e-6 -2.5e-6];
% Make all horizontal
xRange=xRange(:).'; yRange=yRange(:).'; zRange=zRange(:).';
outputSize=[numel(xRange) numel(yRange) numel(zRange)];
innerR2=abs(diameter/2-thickness/2)^2;
outerR2=abs(diameter/2+thickness/2)^2;
sample=false(outputSize);
spherePos=[0 -1/sqrt(6) 2/sqrt(3); -1 -1/sqrt(6) -1/sqrt(3); 1 -1/sqrt(6) -1/sqrt(3); 0 sqrt(3/2) 0]*diameter/2;
spherePos=spherePos+repmat(centerOffset,[size(spherePos,1) 1]);
for xIdx=1:outputSize(1),
inAnyShell=false(outputSize(2:3));
for sphereIdx=1:size(spherePos,1),
R2=abs(xRange(xIdx)-spherePos(sphereIdx,1)).^2+...
repmat(abs(yRange-spherePos(sphereIdx,2)).^2.',[1 outputSize(3)])+repmat(abs(zRange-spherePos(sphereIdx,3)).^2,[outputSize(2) 1]);
inShell=R2>=innerR2 & R2<=outerR2;
inAnyShell=inAnyShell|inShell;
end
sample(xIdx,:,:)=inAnyShell;
end
sample=single(sample);
end
|
github
|
mc225/Softwares_Tom-master
|
previewLightSheetRecordings.m
|
.m
|
Softwares_Tom-master/LightSheet/previewLightSheetRecordings.m
| 4,212 |
utf_8
|
54901b2af67bbac18cf1165fc26d700c
|
%
% previewLightSheetRecordings(folders)
%
% Calls previewLightSheetRecording repeatedly
%
function previewLightSheetRecordings(folderNames,destinationEmails)
if (nargin<1 || isempty(folderNames))
folderNames={'H:\RESULTS\2013-11-27\Amphioxus'};
% folderNames={'H:\RESULTS\2013-11-27\Zebra fish','H:\RESULTS\2013-11-27\Spheroid'}; % Jonny: Please update the e-mail addresses below
% folderNames=uigetdir(pwd(),'Select Recording(s)');
% if (~iscell(folderNames) && ~ischar(folderNames) && ~isempty(folderNames))
% logMessage('Folder selection canceled.');
% return;
% end
end
if (~iscell(folderNames))
folderNames={folderNames};
end
if nargin<2
destinationEmails={'[email protected]','[email protected]','[email protected]'};
end
dataFileRegEx='recording_lambda([0-9]+)nm.+\.avi';
% Recursively process all folders
for folderName=folderNames,
folderName=folderName{1};
allFilesOrDirs=dir(folderName);
allDirs={allFilesOrDirs(cell2mat({allFilesOrDirs.isdir}) & cellfun(@(nm) nm(1)~='.',{allFilesOrDirs.name})).name};
allDataFiles={allFilesOrDirs(cellfun(@(nm) ~isempty(regexpi(nm,dataFileRegEx)),{allFilesOrDirs.name})).name};
allDirs=cellfun(@(nm) fullfile(folderName,nm),allDirs,'UniformOutput',false);
allDataFiles=cellfun(@(nm) fullfile(folderName,nm),allDataFiles,'UniformOutput',false);
% Go through subfolders and add to file list if it has a time stamp, otherwise recurse
for subDir=allDirs,
subDir=subDir{1};
if ~isempty(regexpi(subDir,'[0-9][0-9][0-9][0-9]+-[0-9][0-9]-[0-9][0-9] [0-9][0-9]_[0-9][0-9]_[0-9][0-9]\.[0-9][0-9]+$')) % If a time stamp
subFolderContents=dir(subDir);
subFolderContents={subFolderContents(cellfun(@(nm) ~isempty(regexpi(nm,dataFileRegEx)),{subFolderContents.name})).name};
subFolderContents=cellfun(@(nm) fullfile(subDir,nm),subFolderContents,'UniformOutput',false);
allDataFiles(end+[1:numel(subFolderContents)])=subFolderContents; % Append new found files
else
previewLightSheetRecordings(subDir,destinationEmails);
end
end
% Combine files by wavelength
allDataFileSets={};
for dataFileIdx=1:numel(allDataFiles),
dataFileSet={allDataFiles{dataFileIdx}}; % Still a single file at this point
% Check if there is also another wavelength version
wavelengthStr=regexpi(dataFileSet{1},dataFileRegEx,'tokens');
wavelengthStr=wavelengthStr{1}{1};
firstGreen=strcmp(wavelengthStr,'488');
if firstGreen,
otherWavelengthStr='532';
else
otherWavelengthStr='488';
end
fileToFind=strrep(dataFileSet{1},['lambda',wavelengthStr,'nm'],['lambda',otherWavelengthStr,'nm']);
clear otherWavelengthStr;
[~,fileToFind]=fileparts(fileToFind); %Use only the file name part
otherFileIdx=find(cellfun(@(nm) ~isempty(regexpi(nm,fileToFind)),allDataFiles),1);
if ~isempty(otherFileIdx)
if otherFileIdx>dataFileIdx
dataFileSet{2}=allDataFiles{otherFileIdx};
if ~firstGreen && numel(dataFileSet)>=2, % Make sure that green is first if it exists
dataFileSet=dataFileSet([2 1]);
end
allDataFileSets{end+1}=dataFileSet;
end
else
allDataFileSets{end+1}=dataFileSet;
end
end
% Process all the collected data files sets
for dataFileSetIdx=1:numel(allDataFileSets),
dataFileSet=allDataFileSets{dataFileSetIdx};
try
outputFullFileName=previewLightSheetRecording(dataFileSet);
logMessage('Just created %s.',outputFullFileName,destinationEmails,outputFullFileName);
catch Exc
Exc
logMessage('Could not process %s.',dataFileSet{1});
end
end
end
end
|
github
|
mc225/Softwares_Tom-master
|
deconvolveRecordedImageStack.m
|
.m
|
Softwares_Tom-master/LightSheet/deconvolveRecordedImageStack.m
| 8,273 |
utf_8
|
8c3ebf6ff4d3aa1207bbd66184ddea0a
|
% [restoredDataCube lightSheetDeconvFilter lightSheetOtf ZOtf xRange,yRange,zRange tRange lightSheetPsf]=deconvolveRecordedImageStack(recordedImageStack,config)
%
% recordedImageStack: The recorded values [x y z]=[down right back]
% config: a light sheet microscope set-up configuration file, including the wavelengths and the pupil functions.
%
function [restoredDataCube lightSheetDeconvFilter lightSheetOtf ZOtf xRange,yRange,zRange tRange lightSheetPsf]=deconvolveRecordedImageStack(recordedImageStack,config)
cubicInterpolation=true;
% Sample grid specification
stageTranslationStepSize=norm(median(diff(config.stagePositions.target)));
if isempty(config.detector.center)
config.detector.center=[0 0];
end
realMagnification=config.detection.objective.magnification*config.detection.tubeLength/config.detection.objective.tubeLength;
xRange=-config.detector.center(1)+config.detector.pixelSize(1)*([1:size(recordedImageStack,1)]-floor(size(recordedImageStack,1)/2)-1)/realMagnification; % up/down
yRange=-config.detector.center(2)+config.detector.pixelSize(2)*([1:size(recordedImageStack,2)]-floor(size(recordedImageStack,2)/2)-1)/realMagnification; % left/right
tRange=stageTranslationStepSize*([1:size(recordedImageStack,3)]-floor(size(recordedImageStack,3)/2+1))/config.detector.framesPerSecond; %Translation range (along z-axis)
zRange=tRange; % detection axis, zero centered
tilt=0;
logMessage('Calculating light sheet...');
lightSheetPsf=calcLightSheetPsf(single(xRange),single(yRange),single(zRange),tilt,config.excitation,config.modulation.alpha,config.modulation.beta,config.sample.refractiveIndex);
if (isfield(config.detector,'scanShear'))
scanShear=config.detector.scanShear;
else
scanShear=[0 0];
end
if (isfield(config.detector,'perspectiveScaling'))
scaling=config.detector.perspectiveScaling;
else
scaling=[0 0];
end
if (~all(scanShear==0) || ~all(scaling==0))
% Geometrically correcting recorded data cube and light sheet
lightSheetPsfOrig=lightSheetPsf;
logMessage('Geometrically shifting and deforming recorded date cube and light sheet by [%0.3f%%,%0.3f%%] and a magnification change of [%0.3f%%,%0.3f%%] per micrometer...',-[scanShear scaling*1e-6]*100);
% YRangeMatrix=repmat(yRange,[size(xRange,2) 1]);XRangeMatrix=repmat(xRange.',[1 size(yRange,2)]);
for (zIdx=1:size(recordedImageStack,3))
% [~, sV] = memory();
% logMessage('zIdx=%d, memory available: %0.0f MB',[zIdx sV.PhysicalMemory.Available/2^20]);
zPos=zRange(zIdx);
sampleXRange = scanShear(1)*zPos + xRange*(1-scaling(1)*zPos);
sampleYRange = scanShear(2)*zPos + yRange*(1-scaling(2)*zPos);
if (cubicInterpolation)
interpolatedSlice=interp2(yRange.',xRange,recordedImageStack(:,:,zIdx),sampleYRange.',sampleXRange,'*cubic',0);
else
interpolatedSlice=interp2(yRange.',xRange,recordedImageStack(:,:,zIdx),sampleYRange.',sampleXRange,'*linear',0);
% interpolatedSlice=qinterp2(YRangeMatrix,XRangeMatrix,recordedImageStack(:,:,zIdx),repmat(sampleYRange,[size(sampleXRange,2) 1]),repmat(sampleXRange.',[1 size(sampleYRange,2)]), 2);
% interpolatedSlice(isnan(interpolatedSlice))=0;
end
recordedImageStack(:,:,zIdx)=interpolatedSlice;
lightSheetPsf(:,:,zIdx)=interp1(yRange,lightSheetPsf(:,:,zIdx),sampleYRange,'*cubic',0);
end
end
logMessage('Reconstructing convolved data set...');
[recordedImageStack lightSheetDeconvFilter lightSheetOtf ZOtf tRange]=deconvolveLightSheet(xRange,yRange,zRange,tRange,recordedImageStack,config,lightSheetPsf);
restoredDataCube=recordedImageStack; clear recordedImageStack; % This operation does not take extra memory in Matlab
if (~all(scanShear==0) || ~all(scaling==0))
logMessage('Undoing the geometrically shifting and deformation of the date cube and light sheet by [%0.3f%%,%0.3f%%] and a magnification change of [%0.3f%%,%0.3f%%] per micrometer...',-[scanShear scaling*1e-6]*100);
for (tIdx=1:size(restoredDataCube,3))
tPos=tRange(tIdx);
sampleXRange = scanShear(1)*tPos + xRange*(1-scaling(1)*tPos);
sampleYRange = scanShear(2)*tPos + yRange*(1-scaling(2)*tPos);
if (cubicInterpolation)
interpolatedSlice=interp2(sampleYRange.',sampleXRange,restoredDataCube(:,:,tIdx),yRange.',xRange,'*cubic',0);
else
interpolatedSlice=interp2(sampleYRange.',sampleXRange,restoredDataCube(:,:,tIdx),yRange.',xRange,'*linear',0);
% interpolatedSlice=qinterp2(repmat(sampleYRange,[size(sampleXRange,2) 1]),repmat(sampleXRange.',[1 size(sampleYRange,2)]),restoredDataCube(:,:,tIdx),YRangeMatrix,XRangeMatrix, 2);
% interpolatedSlice(isnan(interpolatedSlice))=0;
end
recordedImageStack(:,:,tIdx)=interpolatedSlice;
end
lightSheetPsf=lightSheetPsfOrig;
end
end
%
% Deconvolution in Z after extending the last pixels outward. Note that the
% PSF should occupy maximum 1/2 of the total input z-range to avoid wrapping.
%
function [restoredDataCube lightSheetDeconvFilter lightSheetOtf ZOtf tRange]=deconvolveLightSheet(xRange,yRange,zRange,tRange,recordedImageStack,config,lightSheetPsf)
% Calculate an extended range over which the deconvolved image can be
% spread out due to the light sheet diffraction.
if (length(tRange)>1), dt=diff(tRange([1:2])); else dt=1; end
tRangePadded=tRange(floor(end/2)+1) + dt*([1:length(tRange)*2]-length(tRange)-1);
inputSize=size(recordedImageStack);
if (length(inputSize)<4)
if (length(inputSize)<3)
inputSize(3)=1;
end
inputSize(4)=1;
end
%Just (sub-pixel)-shift the PSF to the center and pad to double the size
if (length(zRange)>1)
lightSheetDeconvPsf=interp1(-zRange,squeeze(lightSheetPsf(floor(end/2)+1,:,:)).',tRangePadded,'*cubic',0).';
lightSheetDeconvPsf=permute(lightSheetDeconvPsf,[3 1 2]);
else
lightSheetDeconvPsf=lightSheetPsf;
lightSheetDeconvPsf(:,:,2)=0;
end
deconvSize=size(lightSheetDeconvPsf); deconvSize(2)=size(recordedImageStack,2);
%Deconvolve the light-sheet in Z
ZOtf=([1:deconvSize(3)]-floor(deconvSize(3)/2)-1)/(dt*deconvSize(3));
actualNumericalAperture=config.excitation.fractionOfNumericalApertureUsed*config.excitation.objective.numericalAperture;
excitationOpticalCutOffSpFreq=2*actualNumericalAperture/config.excitation.wavelength; % Independent of refractive index of medium
excitationNoiseToSignalRatio=config.sample.backgroundLevel*(ZOtf/excitationOpticalCutOffSpFreq)/config.sample.signalLevel;
lightSheetOtf=fftshift(fft(ifftshift(lightSheetDeconvPsf(1,:,:),3),[],3),3);
clear lightSheetDeconvPsf;
lightSheetOtf=lightSheetOtf./max(abs(lightSheetOtf(:))); % Maintain the mean brightness
%Construct the deconvolution filter:
lightSheetDeconvFilter=conj(lightSheetOtf)./(abs(lightSheetOtf).^2+repmat(permute(excitationNoiseToSignalRatio.^2,[1 3 2]),[size(lightSheetOtf,1) size(lightSheetOtf,2) 1]));
%Extend edges to double the size and convolve (slice by slice to avoid memory issues)
% restoredDataCube=zeros([inputSize(1:2), inputSize(3), inputSize(4:end)],'single'); % overwrite recordedImageStack instead to save memory
for (xIdx=1:size(recordedImageStack,1))
recordedImageStackSliceFft=fft(recordedImageStack(xIdx,:,[1:end, end*ones(1,floor(end/2)), ones(1,floor((end+1)/2))],:),[],3); % Extend edges
restoredDataCubeSlice=ifft(recordedImageStackSliceFft.*repmat(ifftshift(lightSheetDeconvFilter,3),[1 1 1 inputSize(4:end)]),[],3,'symmetric');
%Drop the bit that might have overlap from a wrapped kernel
recordedImageStack(xIdx,:,:,:)=restoredDataCubeSlice(:,:,1:end/2,:); % overwrite recordedImageStack to save memory
end
restoredDataCube=recordedImageStack; clear recordedImageStack; % This operation does not take extra memory in Matlab
end
|
github
|
mc225/Softwares_Tom-master
|
createResolutionPlot.m
|
.m
|
Softwares_Tom-master/LightSheet/createResolutionPlot.m
| 6,629 |
utf_8
|
172b08ac5b385c30f5181b644fc70966
|
function createResolutionPlot(inputFolder)
% close all;
% beamTypes={'Gaussian','Airy'};
if nargin<1 || isempty(inputFolder)
% inputFolder='C:\Users\Tom\Dropbox\AirySheetData\FWHMs\forwardscans2';
% inputFolder='C:\Users\Tom\Dropbox\AirySheetData\FWHMs\forwardscans';
% inputFolder='C:\Users\Tom\Dropbox\AirySheetData\FWHMs\backwardscans';
% inputFolder='C:\Users\Tom\Dropbox\AirySheetData\FWHMs\morePowerBackward';
beamTypes={'Bessel10','Bessel5'};
inputFolder='C:\Users\Tom\Dropbox\AirySheetData\FWHMs\morePowerForward';
end
description='';
for beamTypeIdx=1:length(beamTypes)
description=[description,'_',beamTypes{beamTypeIdx}];
end
outputFilePath=['C:\Users\Tom\Documents\nanoscope\docs\LightSheet\paper\figures\resolutionVsFOV\fwhmZOfBeads',description,'.svg'];
samples{1}=load(fullfile(inputFolder,['images',beamTypes{1},'.mat']));
samples{1}=samples{1}.samples;
samples{2}=load(fullfile(inputFolder,['images',beamTypes{2},'.mat']));
samples{2}=samples{2}.samples;
%Keep only those points that fall within the plot
positions=cell2mat({samples{1}.centroid}.');
inPlot=positions(:,1)>=-20e-6;
samples{1}=samples{1}(inPlot);
samples{2}=samples{2}(inPlot);
positions=positions(inPlot,:);
positions=cell2mat({samples{1}.centroid}.');
fwhm{1}=cell2mat({samples{1}.fwhm}.');
fwhm{2}=cell2mat({samples{2}.fwhm}.');
% distanceFromWaist=-positions(:,2);
distanceFromWaist=abs(positions(:,2));
fig=figure('Position',[50 50 800 300],'NumberTitle','off','Name',description);
ax=axes();
scatterGaussian=scatterV6(distanceFromWaist*1e6,fwhm{1}(:,3)*1e6,'x','MarkerEdgeColor',[1 0 0],'LineWidth',2);
hold on;
scatterAiry=scatterV6(distanceFromWaist*1e6,fwhm{2}(:,3)*1e6,50,[0 0.5 0],'filled');
hold off;
xlim([0 150]); ylim([0 25]);
labs(1)=xlabel('x [\mum]'); labs(2)=ylabel('FWHM [\mum]');
set(ax,'XTick',[0:25:1000]); set(ax,'YTick',[0:5:100]);
set(ax,'LineWidth',2);
set([ax labs],'FontSize',22,'FontWeight','bold','FontName','Arial');
set(labs,'FontSize',24);
set(ax,'Box','on');
drawnow();
%attach Callback
% set([scatterGaussian scatterAiry],'HitTest','off');
sampleMarkersGaussian=scatterGaussian; %get(scatterGaussian,'Children');
sampleMarkersAiry=scatterAiry; %get(scatterAiry,'Children');
set([sampleMarkersGaussian sampleMarkersAiry],'HitTest','on');
for sampleIdx=1:length(sampleMarkersGaussian)
bothMarkers=[sampleMarkersGaussian(sampleIdx) sampleMarkersAiry(sampleIdx)];
set(sampleMarkersGaussian(sampleIdx),'ButtonDownFcn',@(obj,evt) inspectSample(bothMarkers,'gaussian',sampleIdx,samples{1}(sampleIdx),samples{2}(sampleIdx)));
set(sampleMarkersAiry(sampleIdx),'ButtonDownFcn',@(obj,evt) inspectSample(bothMarkers,'airy',sampleIdx,samples{1}(sampleIdx),samples{2}(sampleIdx)));
end
uicontrol(fig,'Style','pushbutton','String','Save','Callback',@saveFigure,'UserData',outputFilePath);
set(fig,'ToolBar','figure');
zoom(fig);
end
function markers=scatterV6(X,Y,S,varargin)
nbMarkers=length(X);
maxMarkers=50;
markers=zeros(size(X));
for markerIdx=1:maxMarkers:nbMarkers
opts=varargin;
selI=markerIdx:min(nbMarkers,markerIdx+maxMarkers-1);
if all(ischar(S)) || isempty(opts) || all(isscalar(opts{1}))
scatterGroup=scatter(X(selI),Y(selI),S);
else
if (length(opts)>1 && strcmpi(opts{2},'filled'))
scatterGroup=scatter(X(selI),Y(selI),S,opts{1:2});
opts={opts{3:end}};
else
scatterGroup=scatter(X(selI),Y(selI),S,opts{1});
opts={opts{2:end}};
end
end
for (argIdx=1:2:length(opts)-1)
set(scatterGroup,opts{argIdx},opts{argIdx+1});
end
hold on;
newMarkers=get(scatterGroup,'Children');
markers(markerIdx-1+[1:length(newMarkers)])=newMarkers(end:-1:1); % Assume that the order is swapped!
end
hold off;
end
function saveFigure(obj,evt)
fig=get(obj,'Parent');
outputFilePath=get(obj,'UserData');
set(obj,'Visible','off');
logMessage('Writing figure to %s.',outputFilePath);
plot2svg(outputFilePath,fig);
set(obj,'Visible','on');
end
function inspectSample(sampleMarkers,sampleSet,sampleIdx,sampleG,sampleA)
description=sprintf([sampleSet ' sample %d, centroid=(%0.1f,%0.1f,%0.1f)um, FWHM=%0.0f and %0.0f nm'],[sampleIdx,sampleA.centroid*1e6 [sampleG.fwhm(3) sampleA.fwhm(3)]*1e9]);
logMessage(description);
colorMap=hot(1024);
inspectFig=figure('Position',[200 200 640 480]);
subplot(2,3,1);showImage(mapColor(sampleG.test.proj3./max(sampleG.test.proj3(:)),colorMap),[],sampleG.yRange*1e6,sampleG.xRange*1e6);axis equal;
xlabel('x (propagation) [um]'); ylabel('y (swipe) [um]');
subplot(2,3,2);showImage(mapColor(sampleG.test.proj2./max(sampleG.test.proj2(:)),colorMap),[],sampleG.yRange*1e6,sampleG.zRange*1e6); axis equal;
xlabel('x (propagation) [um]'); ylabel('z (scan) [um]');
subplot(2,3,3);showImage(mapColor(sampleG.test.proj1./max(sampleG.test.proj1(:)),colorMap),[],sampleG.xRange*1e6,sampleG.zRange*1e6); axis equal;
xlabel('y (swipe) [um]'); ylabel('z (scan) [um]');
subplot(2,3,4);showImage(mapColor(sampleA.test.proj3./max(sampleA.test.proj3(:)),colorMap),[],sampleA.yRange*1e6,sampleA.xRange*1e6);axis equal;
xlabel('x (propagation) [um]'); ylabel('y (swipe) [um]');
subplot(2,3,5);showImage(mapColor(sampleA.test.proj2./max(sampleA.test.proj2(:)),colorMap),[],sampleA.yRange*1e6,sampleA.zRange*1e6); axis equal;
xlabel('x (propagation) [um]'); ylabel('z (scan) [um]');
subplot(2,3,6);showImage(mapColor(sampleA.test.proj1./max(sampleA.test.proj1(:)),colorMap),[],sampleA.xRange*1e6,sampleA.zRange*1e6); axis equal;
xlabel('y (swipe) [um]'); ylabel('z (scan) [um]');
set(inspectFig,'NumberTitle','off','Name',description);
set(inspectFig,'ToolBar','figure');
zoom(inspectFig);
drawnow();
keepAction=@(obj,evt) close(inspectFig);
uicontrol(inspectFig,'Style','pushbutton','String','Keep','Position',[10 10 50 20],'Callback',keepAction);
uicontrol(inspectFig,'Style','pushbutton','String','Remove','Position',[80 10 50 20],'Callback',@(obj,evt) removeMarkers(sampleMarkers,inspectFig));
end
function removeMarkers(sampleMarkers,inspectFig)
set(sampleMarkers,'Visible','off');
close(inspectFig);
end
|
github
|
mc225/Softwares_Tom-master
|
plotFieldOfViewWidthAndAxialResolutionVersusNA.m
|
.m
|
Softwares_Tom-master/LightSheet/plotFieldOfViewWidthAndAxialResolutionVersusNA.m
| 8,351 |
utf_8
|
f4eb96474608903a149d69fba59c96a2
|
% [numericalApertures,FOVWidths,axialResolutions]=plotFieldOfViewWidthAndAxialResolutionVersusNA(refractiveIndex,wavelength)
%
% Calculates the field of view and axial resolution of a light sheet microscope as a function of the illumination NA.
%
% All SI units.
%
function [numericalApertures,FOVWidths,axialResolutions]=plotFieldOfViewWidthAndAxialResolutionVersusNA(refractiveIndex,wavelength)
close all;
if (nargin<1 || isempty(refractiveIndex))
refractiveIndex=1.4;
end
if (nargin<2 || isempty(wavelength))
wavelength=532e-9;
end
numericalApertures=.001:.001:(refractiveIndex/1);
alpha=7;
betas=[0.10 0.05];
fontSize=24;
lineColors=[.33 .33 .33; 0.2 0.2 0.8; 0.8 0 0; 0 .67 0];
lineStyles={':','-','--','-'};
lineWidths=[2 3 2 3];
% Calculate
FOVGaussian=4*wavelength*refractiveIndex*numericalApertures.^-2;
axialResolutionGaussian=wavelength./(2*numericalApertures*0.88);
FOVBessel10=(wavelength/refractiveIndex)./(2*(1-sqrt(1-(numericalApertures/refractiveIndex).^2))*betas(1));
axialResolutionBessel10=wavelength*pi*.05./(numericalApertures*betas(1));
FOVBessel5=(wavelength/refractiveIndex)./(2*(1-sqrt(1-(numericalApertures/refractiveIndex).^2))*betas(2));
axialResolutionBessel5=wavelength*pi*.05./(numericalApertures*betas(2));
FOVAiry=(6*alpha*wavelength/refractiveIndex)./(1-sqrt(1-(numericalApertures/refractiveIndex).^2));
maxSpFreqAiry=min(0.88,1/(0.05^2*48*alpha)).*numericalApertures/(wavelength/2);
axialResolutionAiry=1./maxSpFreqAiry;
maxDetectionNAs=refractiveIndex*sin(pi/2-asin(numericalApertures/refractiveIndex));
maxDetectionNAs=maxDetectionNAs*0+0.40;
spotLengths=4*refractiveIndex*wavelength./(maxDetectionNAs.^2);
pixelSize=[1 1]*7.4e-6;
realMagnification=20*0.176/0.160;
depthOfFocus=refractiveIndex*(wavelength./(maxDetectionNAs.^2)+pixelSize(1)./(realMagnification.*maxDetectionNAs));
% FOVWidths_old=2*wavelength*sqrt(1-(numericalApertures./refractiveIndex).^2)*refractiveIndex./(2*sqrt(2)*numericalApertures.^2);
FOVWidths=4*wavelength*refractiveIndex./numericalApertures.^2;
axialResolutions=wavelength/2./numericalApertures;
if (nargout==0)
% Display results
figs(1)=figure('Position',[100 100 1024 768]);
axs(1)=subplot(2,2,1,'Parent',figs(1));
axs(2)=subplot(2,2,2,'Parent',figs(1));
axs(3)=subplot(2,2,[3 4],'Parent',figs(1));
labels=[];
semilogy(numericalApertures,axialResolutionGaussian*1e6,lineStyles{1},'LineWidth',lineWidths(1),'Color',lineColors(1,:),'Parent',axs(1)); hold(axs(1),'on');
semilogy(numericalApertures,axialResolutionBessel10*1e6,lineStyles{2},'LineWidth',lineWidths(2),'Color',lineColors(2,:),'Parent',axs(1)); hold(axs(1),'on');
semilogy(numericalApertures,axialResolutionBessel5*1e6,lineStyles{3},'LineWidth',lineWidths(3),'Color',lineColors(3,:),'Parent',axs(1)); hold(axs(1),'on');
semilogy(numericalApertures,axialResolutionAiry*1e6,lineStyles{4},'LineWidth',lineWidths(4),'Color',lineColors(4,:),'Parent',axs(1)); hold(axs(1),'on');
semilogy(numericalApertures,axialResolutionGaussian*1e6,lineStyles{1},'LineWidth',lineWidths(1),'Color',lineColors(1,:),'Parent',axs(1)); hold(axs(1),'on');
% semilogy(numericalApertures,spotLengths*1e6,':','LineWidth',2,'Color',[1 1 1]*.33,'Parent',axs(1)); hold(axs(1),'on');
xlim(axs(1),[0 numericalApertures(end)]); ylim(axs(1),[.1 500]);
set(axs(1),'YTick',10.^[0:1:100]);
labels(end+1)=xlabel(axs(1),'NA');
labels(end+1)=ylabel(axs(1),'Axial Resolution [\mum]');
legend(axs(1),{'Gaussian','Bessel10','Bessel5','Airy'});
semilogy(numericalApertures,FOVGaussian*1e6,lineStyles{1},'LineWidth',lineWidths(1),'Color',lineColors(1,:),'Parent',axs(2)); hold(axs(2),'on');
semilogy(numericalApertures,FOVBessel10*1e6,lineStyles{2},'LineWidth',lineWidths(2),'Color',lineColors(2,:),'Parent',axs(2)); hold(axs(2),'on');
semilogy(numericalApertures,FOVBessel5*1e6,lineStyles{3},'LineWidth',lineWidths(3),'Color',lineColors(3,:),'Parent',axs(2)); hold(axs(2),'on');
semilogy(numericalApertures,FOVAiry*1e6,lineStyles{4},'LineWidth',lineWidths(4),'Color',lineColors(4,:),'Parent',axs(2)); hold(axs(2),'on');
xlim(axs(2),[0 numericalApertures(end)]); ylim(axs(2),[.1 500]);
set(axs(2),'YTick',10.^[0:1:100]);
labels(end+1)=xlabel(axs(2),'NA');
labels(end+1)=ylabel(axs(2),'FOV Width [\mum]');
legend(axs(2),{'Gaussian','Bessel10','Bessel5','Airy'});
% loglog(axialResolutionGaussian*1e6,FOVGaussian*1e6,lineStyles{1},'LineWidth',lineWidths(1),'Color',lineColors(1,:),'Parent',axs(3)); hold(axs(3),'on');
% loglog(axialResolutionBessel10*1e6,FOVBessel10*1e6,lineStyles{2},'LineWidth',lineWidths(2),'Color',[0.8 0.2 0.2],'Parent',axs(3)); hold(axs(3),'on');
% loglog(axialResolutionBessel5*1e6,FOVBessel5*1e6,lineStyles{3},'LineWidth',lineWidths(3),'Color',lineColors(3,:),'Parent',axs(3)); hold(axs(3),'on');
% loglog(axialResolutionAiry*1e6,FOVAiry*1e6,lineStyles{4},'LineWidth',lineWidths(4),'Color',lineColors(4,:),'Parent',axs(3)); hold(axs(3),'on');
plot(FOVGaussian*1e6,axialResolutionGaussian*1e6,lineStyles{1},'LineWidth',lineWidths(1),'Color',lineColors(1,:),'Parent',axs(3)); hold(axs(3),'on');
plot(FOVBessel10*1e6,axialResolutionBessel10*1e6,lineStyles{2},'LineWidth',lineWidths(2),'Color',lineColors(2,:),'Parent',axs(3)); hold(axs(3),'on');
plot(FOVBessel5*1e6,axialResolutionBessel5*1e6,lineStyles{3},'LineWidth',lineWidths(3),'Color',lineColors(3,:),'Parent',axs(3)); hold(axs(3),'on');
plot(FOVAiry*1e6,axialResolutionAiry*1e6,lineStyles{4},'LineWidth',lineWidths(4),'Color',lineColors(4,:),'Parent',axs(3)); hold(axs(3),'on');
xlim(axs(3),[0 1000]); ylim(axs(3),[0 10]);
set(axs(3),'YTick',[0:1:100]);
labels(end+1)=xlabel(axs(3),'FOV Width [\mum]');
labels(end+1)=ylabel(axs(3),'Axial Resolution [\mum]');
legend(axs(3),{'Gaussian','Bessel10','Bessel5','Airy'},'Parent',figs(1));
set(axs,'LineWidth',3,'FontSize',fontSize,'FontWeight','bold');
set(labels,'FontSize',fontSize,'FontWeight','bold');
% figs(1)=figure('Position',[100 100 1024 768]);
% axs(1)=axes('Parent',figs(1));
% % Add horizontal gray lines
% horizontalLinePositions=[.5 1 5 10 50 100];
% semilogy(repmat([0 refractiveIndex].',size(horizontalLinePositions)),repmat(horizontalLinePositions,[2 1]),'LineWidth',lineWidths(1)1,'Color',[0.8 0.8 0.8],'Parent',axs(1));
% hold(axs(1),'on');
% semilogy(numericalApertures,FOVWidths*1e6,'LineWidth',lineWidths(1)3,'Color',lineColors(1,:),'Parent',axs(1));
% semilogy(numericalApertures,axialResolutions*1e6,'LineWidth',lineWidths(1)2,'Color',[0 .33 0],'Parent',axs(1));
% xlim([0 refractiveIndex]);
% ylim([.1 500]);
% xlabel('NA','FontSize',fontSize,'FontWeight','bold');
% ylabel('FOV width and axial resolution [\mum]','FontSize',fontSize,'FontWeight','bold');
% legend({'Gaussian FOV Width','Gaussian axial resolution'});
% hold off;
% set(axs(1),'LineWidth',lineWidths(1)3,'FontSize',fontSize,'FontWeight','bold');
% set(axs(1),'XTick',[0:.2:10]);
%
% figs(2)=figure('Position',[100 100 1024 768]);
% axs(2)=axes('Parent',figs(2));
% hold(axs(1),'on');
% plot(FOVWidths*1e6,axialResolutions*1e6,'LineWidth',lineWidths(1)3,'Color',lineColors(1,:),'Parent',axs(2));
% xlim([0 5]);
% % ylim([0 500]);
% xlabel('FOV width and axial resolution [\mum]','FontSize',fontSize,'FontWeight','bold');
% ylabel('approx. light sheet width [\mum]','FontSize',fontSize,'FontWeight','bold');
% legend({'Gaussian'});
% hold off;
% set(axs(2),'LineWidth',lineWidths(1)3,'FontSize',fontSize,'FontWeight','bold');
% set(axs(2),'XTick',[0:1:10]);
%
% print(figs(1),'plotFieldOfViewWidthAndAxialResolutionVersusNA.eps','-depsc')
% print(figs(2),'plotFieldOfViewWidthVersusAxialResolution.eps','-depsc')
clear numericalApertures;
end
end
|
github
|
mc225/Softwares_Tom-master
|
extractSubVolumeThenProject_2Colors.m
|
.m
|
Softwares_Tom-master/LightSheet/extractSubVolumeThenProject_2Colors.m
| 2,408 |
utf_8
|
ae6e05fdafcae2535c8b4859b603461f
|
% Takes a subvolume out of corresponding red and green datacubes, makes a
% maximum intensity projection of the 2 subvolumes, applies the
% corresponding colormaps to the data and combines in a 3-colour image.
% Can also output the normalisation factors used to allow the same
% normalisation to be used across multiple images.
function [TwoColorImage,normalisation]=extractSubVolumeThenProject_2Colors(dataType,alpha,beta,subVolume_x,subVolume_y,subVolume_z,transpose,normalisation)
fileName_g=strcat('recording_lambda488nm_alpha',num2str(alpha),'_beta',num2str(beta));
fileName_r=strcat('recording_lambda532nm_alpha',num2str(alpha),'_beta',num2str(beta));
matfile_g=matfile(fileName_g);
matfile_r=matfile(fileName_r);
%guess the projection direction - minimum sized dimension
subVolumeSize=[length(subVolume_x),length(subVolume_y),length(subVolume_z)];
if min(subVolumeSize)==length(subVolume_x)
ProjectionGuess=1;
elseif min(subVolumeSize)==length(subVolume_y)
ProjectionGuess=2;
elseif min(subVolumeSize)==length(subVolume_z)
ProjectionGuess=3;
end
if strcmp(dataType,'deconv')==1
image_g=squeeze(max(matfile_g.restoredDataCube(subVolume_x,subVolume_y,subVolume_z),[],ProjectionGuess));
image_r=squeeze(max(matfile_r.restoredDataCube(subVolume_x,subVolume_y,subVolume_z),[],ProjectionGuess));
elseif strcmp(dataType,'record')==1
image_g=squeeze(max(matfile_g.recordedImageStack(subVolume_x,subVolume_y,subVolume_z),[],ProjectionGuess));
image_r=squeeze(max(matfile_r.recordedImageStack(subVolume_x,subVolume_y,subVolume_z),[],ProjectionGuess));
end
if strcmp(transpose,'Y_transp')==1
image_g=image_g.';
image_r=image_r.';
end
image_g=image_g.*(image_g>0);
image_r=image_r.*(image_r>0);
if size(normalisation~=[1 2]);
normalisation=zeros(1,2);
normalisation(1)=max(image_g(:));
normalisation(2)=max(image_r(:));
end
image_g=image_g./normalisation(1);
image_r=image_r./normalisation(2);
colorMap=interpolatedColorMap(1024,[0 0 0; 0 .8 0; 1 1 1],[0 .5 1]);
image_g_RGB=mapColor(image_g,colorMap);
colorMap=interpolatedColorMap(1024,[0 0 0; .8 0 0; 1 1 1],[0 .5 1]);
image_r_RGB=mapColor(image_r,colorMap);
image_RGB=image_r_RGB+image_g_RGB;
TwoColorImage=min(1,image_RGB);
end
|
github
|
mc225/Softwares_Tom-master
|
compareBeamProfiles.m
|
.m
|
Softwares_Tom-master/LightSheet/compareBeamProfiles.m
| 18,256 |
utf_8
|
ed79ad33dfda4e0606a2269708108d80
|
%
%
function compareBeamProfiles()
close all;
config=struct();
config.excitation=struct();
config.excitation.objective=struct();
config.excitation.objective.refractiveIndex=1.00;
config.excitation.objective.numericalAperture=0.42;
config.excitation.objective.magnification=20;
config.excitation.objective.tubeLength=0.200;
config.excitation.wavelength=532e-9;
config.excitation.fractionOfNumericalApertureUsed=1;
config.sample.refractiveIndex=1.40;
config.detection=struct();
config.detection.objective=struct();
config.detection.objective.refractiveIndex=1.00;
config.detection.objective.numericalAperture=0.40;
config.detection.objective.magnification=20;
config.detection.objective.tubeLength=0.160;
config.detection.tubeLength=0.176;
config.detection.wavelength=600e-9; %6.12e-7;
config.detection.fractionOfNumericalApertureUsed=1;
config.detector=struct();
config.detector.pixelSize=[1 1]*7.4e-6;
% coreWidthBessel=2*config.excitation.wavelength/(2*config.excitation.objective.numericalAperture);
% coreWidthBessel=2*config.excitation.wavelength/(2*config.excitation.objective.numericalAperture*0.88); %2*0.720e-6;
coreWidthBessel=2*2.4048255576957727686216318793264546431242449091459671*config.excitation.wavelength/(2*pi*config.excitation.objective.numericalAperture);
realMagnification=config.detection.objective.magnification*config.detection.tubeLength/config.detection.objective.tubeLength;
depthOfFocus=config.sample.refractiveIndex*(config.detection.wavelength/(config.detection.objective.numericalAperture^2)+...
config.detector.pixelSize(1)/(realMagnification*config.detection.objective.numericalAperture));
spotLength=4*config.sample.refractiveIndex*config.detection.wavelength/(config.detection.objective.numericalAperture^2);
% Gaussian
resGaussian=plotUsefulPhotonFraction(config,0,1,spotLength);
% Airy
resAiry=plotUsefulPhotonFraction(config,7,1,spotLength);
% Bessel 10
resBessel10=plotUsefulPhotonFraction(config,0,0.10,[coreWidthBessel spotLength]);
% Bessel 5
resBessel5=plotUsefulPhotonFraction(config,0,0.05,[coreWidthBessel spotLength]);
% Bessel 2
resBessel2=plotUsefulPhotonFraction(config,0,0.02,[coreWidthBessel spotLength]);
% Bessel 1
resBessel1=plotUsefulPhotonFraction(config,0,0.01,[coreWidthBessel spotLength]);
% % Show two-photon MTF plots
% figure;
% plot(resGaussian.fRel2Slice,abs(resGaussian.otf2Slice),'Color',[.5 .5 .5]); hold on;
% plot(resAiry.fRel2Slice,abs(resAiry.otf2Slice),'Color',[0 .8 0]); hold on;
% plot(resBessel10(1).fRel2Slice,abs(resBessel10(1).otf2Slice),'Color',[.3 0 0]); hold on;
% plot(resBessel5(1).fRel2Slice,abs(resBessel5(1).otf2Slice),'Color',[.5 0 0]); hold on;
% plot(resBessel2(1).fRel2Slice,abs(resBessel2(1).otf2Slice),'Color',[.7 0 0]); hold on;
% plot(resBessel1(1).fRel2Slice,abs(resBessel1(1).otf2Slice),'Color',[1 0 0]); hold on;
% Display
fig=figure();
plot(resGaussian.zRange*1e6,resGaussian.focalPlaneEfficiency(:,1),'Color',[0 0 0],'LineWidth',2);
hold on;
plot(resAiry.zRange*1e6,resAiry.focalPlaneEfficiency(:,1),'Color',[0 .5 0],'LineWidth',3);
plot(resBessel10(1).zRange*1e6,resBessel10(1).focalPlaneEfficiency(:,1),'Color',[1 0 0],'LineWidth',2,'LineStyle','--');
plot(resBessel5(1).zRange*1e6,resBessel5(1).focalPlaneEfficiency(:,1),'Color',[.75 0 .75],'LineWidth',1,'LineStyle','--');
plot(resBessel2(1).zRange*1e6,resBessel2(1).focalPlaneEfficiency(:,1),'Color',[0 1 .5],'LineWidth',1,'LineStyle','--');
plot(resBessel1(1).zRange*1e6,resBessel1(1).focalPlaneEfficiency(:,1),'Color',[0 0 1],'LineWidth',2,'LineStyle','--');
plot(resBessel10(1).zRange*1e6,resBessel10(1).coreEfficiency(:,1),'Color',[1 0 0],'LineWidth',2,'LineStyle',':');
plot(resBessel5(1).zRange*1e6,resBessel5(1).coreEfficiency(:,1),'Color',[.75 0 .75],'LineWidth',1,'LineStyle',':');
plot(resBessel2(1).zRange*1e6,resBessel2(1).coreEfficiency(:,1),'Color',[0 1 .5],'LineWidth',1,'LineStyle',':');
plot(resBessel1(1).zRange*1e6,resBessel1(1).coreEfficiency(:,1),'Color',[0 0 1],'LineWidth',2,'LineStyle',':');
plot(resBessel2(1).zRange*1e6,resBessel2(1).focalPlaneEfficiency(:,2),'Color',[0 1 .5],'LineWidth',2,'LineStyle','-.');
plot(resBessel1(1).zRange*1e6,resBessel1(1).focalPlaneEfficiency(:,2),'Color',[0 0 1],'LineWidth',2,'LineStyle','-.');
xlim(resBessel1(1).zRange([1 end])*1e6); ylim([0 1]);
legend({'Gaussian','Airy','Bessel10-SI','Bessel5-SI','Bessel2-SI','Bessel1-SI',...
'Bessel10-conf','Bessel5-conf','Bessel2-conf','Bessel1-conf','Bessel2-2PE','Bessel1-2PE'});
FOVs=[resGaussian.FOV resAiry.FOV...
repmat([resBessel10(1).FOV resBessel5(1).FOV resBessel2(1).FOV resBessel1(1).FOV],[1 3])...
resBessel10(1).FOV2PE resBessel5(1).FOV2PE resBessel2(1).FOV2PE resBessel1(1).FOV2PE];
FWHMs=[resGaussian(1).fullWidthAtHalfMaximumAtWaist resAiry(1).fullWidthAtHalfMaximumAtWaist...
resBessel10(2).fullWidthAtHalfMaximumAtWaist resBessel5(2).fullWidthAtHalfMaximumAtWaist resBessel2(2).fullWidthAtHalfMaximumAtWaist resBessel1(2).fullWidthAtHalfMaximumAtWaist...
resBessel10(1).fullWidthAtHalfMaximumAtWaist resBessel5(1).fullWidthAtHalfMaximumAtWaist resBessel2(1).fullWidthAtHalfMaximumAtWaist resBessel1(1).fullWidthAtHalfMaximumAtWaist...
resBessel10(1).fullWidthAtHalfMaximumAtWaist resBessel5(1).fullWidthAtHalfMaximumAtWaist resBessel2(1).fullWidthAtHalfMaximumAtWaist resBessel1(1).fullWidthAtHalfMaximumAtWaist...
resBessel10(2).fullWidthAtHalfMaximumAtWaist2PE resBessel5(2).fullWidthAtHalfMaximumAtWaist2PE resBessel2(2).fullWidthAtHalfMaximumAtWaist2PE resBessel1(2).fullWidthAtHalfMaximumAtWaist2PE...
];
waistEfficiencies=[resGaussian.focalPlaneEfficiency(1,1) resAiry.focalPlaneEfficiency(1,1)...
resBessel10(2).focalPlaneEfficiency(1,1) resBessel5(2).focalPlaneEfficiency(1,1) resBessel2(2).focalPlaneEfficiency(1,1) resBessel1(2).focalPlaneEfficiency(1,1)...
resBessel10(1).focalPlaneEfficiency(1,1) resBessel5(1).focalPlaneEfficiency(1,1) resBessel2(1).focalPlaneEfficiency(1,1) resBessel1(1).focalPlaneEfficiency(1,1)...
resBessel10(1).coreEfficiency(1,1) resBessel5(1).coreEfficiency(1,1) resBessel2(1).coreEfficiency(1,1) resBessel1(1).coreEfficiency(1,1)...
resBessel10(2).focalPlaneEfficiency(1,2) resBessel5(2).focalPlaneEfficiency(1,2) resBessel2(2).focalPlaneEfficiency(1,2) resBessel1(2).focalPlaneEfficiency(1,2)];
averageEfficiencies=[resGaussian.averageFocalPlaneEfficiency(1) resAiry.averageFocalPlaneEfficiency(1)...
resBessel10(2).averageFocalPlaneEfficiency(1) resBessel5(2).averageFocalPlaneEfficiency(1) resBessel2(2).averageFocalPlaneEfficiency(1) resBessel1(2).averageFocalPlaneEfficiency(1)...
resBessel10(1).averageFocalPlaneEfficiency(1) resBessel5(1).averageFocalPlaneEfficiency(1) resBessel2(1).averageFocalPlaneEfficiency(1) resBessel1(1).averageFocalPlaneEfficiency(1)...
resBessel10(1).averageCoreEfficiency(1) resBessel5(1).averageCoreEfficiency(1) resBessel2(1).averageCoreEfficiency(1) resBessel1(1).averageCoreEfficiency(1)...
resBessel10(1).averageCoreEfficiency(2) resBessel5(1).averageCoreEfficiency(2) resBessel2(1).averageCoreEfficiency(2) resBessel1(1).averageCoreEfficiency(2)];
axialResolution=[resGaussian(1).axialResolution resAiry(1).axialResolution...
resBessel10(2).axialResolution resBessel5(2).axialResolution resBessel2(2).axialResolution resBessel1(2).axialResolution...
resBessel10(1).axialResolution resBessel5(1).axialResolution resBessel2(1).axialResolution resBessel1(1).axialResolution...
resBessel10(1).axialResolution resBessel5(1).axialResolution resBessel2(1).axialResolution resBessel1(1).axialResolution...
resBessel10(2).axialResolution resBessel5(2).axialResolution resBessel2(2).axialResolution resBessel1(2).axialResolution];
numericalAxialResolution=[resGaussian(1).axialResolution1PE resAiry(1).axialResolution1PE...
resBessel10(2).axialResolution1PE resBessel5(2).axialResolution1PE resBessel2(2).axialResolution1PE resBessel1(2).axialResolution1PE...
resBessel10(1).axialResolution resBessel5(1).axialResolution resBessel2(1).axialResolution resBessel1(1).axialResolution...
resBessel10(1).axialResolution resBessel5(1).axialResolution resBessel2(1).axialResolution resBessel1(1).axialResolution...
resBessel10(2).axialResolution2PE resBessel5(2).axialResolution2PE resBessel2(2).axialResolution2PE resBessel1(2).axialResolution2PE];
peakValues=[resGaussian(1).peakValueAtWaist resAiry(1).peakValueAtWaist...
resBessel10(2).peakValueAtWaist resBessel5(2).peakValueAtWaist resBessel2(2).peakValueAtWaist resBessel1(2).peakValueAtWaist...
resBessel10(1).peakValueAtWaist resBessel5(1).peakValueAtWaist resBessel2(1).peakValueAtWaist resBessel1(1).peakValueAtWaist...
resBessel10(1).peakValueAtWaist resBessel5(1).peakValueAtWaist resBessel2(1).peakValueAtWaist resBessel1(1).peakValueAtWaist...
resBessel10(2).peakValueAtWaist2PE resBessel5(2).peakValueAtWaist2PE resBessel2(2).peakValueAtWaist2PE resBessel1(2).peakValueAtWaist2PE];
peakValues=peakValues/peakValues(1);
relativePeakValues=peakValues./waistEfficiencies;
relativePeakValues=relativePeakValues/relativePeakValues(1);
logMessage(['Light Sheet Type: Gaussian, Airy, Bessel10, Bessel5, Bessel2, Bessel1, Bessel10-SI, Bessel5-SI, Bessel2-SI, Bessel1-SI, Bessel10-conf, Bessel5-conf, Bessel2-conf, Bessel1-conf, Bessel10-2PE, Bessel5-2PE, Bessel2-2PE, Bessel1-2PE']);
logMessage(['FOV: ', sprintf('%0.0f ',FOVs*1e6),'um']);
logMessage(['FWHMs: ', sprintf('%0.0f ',FWHMs*1e9),'nm']);
logMessage(['half-FOV: ', sprintf('%0.0f ',0.5*FOVs*1e6),'um']);
logMessage(['waistEfficiencies: ', sprintf('%0.1f ',waistEfficiencies*100),'%']);
logMessage(['averageEfficiencies: ', sprintf('%0.1f ',averageEfficiencies*100),'%']);
logMessage(['theoretical axial resolution: ', sprintf('%0.0f ',axialResolution*1e9),'nm']);
logMessage(['numerical axial resolution: ', sprintf('%0.0f ',numericalAxialResolution*1e9),'nm']);
logMessage(['peak value: ', sprintf('%0.1f ',100*peakValues),'%']);
logMessage(['relative peak value: ', sprintf('%0.1f ',100*relativePeakValues),'%']);
end
function results=plotUsefulPhotonFraction(config,alpha,beta,coreWidths)
results=struct([]);
result=struct();
% Calculate the theorectical FOV
if beta<1
% Bessel beam
result.FOV=config.excitation.wavelength/config.sample.refractiveIndex/(2*(1-sqrt(1-(config.excitation.objective.numericalAperture/config.sample.refractiveIndex)^2))*beta);
axialResolution=config.excitation.wavelength*pi*.05/(config.excitation.objective.numericalAperture*beta);
axialResolution2PE=config.excitation.wavelength*pi*.05/(config.excitation.objective.numericalAperture*beta);
elseif alpha~=0
% Airy
result.FOV=6*alpha*config.excitation.wavelength/config.sample.refractiveIndex/(1-sqrt(1-(config.excitation.objective.numericalAperture/config.sample.refractiveIndex)^2));
maxSpFreq=min(0.88,1/(0.05^2*48*alpha))*config.excitation.objective.numericalAperture/(config.excitation.wavelength/2);
axialResolution=1./maxSpFreq;
else
% Gaussian
result.FOV=4*config.excitation.wavelength*config.sample.refractiveIndex*config.excitation.objective.numericalAperture^-2;
axialResolution=config.excitation.wavelength/(2*config.excitation.objective.numericalAperture*0.88);
end
result.FOV2PE=2*result.FOV;
result.xRange=single([-75:.05:75]*1e-6);
result.yRange=result.xRange;
result.zRange=single([0:.05:1]*result.FOV/2);
config.modulation.alpha=alpha;
config.modulation.beta=beta;
pupilFunctor=@(U,V) (sqrt(U.^2+V.^2)>=(1-config.modulation.beta)).*exp(2i*pi*config.modulation.alpha*(U.^3+V.^3));
cache=Cache(); % Get the default cache
key={result.zRange,result.zRange,result.yRange,config,1/sqrt(2),1i/sqrt(2)};
if (isfield(cache,key))
logMessage('Loading PSF projection from cache...');
psf=cache(key);
else
psf=calcVectorialPsf(result.xRange,result.yRange,result.zRange,config.excitation.wavelength,@(U,V) pupilFunctor(U,V)/sqrt(2),@(U,V) 1i*pupilFunctor(U,V)/sqrt(2),config.excitation.objective.numericalAperture,config.sample.refractiveIndex,config.excitation.objective.magnification,config.excitation.objective.tubeLength);
cache(key)=psf;
end
% Calc PSF projection and OTF slice
result.psfAtWaist=sum(psf(:,:,1));
result.fullWidthAtHalfMaximumAtWaist=calcFullWidthAtHalfMaximum(result.xRange,result.psfAtWaist,'Linear');
result.fullWidthAtHalfMaximumAtWaist2PE=calcFullWidthAtHalfMaximum(result.xRange*2,abs(result.psfAtWaist).^2,'Linear');
cutOffSpatialFrequency=(2*config.excitation.objective.numericalAperture*config.excitation.fractionOfNumericalApertureUsed)/config.excitation.wavelength;
[XOtf,YOtf,fRel]=calcOtfGridFromSampleFrequencies(1./[diff(result.xRange(1:2)) diff(result.yRange(1:2))],[length(result.xRange) length(result.yRange)],cutOffSpatialFrequency);
otf=fftshift(fft2(ifftshift(psf(:,:,1))));
otf2=fftshift(fft2(ifftshift(abs(psf(:,:,1)).^2)));
otf2=otf2/otf2(1+floor(end/2),1+floor(end/2));
fRelSel=single(any(fRel.'<=1).')*single(any(fRel<=1));
fRelSel2=single(any(fRel.'<=2).')*single(any(fRel<=2));
selSize=[sum(any(fRel.'<=1)) sum(any(fRel<=1))];
selSize2=[sum(any(fRel.'<=2)) sum(any(fRel<=2))];
otf=reshape(otf(logical(fRelSel)),selSize);
otf2=reshape(otf2(logical(fRelSel2)),selSize2);
XOtf2=0.5*reshape(XOtf(logical(fRelSel2)),selSize2);
XOtf=reshape(XOtf(logical(fRelSel)),selSize);
fRel2=0.5*reshape(fRel(logical(fRelSel2)),selSize2);
fRel=reshape(fRel(logical(fRelSel)),selSize);
result.otfSlice=conj(otf(1+floor(end/2),1+floor(end/2):-1:1));
result.otf2Slice=conj(otf2(1+floor(end/2),1+floor(end/2):-1:1));
result.XOtfSlice=-XOtf(1+floor(end/2),1+floor(end/2):-1:1);
result.XOtf2Slice=-XOtf2(1+floor(end/2),1+floor(end/2):-1:1);
result.fRelSlice=fRel(1+floor(end/2),1+floor(end/2):-1:1);
result.fRel2Slice=fRel2(1+floor(end/2),1+floor(end/2):-1:1);
result.peakValueAtWaist=max(result.psfAtWaist/sum(result.psfAtWaist));
result.peakValueAtWaist2PE=max(abs(result.psfAtWaist).^2/sum(abs(result.psfAtWaist).^2));
maxSpFreq1PE=result.XOtfSlice(find(abs(result.otfSlice)/max(abs(result.otfSlice))<.05,1,'first')-1);
result.axialResolution1PE=1/maxSpFreq1PE;
maxSpFreq2PE=result.XOtf2Slice(find(abs(result.otf2Slice)/max(abs(result.otf2Slice))<.05,1,'first')-1);
result.axialResolution2PE=1/maxSpFreq2PE;
% figure;
% plot(result.XOtfSlice*1e-3,abs(result.otfSlice));
% figure;
% ssurf(XOtf*1e-3,YOtf*1e-3,abs(result.otf),angle(result.otf));
% xlim(cutOffSpatialFrequency*[-1 1]*1e-3);
% ylim(cutOffSpatialFrequency*[-1 1]*1e-3);
% zlim([0 1]);
[X,Y]=ndgrid(result.xRange,result.yRange);
for (coreWidthIdx=1:length(coreWidths))
coreWidth=coreWidths(coreWidthIdx);
result.axialResolution=min(coreWidth,axialResolution);
corePixels=X.^2+Y.^2<=(coreWidth/2)^2;
corePixels2PE=2*sqrt(X.^2+Y.^2)<=(coreWidth/2);
focalPlanePixels=abs(X)<=(coreWidth/2);
focalPlanePixels2PE=2*abs(X)<=(coreWidth/2);
result.totalPower=[];
result.corePower=[];
result.focalPlanePower=[];
for zIdx=1:length(result.zRange)
psfSlice=psf(:,:,zIdx);
result.totalPower(zIdx,1)=sum(psfSlice(:));
result.totalPower(zIdx,2)=sum(psfSlice(:).^2);
result.corePower(zIdx,1)=sum(psfSlice(corePixels));
result.corePower(zIdx,2)=sum(psfSlice(corePixels2PE).^2);
result.focalPlanePower(zIdx,1)=sum(psfSlice(focalPlanePixels));
result.focalPlanePower(zIdx,2)=sum(psfSlice(focalPlanePixels2PE).^2);
% showImage(cat(3,psfSlice.*corePixels,psfSlice.*~corePixels,psfSlice*0),-1,result.xRange*1e6,result.yRange*1e6);
end
% Calculate some derived metrics
result.powerOutsideCore=result.totalPower-result.corePower;
result.powerOutsideFocalPlane=result.totalPower-result.focalPlanePower;
result.powerOutsideCorePerUsefulPower=result.powerOutsideCore./result.corePower;
result.powerOutsideFocalPlanePerUsefulPower=result.powerOutsideFocalPlane./result.focalPlanePower;
result.averagePowerOutsideCorePerUsefulPower=sum(result.powerOutsideCore)./sum(result.corePower);
result.averagePowerOutsideFocalPlanePerUsefulPower=sum(result.powerOutsideFocalPlane)./sum(result.focalPlanePower);
result.coreEfficiency=result.corePower./result.totalPower;
result.focalPlaneEfficiency=result.focalPlanePower./result.totalPower;
result.averageCoreEfficiency=sum(result.corePower)./sum(result.totalPower);
result.averageFocalPlaneEfficiency=sum(result.focalPlanePower)./sum(result.totalPower);
% Stack all results in an array
if (isempty(results))
results=result;
else
results(coreWidthIdx)=result;
end
if (nargout==0)
%
% Display
%
fig(coreWidthIdx)=figure();
subplot(1,2,1);
plot(zRange*1e6,result.powerOutsideCorePerUsefulPower);
ylim([0 ceil(1.5*result.powerOutsideCorePerUsefulPower(1)/10)*10]);
title(sprintf('core of alpha=%0.0f, beta=%0.0f%%',[config.modulation.alpha config.modulation.beta*100]));
subplot(1,2,2);
plot(zRange*1e6,result.powerOutsideFocalPlanePerUsefulPower);
ylim([0 ceil(1.5*result.powerOutsideFocalPlanePerUsefulPower(1)/10)*10]);
title(sprintf('section of alpha=%0.0f, beta=%0.0f%%',[config.modulation.alpha config.modulation.beta*100]));
end
end
end
|
github
|
mc225/Softwares_Tom-master
|
processCapillaryLightSheetVideos.m
|
.m
|
Softwares_Tom-master/LightSheet/processCapillaryLightSheetVideos.m
| 9,147 |
utf_8
|
5026d17a78cc88cb105294590ac086cc
|
% processCapillaryLightSheetVideos(folderNames,reprocessData,centerOffset,scanShear,perspectiveScaling,gaussianIlluminationStd,beamAngle)
%
% Reads the recorded date, converts it the matrices and deconvolves.
%
% Input:
% folderNames: a string or cell array of strings indicating folders with avi and json files.
% reprocessData: When false, date which already has a mat file with
% a restoredDataCube matrix in it will be skipped.
% centerOffset: The offset of the light sheet beam waist in meters given
% as a two-elent vector containing the vertical (swipe direction, Y) and the
% horizontal (propagation direction, X) offset, respectivelly.
% scanShear: The linear shift of the recording in [x,y]=[vertical,horizontal] when increasing z by one meter
% perspectiveScaling: The linear change in [x,y]=[vertical,horizontal] magnification when increasing z by one meter
%
%
% Note: projections can be shown using:
% figure;axs=subplot(1,2,1);imagesc(yRange*1e6,zRange*1e6,squeeze(max(recordedImageStack,[],1)).');axis equal;axs(2)=subplot(1,2,2);imagesc(yRange*1e6,tRange*1e6,squeeze(max(restoredDataCube,[],1)).'); linkaxes(axs);
% figure;imagesc(yRange*1e6,xRange*1e6,squeeze(max(recordedImageStack,[],3))); axis equal;
%
function processCapillaryLightSheetVideos(folderNames,reprocessData,centerOffset,scanShear,perspectiveScaling,gaussianIlluminationStd,beamAngle)
if (nargin<1 || isempty(folderNames))
folderNames={'Z:\RESULTS\20120501_alpha7_int1000_g1_littlemorepower_betterfocus_beads_leftofprobe\backwardScans'};
% folderNames={'Z:\RESULTS\20120501_alpha7_int1000_g1_morepower_beads_leftofprobe'};
end
if (nargin<2)
reprocessData=true;
end
if (nargin<3)
% the first two dimensions of the data cube [swipe propagation], x-y here, y-x in paper
centerOffset=[0 42e-6]; % Leave empty [] to keep default
end
if (nargin<4)
% the first two dimensions of the data cube [swipe propagation], x-y here, y-x in paper
scanShear=[0.025 0.023]; % Leave empty [] to keep default
end
if (nargin<5)
% the first two dimensions of the data cube [swipe propagation], x-y here, y-x in paper
perspectiveScaling=[]; % [373.4900 722.6800]; % Leave empty [] to keep default
end
if (nargin<6)
gaussianIlluminationStd=2/3;
end
if (nargin<7)
beamAngle=0.05;
end
if (ischar(folderNames))
folderNames={folderNames};
end
%Load the default configuration
functionName=mfilename();
configPath=mfilename('fullpath');
configPath=configPath(1:end-length(functionName));
defaultConfigFileName=strcat(configPath,'capillarySetup.json');
defaultConfig=loadjson(defaultConfigFileName);
defaultConfig.sample.signalLevel=0.3;
% Go through all the specified folders
for (folderName=folderNames(:).')
folderName=folderName{1};
logMessage('Checking folder %s for recorded videos.',folderName);
experimentConfigFileName=fullfile(folderName,'experimentConfig.json');
if (exist(experimentConfigFileName,'file'))
experimentConfig=loadjson(experimentConfigFileName);
else
experimentConfig=struct();
experimentConfig.detector=struct();
experimentConfig.detector.center=[0 0];
experimentConfig.detector.scanShear=[0 0];
experimentConfig.detector.perspectiveScaling=[0 0];
experimentConfig.excitation.illuminationClippingFactors=zeros(2); %0.06*[1 1; 1 1];
end
if (~isempty(centerOffset))
experimentConfig.detector.center=centerOffset;
end
if (~isempty(scanShear))
experimentConfig.detector.scanShear=scanShear;
end
if (~isempty(perspectiveScaling))
experimentConfig.detector.perspectiveScaling=perspectiveScaling;
end
if (~isempty(gaussianIlluminationStd))
experimentConfig.excitation.gaussianIlluminationStd=gaussianIlluminationStd;
end
if (~isempty(beamAngle))
experimentConfig.excitation.beamAngle=beamAngle;
end
% experimentConfig.excitation.excitationApertureFilling=.92; % not used?
savejson([],experimentConfig,experimentConfigFileName);
experimentConfig=structUnion(defaultConfig,experimentConfig);
% and process all videos
videoFileNameList=dir(strcat(folderName,'/*.avi'));
for (fileName={videoFileNameList.name})
fileName=fileName{1}(1:end-4);
filePathAndName=strcat(folderName,'/',fileName);
logMessage('Processing %s...',filePathAndName);
% Load specific configuration description
configFile=strcat(filePathAndName,'.json');
inputFileName=strcat(filePathAndName,'.avi');
outputFileName=strcat(filePathAndName,'.mat');
reprocessFile=true;
if (~reprocessData && exist(outputFileName,'file'))
storedVariables = whos('-file',outputFileName);
if (ismember('restoredDataCube', {storedVariables.name}))
reprocessFile=false;
end
end
if (reprocessFile)
if (~exist(configFile,'file'))
logMessage('Description file with extension .json is missing, deducing parameters from file name!');
specificConfig={}; specificConfig.modulation={};
if (~isempty(regexp(configFile,'Airy_[^\\/]*\.json$', 'once')))
alpha=regexpi(configFile,'_alpha(\d+)_','tokens');
alpha=alpha{end};
specificConfig.modulation.alpha=-str2double(alpha);
else
specificConfig.modulation.alpha=0;
end
beta=regexp(configFile,'Bessel(\d+)_[^\\/]*\.json$','tokens');
if (~isempty(beta))
beta=beta{1};
specificConfig.modulation.beta=str2double(beta)/100;
else
specificConfig.modulation.beta=1;
end
stagePositions=csvread([configFile(1:end-5),'.txt'])*1e-6;
stagePositions=stagePositions*experimentConfig.sample.refractiveIndex*2; %Adjust for the capillary movement in air
specificConfig.stagePositions.actual=stagePositions;
specificConfig.stagePositions.target=median(diff(stagePositions))*([1:length(stagePositions)]-1)+stagePositions(1);
savejson([],specificConfig,configFile);
else
specificConfig=loadjson(configFile);
end
setupConfig=structUnion(experimentConfig,specificConfig);
% Load recorded data
logMessage('Loading %s...',inputFileName);
recordedImageStack=readDataCubeFromAviFile(inputFileName);
%If backward scan, flip axis
if (median(diff(specificConfig.stagePositions.target))<0)
specificConfig.stagePositions.target=specificConfig.stagePositions.target(end:-1:1);
specificConfig.stagePositions.actual=specificConfig.stagePositions.actual(end:-1:1);
recordedImageStack=recordedImageStack(:,:,end:-1:1,:);
end
% Store partial results
logMessage('Saving recorded data to %s...',outputFileName);
save(outputFileName,'recordedImageStack','setupConfig', '-v7.3');
% Deconvolve
logMessage('Starting image reconstruction...');
[recordedImageStack lightSheetDeconvFilter lightSheetOtf ZOtf xRange,yRange,zRange tRange lightSheetPsf]=deconvolveRecordedImageStack(recordedImageStack,setupConfig);
restoredDataCube=recordedImageStack; clear recordedImageStack; % This operation does not take extra memory in Matlab
% Append the rest of the results
logMessage('Saving restored data cube to %s...',outputFileName);
save(outputFileName,'restoredDataCube','xRange','yRange','zRange','tRange','ZOtf','lightSheetPsf','lightSheetOtf','lightSheetDeconvFilter', '-v7.3','-append');
clear restoredDataCube;
else
logMessage('Skipping file %s, already done.',inputFileName);
end
end
% Check for subfolders and handles these recursively
directoryList=dir(folderName);
for listIdx=1:length(directoryList),
if directoryList(listIdx).isdir && directoryList(listIdx).name(1)~='.'
expandedFolderName=strcat(folderName,'/',directoryList(listIdx).name);
processCapillaryLightSheetVideos(expandedFolderName,reprocessData);
end
end
end
end
|
github
|
mc225/Softwares_Tom-master
|
processLightSheetDataCube.m
|
.m
|
Softwares_Tom-master/LightSheet/processLightSheetDataCube.m
| 17,786 |
utf_8
|
d051ac6eefc1099c0ee639467475c284
|
% [restoredDataCubeI xRange yRange zRange tRangeExtended recordedImageStack tRange ZOtf lightSheetPsf lightSheetOtf lightSheetDeconvFilter]
% =processLightSheetDataCube(inputFileName,stageTranslationStepSize,excitation,detection,sample,detector,focusCoordinates,openFractionOfRadius,alpha,extraIntegrationTime,illuminationCroppingFactors,dataShear,deNoiseFrames,deconvolveWithDetectionPsf)
%
% Processes the datacube obtained after a light sheet capturing experiment.
%
% Input:
% inputFileName: The avi file containing the captured frames.
% stageTranslationStepSize: z-step size of the sample in meters.
% excitation: struct array with the fields:
% wavelength
% numericalApertureInAir
% magnification
% tubeLength
% power
% detection: struct array with the fields:
% wavelength
% numericalApertureInAir
% magnification
% tubeLength
% sample: struct array with the fields:
% fluorophore: struct array with the fields:
% maxDensity
% extinctionCoefficient: m^2
% quantumYield
% refractiveIndex: assuming the objective NA is in air
% signalLevel: used for deconvolution
% backgroundLevel
% detector: struct array with the fields:
% wavelength
% numericalApertureInAir
% magnification
% tubeLength
% focusCoordinates: The coordinates of the beam focus used to calculate the PSF for the
% deconvolution. The coordinates are given in pixels and frames
% (starting from 0)
% openFractionOfRadius: The open fraction of the radius of the annular
% aperture to create a Bessel beam, default 1 (full open aperture, top-hat beam).
% alpha: The cubic phase mask value, default 0 (no cubic phase mask). The
% optical path length is altered by alpha*u^3 wavelengths, where U is
% the normalized pupil coordinate.
% extraIntegrationTime: for Bessel beam
% illuminationCroppingFactors:
% dataShear: The (fractional) pixel shift in X and Y of the projection when moving one step in Z.
% deNoiseFrames: before deconvolution in Z, default false
% deconvolveWithDetectionPsf: after deconvolution in Z, default false
% maxFilesToLoad: The limit to the number of replicated scans that will be loaded if duplicates exist. (default: Inf)
%
% Output:
% restoredDataCubeI:
% xRange yRange zRange tRangeExtended:
% recordedImageStack
% tRange
% ZOtf
% lightSheetPsf
% lightSheetOtf
% lightSheetDeconvFilter
%
function [restoredDataCubeI xRange yRange zRange tRangeExtended recordedImageStack tRange ZOtf lightSheetPsf lightSheetOtf lightSheetDeconvFilter]=processLightSheetDataCube(inputFileName,stageTranslationStepSize,excitation,detection,sample,detector,focusCoordinateDecenter,openFractionOfRadius,alpha,extraIntegrationTime,illuminationCroppingFactors,dataShear,deNoiseFrames,deconvolveWithDetectionPsf,maxFilesToLoad)
if (nargin<1)
inputFileName='Z:\RESULTS\20120501_alpha7_int1000_g1_littlemorepower_betterfocus_beads_leftofprobe\Airy_0F.avi';
end
if (nargin<2)
% stageTranslationStepSize=0.00025e-3; % [m/frame]
stageTranslationStepSize=100e-9; % [m/frame]
end
if (nargin<3 || isempty(excitation))
% Objectives and wavelengths
excitation={};
excitation.wavelength=532e-9;
excitation.objective={};
excitation.objective.numericalAperture=.42;
excitation.fractionOfNumericalApertureUsed=1;
excitation.objective.magnification=20;
excitation.objective.tubeLength=200e-3; %for Mitutoyo the rear focal length is 200mm
excitation.power=0.01e-3;
excitation.tubeLength=200e-3;
end
if (nargin<4 || isempty(detection))
detection={};
detection.wavelength=612e-9; % Firefli* Fluorescent Red (542/612nm) % 395e-9; for GFP
detection.objective={};
detection.objective.numericalAperture=.40; % .28;
detection.objective.magnification=20; %Actual total magnification 22
detection.objective.tubeLength=160e-3; % for Newport, %200e-3 for Mitutoyo / Nikon
detection.tubeLength=1.1*160e-3;
end
if (nargin<5 || isempty(sample))
% Sample medium specification
NAvogadro=6.0221417930e23;
sample={};
sample.fluorophore={};
sample.fluorophore.maxDensity=0.01*10^3*NAvogadro; % m^-3, 0.01*mol/L density
sample.fluorophore.extinctionCoefficient=30000*(100/10^3)/NAvogadro; % m^2
sample.fluorophore.quantumYield=0.79;
sample.refractiveIndex=1.4; %Assuming the objective NA is in air
sample.signalLevel=0.5; % for deconvolution
sample.backgroundLevel=0.05; % fraction of dynamic range
end
if (nargin<6 || isempty(detector))
% Detector specification
detector={};
detector.integrationTime=2e-3; % s
detector.quantumEfficiency=0.55;
detector.darkCurrent=200; % e-/s
detector.readOutNoise=16; % e-
detector.wellDepth=20e3; % e-
detector.numberOfGrayLevels=2^12;
detector.pixelSize=7.4*[1 1]*1e-6;
detector.framesPerSecond=1; % [s]
detector.center=[0 0]*1e-6;
end
if (nargin<7)
focusCoordinateDecenter=[];
end
% Choice of light-sheet
if (nargin<8)
openFractionOfRadius=1.0; %Fraction of radius
end
if (nargin<9)
alpha=0.0;
end
if (nargin<10)
extraIntegrationTime=1.0; % Assume the bessel beam is illuminated equally
end
if (nargin<11 || isempty(illuminationCroppingFactors))
illuminationCroppingFactors=[1 1; 1 1]*0.06;
end
if (nargin<12)
dataShear=[];
end
if (nargin<13 || isempty(deNoiseFrames))
deNoiseFrames=false;
end
if (nargin<14 || isempty(deconvolveWithDetectionPsf))
deconvolveWithDetectionPsf=false;
end
if (nargin<15 || isempty(maxFilesToLoad))
maxFilesToLoad=Inf;
end
% General constants
hPlanck=6.6260695729e-34;
cLight=299792458;
%% Calculation parameters
deflectBeamInsteadOfSampleMovement=false;
if (alpha~=0)
lightSheetName='Airy';
else
if (openFractionOfRadius==1.0)
lightSheetName='Classic';
else
if (openFractionOfRadius==0.0)
lightSheetName='Theoretical Bessel';
else
lightSheetName='Bessel';
end
end
end
%Assume that the power is adjusted to compensate for a reduction in open fraction.
beamPowerAdjustment=1; %1-(1-openFractionOfRadius)^2;
excitation.power=excitation.power*beamPowerAdjustment; % W
%Load and pre-process data
if (~strcmpi(inputFileName(end-4:end),'_.avi'))
recordedImageStack=readDataCubeFromAviFile(inputFileName);
else
pathName = fileparts(inputFileName);
videoFiles=dir(strcat(inputFileName(1:end-4),'*.avi'));
positionFiles=dir(strcat(inputFileName(1:end-4),'*.txt'));
nbFilesToLoad=min(maxFilesToLoad,length(videoFiles));
logMessage('Loading %u video files of %u ...',[nbFilesToLoad length(videoFiles)]);
recordedImageStack=[];
for (fileIdx=1:nbFilesToLoad)
fileName=videoFiles(fileIdx).name;
singlePositions=dlmread(strcat(pathName,'/',positionFiles(fileIdx).name),'\t');
forward=mean(mean(diff(singlePositions)))>0;
logMessage('Loading video file %s...',fileName);
singleImageStack=readDataCubeFromAviFile(strcat(pathName,'/',fileName));
% %Debug
% singleImageStack=getTestImage('usaf'); singleImageStack(1,1,10)=0;
% if (~forward)
% singleImageStack=singleImageStack(:,:,[end end 1:end-2]);
% end
if (~forward)
singleImageStack=singleImageStack(:,:,end:-1:1);
singlePositions=singlePositions(end:-1:1,:);
end
save(strcat(pathName,'/',fileName(1:end-4),'.mat'),'singleImageStack');
singleImageStackVectorFFT=fft(squeeze(max(max(singleImageStack,[],1),[],2)));
if (~isempty(recordedImageStack))
logMessage('Merging...');
[output Greg] = dftregistration(recordedImageStackVectorFFT,singleImageStackVectorFFT,100);
imageShift=output(3);
logMessage('Detected a shift of %0.2f pixels',imageShift);
singleImageStack=circshift(singleImageStack,[0 0 round(imageShift)]);
recordedImageStack=recordedImageStack+singleImageStack;
else
recordedImageStack = singleImageStack;
recordedImageStackVectorFFT=singleImageStackVectorFFT;
positions=singlePositions(:,1);
end
end
% recordedImageStack=ifftn(recordedImageStack,'symmetric');
end
clear singleImageStack;
%Mask saturated beads
% mask=recordedImageStack>=1;
% logMessage('Masking %f saturated pixels.',sum(mask(:)));
% mask=circshift(mask,-[2^4 2^4 2^7]);
% for (xIdx=2.^[0:5])
% mask=mask|circshift(mask,[xIdx 0 0]);
% end
% for (yIdx=2.^[0:5])
% mask=mask|circshift(mask,[0 yIdx 0]);
% end
% for (zIdx=2.^[0:8])
% mask=mask|circshift(mask,[0 0 zIdx]);
% end
% mask=0*recordedImageStack;
% mask(:,:,1:710)=1;
% recordedImageStack=recordedImageStack.*(1-mask);
% logMessage('Masked %0.6f%% of the data.',100*mean(mask(:)));
% clear mask;
%Correct shear
recordedImageStack=recordedImageStack/extraIntegrationTime;
recordedImageStack=permute(recordedImageStack,[2 1 3]); % Dimension order [x y z]
if (~isempty(dataShear))
logMessage('Correcting a shear of (%0.3f,%0.3f)...',dataShear);
recordedImageStack=correctShear(single(recordedImageStack),dataShear);
end
if (isempty(focusCoordinateDecenter))
focusCoordinateDecenter=[0 0 0];
end
% Sample grid specification
realDetectionMagnification=detection.objective.magnification*detection.objective.tubeLength/detection.tubeLength;
xRange=detector.pixelSize(1)*([1:size(recordedImageStack,1)]-floor(size(recordedImageStack,1)/2)-1)/realDetectionMagnification; % left/right
yRange=detector.pixelSize(2)*([1:size(recordedImageStack,2)]-floor(size(recordedImageStack,2)/2)-1)/realDetectionMagnification; % up/down
tRange=(stageTranslationStepSize*sample.refractiveIndex)*([1:size(recordedImageStack,3)]-floor(size(recordedImageStack,3)/2+1))/detector.framesPerSecond; %Translation range (along z-axis)
zRange=tRange; % detection axis, zero centered
xRange=single(xRange); yRange=single(yRange); zRange=single(zRange); tRange=single(tRange);
% %Crop the first two dimensions by half
% recordedImageStack=recordedImageStack([1:floor(end/2)]+floor(end/4)+focusCoordinateDecenter(1),[1:floor(end/2)]+floor(end/4)+focusCoordinateDecenter(2),:);
%Shift in z (the scan direction) after deconvolution
%Crop the first dimension by 1/8th and the second by a half
%recordedImageStack=recordedImageStack([1:floor(7*end/8)]+floor(end/16)+focusCoordinateDecenter(1),[1:floor(end/2)]+floor(end/4)+focusCoordinateDecenter(2),:);
recordedImageStack=recordedImageStack(:,[1:floor(end/2)]+floor(end/4)+focusCoordinateDecenter(2),:);
if (focusCoordinateDecenter(1)~=0)
logMessage('Warning: light sheet not assumed to be centered!!');
%recordedImageStack=circshift(recordedImageStack,[focusCoordinateDecenter(1) 0 0]);
xRange=xRange-focusCoordinateDecenter(1)*detector.pixelSize(1)/realDetectionMagnification; % left/right;
end
%% Preparative Calculations
% Define some noise related variables
detectionObjectiveSolidAngle=2*pi*(1-cos(asin(detection.objective.numericalAperture/sample.refractiveIndex)));
objectiveEfficiency=detectionObjectiveSolidAngle/(4*pi);
overallDetectionEfficiency=sample.fluorophore.quantumYield*objectiveEfficiency*detector.quantumEfficiency;
% Pre-calc. detection PSF
if (deconvolveWithDetectionPsf)
logMessage('Calculating detection PSF...');
detectionPsf=calcDetectionPsf(xRange,yRange,zRange,0,0,detection,sample.refractiveIndex); %Assume shift invariance of the detection PSF
detectionPsf=single(detectionPsf);
detectionPsf=overallDetectionEfficiency*detectionPsf;
else
detectionPsf=[];
end
%Pre-calc the light-sheet
logMessage('Calculating theoretical light sheet...');
photonEnergy=hPlanck*cLight/excitation.wavelength;
lightSheetPsf=calcLightSheetPsf(xRange,yRange,zRange,0,excitation,alpha,openFractionOfRadius,sample.refractiveIndex,illuminationCroppingFactors);
lightSheetPsf=lightSheetPsf*excitation.power*detector.integrationTime/photonEnergy; %Convert to photons per voxel
%% Image reconstruction
logMessage('Reconstructing convolved data set...');
config={}; config.excitation=excitation; config.detection=detection; config.detector=detector; config.sample=sample;
config.excitation.objective.refractiveIndex=1;
config.stagePositions={}; config.stagePositions.target=tRange;
config.modulation={}; config.modulation.alpha=7; config.modulation.beta=1;
[restoredDataCube lightSheetDeconvFilter lightSheetOtf ZOtf xRange,yRange,zRange tRange lightSheetPsf]=deconvolveRecordedImageStack(recordedImageStack,config);
% [restoredDataCubeI lightSheetDeconvFilter lightSheetOtf ZOtf tRangeExtended]=reconstructLightSheetDataCube(xRange,yRange,zRange,tRange,recordedImageStack,excitation,detection,lightSheetPsf,detectionPsf,sample.signalLevel,sample.backgroundLevel,deflectBeamInsteadOfSampleMovement,deNoiseFrames);
% restoredDataCubeI=circshift(restoredDataCubeI,[0 0 round(focusCoordinateDecenter(3))]);
if (nargout==0)
save('restoredDataCube.mat','restoredDataCubeI','xRange','yRange','zRange','tRange','tRangeExtended');
%% Display results
resultFig=figure();
resultAx(1)=subplot(2,2,1);
resultAx(2)=subplot(2,2,2);
resultAx(3)=subplot(2,2,3);
resultAx(4)=subplot(2,2,4);
%The recorded image
showImage(squeeze(sum(recordedImageStack,2)).',.20,xRange*1e6,tRange*1e6,resultAx(1));
set(gca,'FontWeight','bold','FontName','Times','FontSize',18,'LineWidth',3);
xlabel('x [\mum]','Interpreter','Tex','FontWeight','bold','FontName','Times','FontSize',18); ylabel('z [\mum]','Interpreter','Tex','FontWeight','bold','FontName','Times','FontSize',18);
title(sprintf('%s',lightSheetName),'FontWeight','bold','FontName','Times','FontSize',24);
centerImageView();
%The restored image
showImage(squeeze(sum(restoredDataCubeI,2)).',.05,xRange*1e6,tRangeExtended*1e6,resultAx(2));
set(gca,'FontWeight','bold','FontName','Times','FontSize',18,'LineWidth',3);
xlabel('x [\mum]','Interpreter','Tex','FontWeight','bold','FontName','Times','FontSize',18); ylabel('z [\mum]','Interpreter','Tex','FontWeight','bold','FontName','Times','FontSize',18);
title(sprintf('%s restored',lightSheetName),'FontWeight','bold','FontName','Times','FontSize',24);
centerImageView();
%The light-sheet
showImage(squeeze(lightSheetPsf(:,floor(end/2)+1,:)).'./max(abs(lightSheetPsf(:))),[],xRange*1e6,zRange*1e6,resultAx(3));
set(gca,'FontWeight','bold','FontName','Times','FontSize',18,'LineWidth',3);
xlabel('x [\mum]','Interpreter','Tex','FontWeight','bold','FontName','Times','FontSize',18); ylabel('z [\mum]','Interpreter','Tex','FontWeight','bold','FontName','Times','FontSize',18);
title(sprintf('%s light-sheet',lightSheetName),'FontWeight','bold','FontName','Times','FontSize',24);
centerImageView();
%The MTF
axes(resultAx(4));
plotSliceXPosIdx=floor(length(xRange)/2)+1;
% plotSliceXPosIdx=find(xRange==0);
mtf=abs(squeeze(lightSheetOtf(plotSliceXPosIdx,floor(end/2)+1,[floor(end/2)+1:end,1]) ));
filterAmplification=abs(squeeze(lightSheetDeconvFilter(plotSliceXPosIdx,floor(end/2)+1,[floor(end/2)+1:end,1])));
mtfRestored=mtf.*filterAmplification;
noiseLevel=0.01;
noiseAmplification=noiseLevel*filterAmplification;
ZOtfRange=-1e-6*ZOtf(floor(end/2)+1:-1:1);
area(ZOtfRange,noiseAmplification,'LineWidth',3,'FaceColor',[.5 .5 .5],'EdgeColor','none');
hold on;
plot(ZOtfRange,mtf,'Color',[.8 0 0],'LineWidth',3,'LineStyle','-');
plot(ZOtfRange,mtfRestored,'Color',[0 .75 .1],'LineWidth',2,'LineStyle','-');
xlim([0 ZOtfRange(end)]);
ylim([0 1.1]);
hold off;
set(gca,'FontWeight','bold','FontName','Times','FontSize',18,'LineWidth',3);
xlabel('\nu_z [cycles/\mum]','Interpreter','Tex','FontWeight','bold','FontName','Times','FontSize',18); ylabel('MTF','Interpreter','Tex','FontWeight','bold','FontName','Times','FontSize',18);
title(sprintf('%s Deconvolution MTF',lightSheetName),'FontWeight','bold','FontName','Times','FontSize',24);
% showSlices(recordedImageStack./max(abs(recordedImageStack(:))),0.1,xRange,yRange,tRange);
clear restoredDataCubeI;
else
if (nargout>4)
lightSheetPsf=squeeze(lightSheetPsf(:,1+floor(end/2),:));
lightSheetOtf=squeeze(lightSheetOtf(:,1+floor(end/2),:));
lightSheetDeconvFilter=squeeze(lightSheetDeconvFilter(:,1+floor(end/2),:));
end
end
end
function centerImageView()
xlim([-50 50]);
ylim([-20 20]);
axis equal;
set(gca,'XTick',[-50:10:50]);
set(gca,'YTick',[-20:10:20]);
end
|
github
|
mc225/Softwares_Tom-master
|
calcLightSheetPsf.m
|
.m
|
Softwares_Tom-master/LightSheet/calcLightSheetPsf.m
| 8,171 |
utf_8
|
6a6916b89b6b3dff245f22059eca0c83
|
% [psf psfTwoPhotonSwiped psfTwoPhotonCylindricalLens]=calcLightSheetPsf(xRange,yRange,zRange,tilt,excitation,alpha,openFractionOfRadius,refractiveIndexOfSample)
% Calculates the 2D intensity profile created by a swiped light-sheet.
%
% Inputs:
% tilt: a scalar indicating the tilt of the pupil, or thus the lateral
% position of the light sheet.
% excitation: struct with fields wavelength and objective, the latter
% must contain the fields magnification, tubeLength, and optionally fractionOfNumericalApertureUsed
% alpha: the alpha factor of the cubic phase modulation
% openFractionOfRadius: the open fraction of the annular aperture
% refractiveIndexOfSample: the refractive index of the sample medium
%
% Returns:
% psf = the single photon point-spread function (PSF)
%
% TODO: Check if these arguments still work:
% psfTwoPhotonSwiped = the two photon PSF assuming that the sheet is created by scanning the beam
% psfTwoPhotonCylindricalLens = the two photon PSF assuming that the sheet is created with a cylindrical lens
%
%
% Example:
% zRange=[-50:.1:50]*1e-6;
% xRange=zRange;
% yRange=[0:20:100]*1e-6;
% excitation=struct();
% excitation.wavelength=532e-9;
% excitation.objective=struct();
% excitation.objective.numericalAperture=0.42;
% excitation.objective.refractiveIndex=1.0;
% excitation.objective.magnification=20;
% excitation.objective.tubeLength=200e-3;
% excitation.objective.illuminationClippingFactors=[1 1; 1 1]*0.0;
% excitation.gaussianIlluminationStd=2/3;
%
% lightSheet=calcLightSheetPsf(xRange,yRange,zRange,0,excitation,0,1,1.4);
% lightSheet=squeeze(lightSheet).';
%
% lightSheetN=lightSheet./repmat(max(lightSheet),[length(zRange) 1]);
% imagesc(yRange*1e6,zRange*1e6,lightSheetN); axis equal;
% xlabel('y (propagation) [\mum]');
% ylabel('z (scan) [\mum]');
%
% fwhm=[];
% for idx=1:length(yRange),
% fwhm(idx)=calcFullWidthAtHalfMaximum(zRange,lightSheet(:,idx),'BiasedLinear');
% end;
% close all;
% plot(yRange*1e6,fwhm*1e6)
%
function [psf psfTwoPhotonSwiped psfTwoPhotonCylindricalLens]=calcLightSheetPsf(xRange,yRange,zRange,tilt,excitation,alpha,openFractionOfRadius,refractiveIndexOfSample)
if (nargin<5 || isempty(excitation))
excitation=struct('wavelength',532e-9,...
'objective',struct('numericalAperture',0.80,'magnification',40,'tubeLength',200e-3),...
'fractionOfNumericalApertureUsed',1.0);
end
numericalAperture=excitation.objective.numericalAperture;
if (isfield(excitation,'fractionOfNumericalApertureUsed'))
numericalAperture=numericalAperture*excitation.fractionOfNumericalApertureUsed;
end
if (nargin<8 || isempty(refractiveIndexOfSample))
refractiveIndexOfSample=1.0;
end
if (nargin<1 || isempty(xRange))
xRange=(7.4*1e-6/excitation.objective.magnification)*[-200:199];
xRange=single(xRange);
end
if (nargin<2 || isempty(yRange))
yRange=(7.4*1e-6/excitation.objective.magnification)*[-200:199];
yRange=single(yRange);
end
if (nargin<3 || isempty(yRange))
stageTranslationStepSize=0.1*1e-6;
zRange=(stageTranslationStepSize*refractiveIndexOfSample)*[-250:249]; %Translation range (along z-axis)
zRange=single(zRange);
end
if (nargin<4 || isempty(tilt))
tilt=0;
end
if (nargin<6 || isempty(alpha))
alpha=0;
end
if (nargin<7 || isempty(openFractionOfRadius))
openFractionOfRadius=1;
end
% ! Code to support old data sets !
% Check if the SLM is smaller than the back aperture, if so, simulate the limited illumination
if (~isfield(excitation,'illuminationClippingFactors'))
illuminationClippingFactors=0*[1 1; 1 1];
else
illuminationClippingFactors=excitation.illuminationClippingFactors;
end
if (~isfield(excitation,'gaussianIlluminationStd'))
gaussianIlluminationStd=[];
else
gaussianIlluminationStd=excitation.gaussianIlluminationStd;
end
if (~isfield(excitation,'beamAngle'))
beamAngle=[];
else
beamAngle=excitation.beamAngle;
end
projectionDimension=1;
if (length(xRange)<=1)
%Nyquist sampling is sufficient, we will do a projection later anyway
projRangeLength=512;
xRangeForProj=([1:projRangeLength]-floor(projRangeLength/2)-1)*0.5*0.5*excitation.wavelength/numericalAperture;
else
xRangeForProj=xRange;
end
if (openFractionOfRadius>0)
crop=@(U,V) 1.0*(U>=-(1-illuminationClippingFactors(1,1))&U<=(1-illuminationClippingFactors(1,2)) & V>=-(1-illuminationClippingFactors(2,1))&V<=(1-illuminationClippingFactors(2,2)));
if (~isempty(gaussianIlluminationStd))
apodization=@(U,V) exp(-(U.^2+V.^2)./(2*gaussianIlluminationStd^2));
else
apodization=@(U,V) 1;
end
if (~isempty(beamAngle))
phaseMask=@(U,V) alpha*((cos(beamAngle)*U-sin(beamAngle)*V).^3 + (sin(beamAngle)*U+cos(beamAngle)*V).^3);
else
phaseMask=@(U,V) alpha*(U.^3+V.^3);
end
%Rotate the coordinate system so that X and Z are interchanged
%pupilFunctor=@(U,V) crop(U,V).*(sqrt(U.^2+V.^2)>=(1-openFractionOfRadius)).*exp(2i*pi*(alpha*V.^3 + (tilt-alpha*3/5)*V));
pupilFunctor=@(U,V) crop(U,V).*apodization(U,V).*(sqrt(U.^2+V.^2)>=(1-openFractionOfRadius)).*exp(2i*pi*(phaseMask(U,V) + tilt*V));
%Assume circular polarization propagating along the x-axis
cache=Cache(); % Get the default cache
key={xRangeForProj,zRange,yRange,{excitation.wavelength,1/sqrt(2),1i/sqrt(2),illuminationClippingFactors,gaussianIlluminationStd,beamAngle,alpha,openFractionOfRadius,tilt},numericalAperture,refractiveIndexOfSample,excitation.objective.magnification,excitation.objective.tubeLength,projectionDimension};
if (isfield(cache,key))
logMessage('Loading PSF projection from cache...');
psf=cache(key);
else
startTime=clock();
psf=calcVectorialPsf(xRangeForProj,zRange,yRange,excitation.wavelength,@(U,V) pupilFunctor(U,V)/sqrt(2),@(U,V) 1i*pupilFunctor(U,V)/sqrt(2),numericalAperture,refractiveIndexOfSample,excitation.objective.magnification,excitation.objective.tubeLength,projectionDimension);
if (etime(clock(),startTime)>10) % Only cache slow calculations
cache(key)=psf;
end
end
if (nargout>=2)
keyTwoPhoton={key,'psfTwoPhotonSwiped'};
if (isfield(cache,keyTwoPhoton))
logMessage('Loading two photon PSF from cache...');
psfTwoPhotonSwiped=cache(keyTwoPhoton);
else
startTime=clock();
[psfTwoPhoton,~,psfTwoPhotonSwiped]=calcVectorialPsf(xRangeForProj,zRange,yRange,2*excitation.wavelength,@(U,V) pupilFunctor(U,V)/sqrt(2),@(U,V) 1i*pupilFunctor(U,V)/sqrt(2),numericalAperture,refractiveIndexOfSample,excitation.objective.magnification,excitation.objective.tubeLength,projectionDimension);
if (nargout>=3)
psfTwoPhotonCylindricalLens=psfTwoPhoton.^2;
end
clear psfTwoPhoton;
if (etime(clock(),startTime)>10) % Only cache slow calculations
cache(keyTwoPhoton)=psfTwoPhotonSwiped;
end
end
end
else
error('calcLightSheetPsf.m Not implemented for openFractionOfRadius==0.');
end
%Return to original coordinate system
psf=permute(psf,[1 3 2]);
if (nargout>=2)
psfTwoPhotonSwiped=permute(psfTwoPhotonSwiped,[1 3 2]);
if (nargout>=3)
psfTwoPhotonCylindricalLens=permute(psfTwoPhotonCylindricalLens,[1 3 2]);
end
end
if (nargout==0 && numel(psf)>100)
figure;
tmp=squeeze(psf(:,1,:)).';
tmp=tmp./repmat(max(tmp),[size(tmp,1) 1]);
imagesc(xRange*1e6,zRange*1e6,tmp);axis equal
clear psf;
end
end
|
github
|
mc225/Softwares_Tom-master
|
reconstructScannedImage.m
|
.m
|
Softwares_Tom-master/ImageScanningMicroscopy/reconstructScannedImage.m
| 13,515 |
utf_8
|
d449dfb15afa816baa9459a6e591f87b
|
% [imageScanningImage xRangeOutputImg yRangeOutputImg]=reconstructScannedImage(inputImages,pixelPitch,magnification,outputFileName)
%
function [imageScanningImage xRangeOutputImg yRangeOutputImg]=reconstructScannedImage(inputImages,samplePositions,pixelPitch,magnification,outputFileName)
close all; % TODO: Remove this line when done testing
if (nargin<3 || isempty(pixelPitch))
pixelPitch=[1 1]*7.4e-6;
end
if (length(pixelPitch)==1)
pixelPitch(2)=pixelPitch;
end
if (nargin<4 || isempty(magnification))
magnification=100;
end
pixelPitchInSample=pixelPitch/magnification;
pixelPitchForOutput=pixelPitchInSample/2;
regionOfInterest=[];
if (nargin<1 || isempty(inputImages))
inputImages='C:\Users\Tom\Dropbox\ScansChris\12 aug scans\scan3\scanselectedROI';
regionOfInterest=[]; %[219-16 379-16 32 32];
% % Generate synthetic data
% imgSize=[32 32]/2; % Pixel size of recorded image
% rangeX=[-0.5:.05:0.5]*1e-6;
% rangeY=[-0.5:.05:0.5]*1e-6;
% [stagePositionsX stagePositionsY]=ndgrid(rangeX,rangeY);
% clear rangeX rangeY;
%
% [inputImages samplePositions]=simulateImageScanningMicroscopy(imgSize,stagePositionsX,stagePositionsY,pixelPitchInSample);
% clear imgSize stagePositionsX stagePositionsY;
% % Test output
% inputImages4D=reshape(inputImages,[size(inputImages,1) size(inputImages,2) [1 1]*sqrt(size(inputImages,3))]);
% for (xIdx=1:size(inputImages4D,3))
% for (yIdx=1:size(inputImages4D,4))
% tmp([1:size(inputImages4D,1)]+size(inputImages4D,1)*(xIdx-1),[1:size(inputImages4D,2)]+size(inputImages4D,2)*(yIdx-1))=inputImages4D(:,:,xIdx,yIdx);
% end
% end
% imagesc(tmp);
end
if (nargin==1 || (nargin>0 && isempty(samplePositions)))
nbImagesXY=[floor(sqrt(nbImages)) ceil(nbImages/floor(sqrt(nbImages)))];
stepSize=pixelPitch./magnification;
rangeX=([1:nbImagesXY(1)]-floor(nbImagesXY(1)/2))*stepSize(1);
rangeY=([1:nbImagesXY(2)]-floor(nbImagesXY(2)/2))*stepSize(2);
[stagePositionsX stagePositionsY]=ndgrid(rangeX,rangeY);
clear nbSamples nbImagesXY stepSize rangeX rangeY;
samplePositions=[stagePositionsX(:) stagePositionsY(:)];
end
if (ischar(inputImages))
if (isdir(inputImages))
logMessage('Loading input images from folder %s',inputImages);
[inputImages samplePositions]=loadInputImages(inputImages,regionOfInterest);
else
logMessage('%s is not a folder.',inputImages);
return;
end
end
if (nargin<5)
outputFileName='recontructedImage.fig';
end
% For deconvolution
resolutionIllumination=400e-9;
resolutionDetection=100e-9;
% Process input
inputSize=[size(inputImages,1) size(inputImages,2)];
nbSamples=size(inputImages,3);
% Create output grid and empty output image
xRangeInputImg=([1:inputSize(1)]-floor(inputSize(1)/2))*pixelPitchInSample(1);
yRangeInputImg=([1:inputSize(2)]-floor(inputSize(2)/2))*pixelPitchInSample(2);
[imgInX imgInY]=ndgrid(xRangeInputImg,yRangeInputImg);
xRangeOutputImg=[xRangeInputImg(1)+min(samplePositions(:,1)):pixelPitchForOutput(1):xRangeInputImg(end)+max(samplePositions(:,1))];
yRangeOutputImg=[yRangeInputImg(2)+min(samplePositions(:,2)):pixelPitchForOutput(2):yRangeInputImg(end)+max(samplePositions(:,2))];
[imgOutX imgOutY]=ndgrid(xRangeOutputImg,yRangeOutputImg);
%Calculate background
backgroundImage=min(inputImages,[],3);
inputImages=inputImages-repmat(backgroundImage,[1 1 nbSamples]);
totalIntensities=squeeze(sum(sum(inputImages)));
% Confocal pinhole
pinholeRadius=3; % pixels
confocalPinHole=imgInX.^2+imgInY.^2<=pinholeRadius^2;
confocalIntensities=squeeze(sum(sum(inputImages.*repmat(confocalPinHole,[1 1 nbSamples]))));
%
% Reconstruct
%
interpolantLaserScanning=TriScatteredInterp(samplePositions(:,1),samplePositions(:,2),totalIntensities,'linear');
interpolatedLaserScanningImage = interpolantLaserScanning(imgOutX,imgOutY);
interpolatedLaserScanningImage(isnan(interpolatedLaserScanningImage))=0;
interpolantConfocal=TriScatteredInterp(samplePositions(:,1),samplePositions(:,2),confocalIntensities,'linear');
interpolatedConfocalImage = interpolantConfocal(imgOutX,imgOutY);
interpolatedConfocalImage(isnan(interpolatedConfocalImage))=0;
%Image scanning reconstruction
imageScanningImage=0*imgOutX;
for (imgIdx=1:nbSamples)
fractionOfReconstruction=imgIdx/nbSamples
samplePos=samplePositions(imgIdx,:);
inputImageCenter=1+floor(inputSize./2);
% inputImage=zeros(inputSize);
% inputImage(inputImageCenter(1),inputImageCenter(2))=confocalIntensities(imgIdx); %totalIntensities(imgIdx);
% newImage=interpn(imgInX+samplePos(1),imgInY+samplePos(2),inputImage,imgOutX,imgOutY,'*nearest',0); % show as squares
% newImage(newImage<max(newImage(:)))=0;
% newImage=interpn(imgInX+samplePos(1),imgInY+samplePos(2),inputImage,imgOutX,imgOutY,'*nearest',0);
% Image Scanning Microscopy reconstruction
newImage=interpn(imgInX./2+samplePos(1),imgInY./2+samplePos(2),inputImages(:,:,imgIdx),imgOutX,imgOutY,'*cubic',0);
% imageScanningImage=imageScanningImage+newImage;
imageScanningImage=max(imageScanningImage,newImage);
end
% Deconvolve
cutOffSpatialFrequency=1/max(resolutionDetection,resolutionIllumination); %Only for the regularization
[XOtf,YOtf,fRel]=calcOtfGridFromSampleFrequencies(1./[diff(imgOutX(1:2,1)) diff(imgOutY(1,1:2))],size(imgOutX)*2,cutOffSpatialFrequency);
noiseToSignalLevel=100;
% noiseToSignalPowerRatio=(fRel./noiseToSignalLevel).^2;
imageScanningImagePadded=imageScanningImage([1:end, end*ones(1,ceil(end/2)), ones(1,floor(end/2))],[1:end, end*ones(1,ceil(end/2)), ones(1,floor(end/2))]);
confocalImagePadded=interpolatedConfocalImage([1:end, end*ones(1,ceil(end/2)), ones(1,floor(end/2))],[1:end, end*ones(1,ceil(end/2)), ones(1,floor(end/2))]);
otfDoubleIllum=max(0,(1-0.5*sqrt(XOtf.^2+YOtf.^2).*resolutionIllumination));
otfDoubleDetect=max(0,(1-0.5*sqrt(XOtf.^2+YOtf.^2).*resolutionDetection));
opticalTransferFunction=otfDoubleIllum.*otfDoubleDetect;
filter=calcWienerFilter(opticalTransferFunction,noiseToSignalLevel^2,otfDoubleDetect);
imageScanningDeconvolvedImage=ifft2(fft2(imageScanningImagePadded).*ifftshift(filter),'symmetric');
confocalDeconvolvedImage=ifft2(fft2(confocalImagePadded).*ifftshift(filter),'symmetric');
clear imageScanningImagePadded filter;
imageScanningDeconvolvedImage=imageScanningDeconvolvedImage(1:end/2,1:end/2); % Crop padding again
confocalDeconvolvedImage=confocalDeconvolvedImage(1:end/2,1:end/2); % Crop padding again
% Make first and second coordinate Y and X for consistency with
% functions such as imagesc
tmp=xRangeOutputImg;
xRangeOutputImg=yRangeOutputImg;
yRangeOutputImg=tmp;
clear tmp;
%
% Output
%
%If no output specified, display result
if (nargout<1 || ~isempty(outputFileName))
fig=figure();
axs(1)=subplot(2,3,1);
scatter(samplePositions(:,2)*1e6,samplePositions(:,1)*1e6,10,confocalIntensities,'s','filled'); title('confocal blocks');
set(gca,'Color',[0 0 .75]);
axis image; xlabel('x [\mum]'); ylabel('y [\mum]');
axs(2)=subplot(2,3,2);
imagesc(xRangeOutputImg*1e6,yRangeOutputImg*1e6,interpolatedLaserScanningImage); title('laser scan');
axis image; colormap(hot); colorbar(); xlabel('x [\mum]'); ylabel('y [\mum]');
axs(3)=subplot(2,3,3);
imagesc(xRangeOutputImg*1e6,yRangeOutputImg*1e6,interpolatedConfocalImage); title('confocal');
axis image; colormap(hot); colorbar(); xlabel('x [\mum]'); ylabel('y [\mum]');
axs(4)=subplot(2,3,4);
imagesc(xRangeOutputImg*1e6,yRangeOutputImg*1e6,imageScanningImage); title('image scan');
% hold on;
% scatter(samplePositions(:,2)*1e6,samplePositions(:,1)*1e6,10,[0 0 .75],'+');
% hold off;
axis image; colormap(hot); colorbar(); xlabel('x [\mum]'); ylabel('y [\mum]');
axs(5)=subplot(2,3,5);
imagesc(xRangeOutputImg*1e6,yRangeOutputImg*1e6,confocalDeconvolvedImage); title('confocal deconvolved');
axis image; colormap(hot); colorbar(); xlabel('x [\mum]'); ylabel('y [\mum]');
axs(6)=subplot(2,3,6);
imagesc(xRangeOutputImg*1e6,yRangeOutputImg*1e6,imageScanningDeconvolvedImage); title('image scan deconvolved');
axis image; colormap(hot); colorbar(); xlabel('x [\mum]'); ylabel('y [\mum]');
linkaxes(axs);
% Save result
if (~isempty(outputFileName))
saveas(fig,outputFileName);
end
clear imageScanningImage; % Avoid cluttering the command line
end
end
function [recordedImages stagePositions]=simulateImageScanningMicroscopy(imgSize,samplePositionsX,samplePositionsY,pixelPitchInSample)
stagePositions=[samplePositionsX(:),samplePositionsY(:)];
% sample=getSpokeTarget(256,256,12,1);
% sample(1:end/2,1:end/2)=0;
% sample(1:end/2,end/2:end)=sample(1:end/2,end/2:end)/2;
% sample(end/2:end,1:end/2)=sample(end/2:end,1:end/2)/4;
%sample=getTestImage('usaf_512x512.png'); sample=sample(1:4:end,1:4:end);
sample=zeros(64);
% sample(1+floor(end/2),1+floor(end/2))=1;
sample(1+floor(end/2)-8+[1:3],1+floor(end/2)+[1:3])=1;
sample(1+floor(end/2)+[1:3],1+floor(end/2)+[1:3]+8)=1;
samplePixelPitch=[1 1]*25e-9;
xRangeSample=([1:size(sample,1)]-floor(size(sample,1)/2))*samplePixelPitch(1);
yRangeSample=([1:size(sample,2)]-floor(size(sample,2)/2))*samplePixelPitch(2);
figure; imagesc(yRangeSample*1e6,xRangeSample*1e6,sample); axis image; xlabel('x [\mum]'); ylabel('y [\mum]');
[sampleX sampleY]=ndgrid(xRangeSample,yRangeSample);
clear xRangeSample yRangeSample;
xRangeImg=([1:imgSize(1)*2]-1-imgSize(1))*pixelPitchInSample(1);
yRangeImg=([1:imgSize(2)*2]-1-imgSize(2))*pixelPitchInSample(2);
[imgX imgY]=ndgrid(xRangeImg,yRangeImg);
sigma=100e-9;
illumination=exp(-(imgX.^2+imgY.^2)./(2*sigma^2));
otf=fft2(ifftshift(illumination));
otf=otf./otf(1);
for posIdx=1:size(stagePositions,1),
fractionOfInput=posIdx/size(stagePositions,1)
stagePos=stagePositions(posIdx,:);
%shift
illuminatedSample=interpn(sampleX-stagePos(1),sampleY-stagePos(2),sample,imgX,imgY,'*cubic',0);
%simulate illumination
illuminatedSample=illuminatedSample.*illumination;
% simulate detection
img=ifft2(fft2(illuminatedSample).*otf,'symmetric');
% Crop padding again
img=circshift(img,-ceil(size(img)./4));
img=img(1:end/2,1:end/2);
%Add noise
img=img+0.001*randn(size(img));
% Store in two large matrices
if (posIdx>1)
recordedImages(:,:,posIdx)=img;
else
recordedImages=img;
end
% showImage(img*100);
% drawnow();
% pause(.02);
end
end
function [recordedImages samplePositions]=loadInputImages(inputImageFolder,regionOfInterest)
files=dir([inputImageFolder,'\*.png']);
posIdx=1;
for fileIdx=1:length(files),
fractionOfInput=fileIdx/length(files)
fileName=files(fileIdx).name;
samplePos=regexpi(fileName,'x(\d+)y(\d+)\.png','tokens');
if (~isempty(samplePos))
try
img=imread([inputImageFolder,'/',fileName]);
img=double(img)./255; % normalize to dynamic range
img=mean(img,3); % Convert to gray scale
% Reduce the ROI and create a sub folder if requested
if (~isempty(regionOfInterest))
img=img(regionOfInterest(1)+[1:regionOfInterest(3)]-1,regionOfInterest(2)+[1:regionOfInterest(4)]-1);
selectedROIFolder=[inputImageFolder,'selectedROI'];
if (~exist(selectedROIFolder,'dir'))
mkdir(selectedROIFolder);
end
imwrite(img,[selectedROIFolder,'/',fileName]);
end
samplePos=samplePos{1};
samplePos=str2double(samplePos)*1e-9/10; % 1/10 nm units
if (~all(samplePos==0)) % Ignorethe wide field image
% Store in two large matrices
if (posIdx>1)
recordedImages(:,:,posIdx)=img;
samplePositions(posIdx,:)=samplePos;
else
recordedImages=img;
samplePositions=samplePos(:).';
end
posIdx=posIdx+1;
else
logMessage('Skipping wide field image at coordinate (0,0).');
end
catch Exc
logMessage('Error reading file %s:',fileName);
logMessage(Exc.message)
end
else
logMessage('Skipping file %s, unrecognized file name.',fileName);
end
end
end
|
github
|
mc225/Softwares_Tom-master
|
mainpart.m
|
.m
|
Softwares_Tom-master/OpticalEigenModes/mainpart.m
| 8,988 |
utf_8
|
9925c355a9196baf25c88edc2d95e695
|
%%
function mainpart()
lgct=[];
%% new
%for na=namin:0.1:namax
na=0.65;
theta=asin(na);
prModes=probemodes(5,16,theta);
%% new end
lambda=0.8e-6;
q1=1.22*lambda/(2*na);%airy disk radius
qb=2.4*lambda/2/pi/sin(theta); %BB radius first zero
[x,y,z,t,nx,ny,nz,nt,ff]=probefields(5,16,theta);
dx=((max(x)-min(x))/nx);
%%
efx=squeeze(ff(1,:,:));
efy=squeeze(ff(2,:,:));
efz=squeeze(ff(3,:,:));
hfx=squeeze(ff(4,:,:));
hfy=squeeze(ff(5,:,:));
hfz=squeeze(ff(6,:,:));
%figure(1)
%ii=23;
%imagesc(reshape(abs(efx(ii,:)).^2+abs(efz(ii,:)).^2+abs(efy(ii,:)).^2+...
% abs(hfx(ii,:)).^2+abs(hfy(ii,:)).^2+abs(hfz(ii,:)).^2,nx,ny))
%%
ii=0;
rmax=3.65e-6;
%rmax=.4e-6:.01e-6:.47e-6;
dr=[];deff=[];
for roi=rmax
rr=x.^2+y.^2;
rmask=rr<(roi)^2;
op=repmat(rmask,size(efx,1),1);
maif=real((efx.*op)*hfy'-(efy.*op)*hfx');
[vec lam]=eig(maif);
dlam=real(diag(lam));
idx=(dlam>1e-2*max(dlam));
iev=vec(:,idx);
ilam=diag(1./sqrt(dlam(idx)));
av=iev*ilam;
op=repmat(rr.*rmask,size(efx,1),1);
maif2=av'*real((efx.*op)*hfy'-(efy.*op)*hfx')*av;
[vec2 lam2]=eig((maif2+maif2')/2);
dr=[dr sqrt(lam2(1,1))/q1];
deff=[deff 1/max(dlam)/((av*vec2(:,1))'*(av*vec2(:,1)))];
[roi sqrt(lam2(1,1)) ]
%new
figure(11)
qm=1;ii=ii+1;
lgc=av*vec2(:,qm);
lgc=lgc*sign(lgc(1));
lgct(ii,:)=lgc;
nlgc=lgc/abs(lgc(end));
plot(abs(nlgc).^2);drawnow;
thp0x=nlgc'*efx;thp0y=nlgc'*efy;thp0z=nlgc'*efz;
thp1x=nlgc'*hfx;thp1y=nlgc'*hfy;thp1z=nlgc'*hfz;
thp0=real(conj(thp0x).*thp1y-conj(thp0y).*thp1x);
thp=reshape(thp0,nx,ny);
ti2=sum(rmask.*thp0);
figure(3)
imagesc(thp);%title(['oei:' num2str(ti0/ti2)])
figure(4);
subplot(4,3,1);imagesc(reshape(real(thp0x),nx,ny));
subplot(4,3,2);imagesc(reshape(real(thp0y),nx,ny));
subplot(4,3,3);imagesc(reshape(real(thp0z),nx,ny));
subplot(4,3,4);imagesc(reshape(imag(thp0x),nx,ny));
subplot(4,3,5);imagesc(reshape(imag(thp0y),nx,ny));
subplot(4,3,6);imagesc(reshape(imag(thp0z),nx,ny));
subplot(4,3,7);imagesc(reshape(real(thp1x),nx,ny));
subplot(4,3,8);imagesc(reshape(real(thp1y),nx,ny));
subplot(4,3,9);imagesc(reshape(real(thp1z),nx,ny));
subplot(4,3,10);imagesc(reshape(imag(thp1x),nx,ny));
subplot(4,3,11);imagesc(reshape(imag(thp1y),nx,ny));
subplot(4,3,12);imagesc(reshape(imag(thp1z),nx,ny));
%%
return;
[xslm,yslm]=meshgrid(1:800,1:600);
rslm=sqrt((xslm-400).^2+(yslm-300).^2);
irs=rslm<260;
figure(4)
ma1=0*xslm;
ma1(irs)=interp1(0:260/(16-1):260,nlgc,rslm(irs));
imagesc(ma1)
ma(1,:,:)=ma1;
tname(1)={'OEi'};
efi(1)=sum(sum(abs(ma1).^2));
%save(['/Users/mm17/Desktop/oeimask.mat'],'ma','title');
%%
%%new
nroi=rmax/wave;
kv=sin(prModes(:,2)); % [omega, gamma]
end
%%new end
%additional masks
ma1=0*xslm;
ma1(irs)=1;
ma(2,:,:)=ma1;
tname(2)={'Dif. Limited'};
efi(2)=sum(sum(abs(ma1).^2));
irs=rslm<260*sqrt(.8);
ma1=0*xslm;
ma1(irs)=1;
ma(3,:,:)=ma1;
tname(3)={'Truncated R=80%'};
efi(3)=sum(sum(abs(ma1).^2));
efi/efi(2)
irs=rslm<260*sqrt(.6);
ma1=0*xslm;
ma1(irs)=1;
ma(4,:,:)=ma1;
tname(4)={'Truncated R=60%'};
efi(4)=sum(sum(abs(ma1).^2));
efi/efi(2)
irs=rslm<260*sqrt(.4);
ma1=0*xslm;
ma1(irs)=1;
ma(5,:,:)=ma1;
tname(5)={'Truncated R=40%'};
efi(5)=sum(sum(abs(ma1).^2));
efi/efi(2)
stop
%%
for ii=1:16
lgc0=0*lgc;lgc0(ii)=1;
thp0x=lgc0'*efx;thp0y=lgc0'*efy;thp0z=lgc0'*efz;
thp1x=lgc0'*hfx;thp1y=lgc0'*hfy;thp1z=lgc0'*hfz;
thp0=real(conj(thp0x).*thp1y-conj(thp0y).*thp1x);
thp=reshape(thp0,nx,ny);
figure(6);subplot(4,4,ii)
imagesc(thp);axis equal
end
%
%%
qm=1;
lgc=av*vec2(:,qm);
thp0x=lgc'*efx;thp0y=lgc'*efy;thp0z=lgc'*efz;
thp1x=lgc'*hfx;thp1y=lgc'*hfy;thp1z=lgc'*hfz;
thp0=abs(thp0x.^2)+abs(thp0y.^2)+abs(thp0z.^2)+abs(thp1x.^2)+abs(thp1y.^2)+abs(thp1z.^2);
ImageHandle=figure(2);
thp=reshape(thp0,nx,ny);
ma=reshape(rmask,nx,ny);
xx=reshape(x,nx,ny);
yy=reshape(y,nx,ny);
zpos=thp;zpos(~ma)=NaN;
zrgb=sc(zpos,'jet');
zpos2=thp;zpos2(ma)=NaN;
zrgb2=sc(zpos2,'gray');
sh(1)=imagesc(zrgb2);
%%%%%colorbar('location','east')
hold on
sh(2)=imagesc(zrgb);
%%%%%set(sh,'edgecolor','none')
set(sh(2),'alphadata',ma)
axis equal;
%colorbar('location','west')
max((1-rmask).*thp0)/max((rmask).*thp0);
set(ImageHandle,'units','centimeters','position',[5 5 15 15]) % set the screen size and position
set(ImageHandle,'paperunits','centimeters','paperposition',[6 6 14 14]) % set size and position for printing
set(gca,'units','normalized','position',[0 0 1 1]) % make sure axis fills entire figure
%%
rad=sqrt(max(rr(rmask)))/((max(x)-min(x))/nx);
ImageHandle=figure(4);
thp=reshape(thp0,nx,ny)/max(thp0);
hold on;imshow(thp*256,jet(256));axis equal;
plot((nx)/2+1+rad*cos(0:pi/30:2*pi),(ny)/2+1+rad*sin((0:pi/30:2*pi)),'--y','LineWidth',3);drawnow
sqrt(2*sum(sum((abs(rmask.*(x.^2+y.^2).*thp0))))/sum(sum((abs(rmask.*thp0)))))
set(ImageHandle,'units','centimeters','position',[5 5 15 15]) % set the screen size and position
set(ImageHandle,'paperunits','centimeters','paperposition',[6 6 14 14]) % set size and position for printing
set(gca,'units','normalized','position',[0 0 1 1]) % make sure axis fills entire figure
stop
%%
figure(1)
%quiver(reshape(real(thp0x),nx,ny),reshape(real(thp0y),nx,ny));axis equal; drawnow
quiver(reshape(real(rmask.*thp0x),nx,ny),reshape(real(rmask.*thp0y),nx,ny));axis equal; drawnow
figure(3)
%quiver(reshape(real(thp0x),nx,ny),reshape(real(thp0y),nx,ny));axis equal; drawnow
subplot(2,3,1);imagesc(reshape(real(thp0x),nx,ny));axis equal;
subplot(2,3,2);imagesc(reshape(real(thp0y),nx,ny));axis equal;
subplot(2,3,3);imagesc(reshape(real(thp0z),nx,ny));axis equal;
subplot(2,3,4);imagesc(reshape(real(thp1x),nx,ny));axis equal;
subplot(2,3,5);imagesc(reshape(real(thp1y),nx,ny));axis equal;
subplot(2,3,6);imagesc(reshape(real(thp1z),nx,ny));axis equal;
%% first intenisty eigemode
figure(5)
lgc=av(:,1);
thp0x=lgc'*efx;thp0y=lgc'*efy;thp0z=lgc'*efz;
thp1x=lgc'*hfx;thp1y=lgc'*hfy;thp1z=lgc'*hfz;
thp0=abs(thp0x.^2)+abs(thp0y.^2)+abs(thp0z.^2)+abs(thp1x.^2)+abs(thp1y.^2)+abs(thp1z.^2);
thp=reshape(rmask.*thp0,nx,ny);
imagesc(thp);axis equal; drawnow
sqrt(sum(sum((abs(rmask.*(x.^2+y.^2).*thp0))))/sum(sum((abs(rmask.*thp0)))))
%% max Bessel
ImageHandle=figure(6);
lgc=zeros(size(av,1),1);lgc(end)=1;
thp0x=lgc'*efx;thp0y=lgc'*efy;thp0z=lgc'*efz;
thp1x=lgc'*hfx;thp1y=lgc'*hfy;thp1z=lgc'*hfz;
thp0=abs(thp0x.^2)+abs(thp0y.^2)+abs(thp0z.^2)+abs(thp1x.^2)+abs(thp1y.^2)+abs(thp1z.^2);
thp=reshape(thp0,nx,ny)/max(thp0);
imshow(thp*256,jet(256));axis equal; hold on;
rb=qb/dx;
plot((nx)/2+1+rb*cos(0:pi/30:2*pi),(ny)/2+1+rb*sin((0:pi/30:2*pi)),'--y','LineWidth',3);drawnow
hold off
rmask=rr<(qb)^2;
sqrt(2*sum(sum((abs(rmask.*(x.^2+y.^2).*thp0))))/sum(sum((abs(rmask.*thp0)))))
set(ImageHandle,'units','centimeters','position',[6 6 15 15]) % set the screen size and position
set(ImageHandle,'paperunits','centimeters','paperposition',[5 5 16 16]) % set size and position for printing
set(gca,'units','normalized','position',[0 0 1 1]) % make sure axis fills entire figure
Iseg = getframe(ImageHandle);
imwrite(Iseg.cdata,'/Users/mm17/Documents/OLDmac/Desktop/QME-OPEX/maxbessel.1.png')
%% Airy disk Bessel
close(6)
dx=((max(x)-min(x))/nx);
ImageHandle=figure(6);
thp0=(2*besselj(1,sqrt(rr)/q1*3.83)./sqrt(rr)).^2;
thp=reshape(thp0,nx,ny)/max(thp0);
imshow(thp*256,jet(256));axis equal;
hold on
rb=q1/dx;
plot((nx)/2+1+rb*cos(0:pi/30:2*pi),(ny)/2+1+rb*sin((0:pi/30:2*pi)),'--y','LineWidth',3);drawnow
hold off;
set(ImageHandle,'units','centimeters','position',[6 6 15 15]) % set the screen size and position
set(ImageHandle,'paperunits','centimeters','paperposition',[5 5 16 16]) % set size and position for printing
set(gca,'units','normalized','position',[0 0 1 1]) % make sure axis fills entire figure
Iseg = getframe(ImageHandle);
imwrite(Iseg.cdata,'/Users/mm17/Documents/OLDmac/Desktop/QME-OPEX/airy.1.png')
rmask=rr<(q1)^2;
sqrt(2*sum(sum((abs(rmask.*(x.^2+y.^2).*thp0))))/sum(sum((abs(rmask.*thp0)))))
end
|
github
|
mc225/Softwares_Tom-master
|
probemodes.m
|
.m
|
Softwares_Tom-master/OpticalEigenModes/probemodes.m
| 3,315 |
utf_8
|
6333da58fd1d9b68da4518baedffa662
|
%%%
%type=1 bessel
% Row vectors for each mode containing:
% param(1)=omega %optical frequency :wavelength=2 pi c/(omega)
% param(2)=gamma %cone angle
% param(3)=pol %A polaraisation 1:vert; 2:horiz; 3:longi;
% param(4)=L %L number
% param(5)=n %index of refraction
function prmodes=probemodes(type,num,theta)
c=299792458;
switch type
case 1
param(1)=1.884e15; %optical frequency :wavelength=2 pi c/(omega)
param(2)=.6; %cone anlge
param(3)=1; %A polaraisation 1:vert; 2:horiz; 3:longi;
param(4)=4; %L number
param(5)=1; %index
prmodes=[];
for j0=1:2
for j2=-0:0
for j1=1:num
param(2)=(j1-1)/(num)*theta;
param(3)=j0;
param(4)=j2;
prmodes=[prmodes;param];
end
end
end
case 2
param(1)=1.884e15; %optical frequency :wavelength=2 pi c/(omega)
param(2)=.6; %cone anlge
param(3)=2; %A polaraisation 1:vert; 2:horiz;
param(4)=4; %L number
param(5)=1; %index
prmodes=[];
for j0=1:1 % pol
for j2=-0:0 % L
for j1=1:num
% param(2)=(j1-1)/(num)*theta;
% param(2)=asin((j1-1)/(num-1)*sin(theta));
param(2)=asin((j1-.5)/(num-1)*sin(theta));
param(3)=j0;
param(4)=j2;
prmodes=[prmodes;param];
end
end
end
case 4
param(1)=2*pi*3e8/0.8e-6; %optical frequency :wavelength=2 pi c/(omega)
param(2)=.6; %cone anlge
param(3)=2; %A polaraisation 1:vert; 2:horiz;
param(4)=0; %L number
param(5)=1; %index
prmodes=[];
for j0=1:1 % pol
for j2=-0:0 % L
for j1=1:num
% param(2)=(j1-1)/(num)*theta;
% param(2)=asin((j1-1)/(num-1)*sin(theta));
param(2)=asin((j1-.5)/(num-1)*sin(theta));
param(3)=j0;
param(4)=j2;
prmodes=[prmodes;param];
end
end
end
case 5
param(1)=2*pi*c/0.8e-6; %optical frequency :wavelength=2 pi c/(omega)
param(2)=.6; %cone angle
param(3)=2; %A polaraisation 1:vert; 2:horiz;
param(4)=0; %L number
param(5)=1; %index
prmodes=[];
for j0=1:2 % pol
for j2=-2:2 % L
for j1=1:num
% param(2)=(j1-1)/(num)*theta;
% param(2)=asin((j1-1)/(num-1)*sin(theta));
param(2)=asin((j1-.5)/(num-1)*sin(theta));
param(3)=j0;
param(4)=j2;
prmodes=[prmodes;param];
end
end
end
end
end
|
github
|
mc225/Softwares_Tom-master
|
savejson.m
|
.m
|
Softwares_Tom-master/ThirdPartyDependencies/jsonlab/savejson.m
| 13,894 |
utf_8
|
e7cec5b8f38043b1b4c02348911ff07b
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 371 2012-06-20 12:43:06Z fangq $
%
% input:
% rootname: name of the root-object, if set to '', will use variable name
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output JSON data
% opt: a struct for additional options, use [] if all use default
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% a=struct('node',[1 9 10; 2 1 1.2], 'elem',[9 1;1 2;2 3],...
% 'face',[9 01 2; 1 2 3; NaN,Inf,-Inf], 'author','FangQ');
% savejson('mesh',a)
% savejson('',a,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
varname=inputname(2);
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s\n',json);
else
json=sprintf('{\n%s\n}\n',json);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);\n',jsonp,json);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
len=numel(item); % let's handle 1D cell first
padding1=repmat(sprintf('\t'),1,level-1);
padding0=repmat(sprintf('\t'),1,level);
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [\n',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[\n',padding0);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": null',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%snull',padding0);
end
end
for i=1:len
txt=sprintf('%s%s%s',txt,padding1,obj2json(name,item{i},level+(len>1),varargin{:}));
if(i<len) txt=sprintf('%s%s',txt,sprintf(',\n')); end
end
if(len>1) txt=sprintf('%s\n%s]',txt,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
len=numel(item);
padding1=repmat(sprintf('\t'),1,level-1);
padding0=repmat(sprintf('\t'),1,level);
sep=',';
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [\n',padding0,checkname(name,varargin{:})); end
else
if(len>1) txt=sprintf('%s[\n',padding0); end
end
for e=1:len
names = fieldnames(item(e));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {\n',txt,repmat(sprintf('\t'),1,level+(len>1)), checkname(name,varargin{:}));
else
txt=sprintf('%s%s{\n',txt,repmat(sprintf('\t'),1,level+(len>1)));
end
if(~isempty(names))
for i=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{i},getfield(item(e),...
names{i}),level+1+(len>1),varargin{:}));
if(i<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,sprintf('\n'));
end
end
txt=sprintf('%s%s}',txt,repmat(sprintf('\t'),1,level+(len>1)));
if(e==len) sep=''; end
if(e<len) txt=sprintf('%s%s',txt,sprintf(',\n')); end
end
if(len>1) txt=sprintf('%s\n%s]',txt,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
sep=sprintf(',\n');
padding1=repmat(sprintf('\t'),1,level);
padding0=repmat(sprintf('\t'),1,level+1);
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [\n',padding1,checkname(name,varargin{:})); end
else
if(len>1) txt=sprintf('%s[\n',padding1); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,repmat(sprintf('\t'),1,level),obj);
else
txt=sprintf('%s%s%s%s',txt,repmat(sprintf('\t'),1,level+1),['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s\n%s%s',txt,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
padding1=repmat(sprintf('\t'),1,level);
padding0=repmat(sprintf('\t'),1,level+1);
if(length(size(item))>2 || issparse(item) || ~isreal(item) || jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{\n%s"_ArrayType_": "%s",\n%s"_ArraySize_": %s,\n',...
padding1,padding0,class(item),padding0,regexprep(mat2str(size(item)),'\s+',',') );
else
txt=sprintf('%s"%s": {\n%s"_ArrayType_": "%s",\n%s"_ArraySize_": %s,\n',...
padding1,checkname(name,varargin{:}),padding0,class(item),padding0,regexprep(mat2str(size(item)),'\s+',',') );
end
else
if(isempty(name))
txt=sprintf('%s%s',padding1,matdata2json(item,level+1,varargin{:}));
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),matdata2json(item,level+1,varargin{:}));
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sprintf(',\n'));
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sprintf(',\n'));
if(find(size(item)==1))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), sprintf('\n'));
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), sprintf('\n'));
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), sprintf('\n'));
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sprintf(',\n'));
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), sprintf('\n'));
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[\n');
post=sprintf('\n%s]',repmat(sprintf('\t'),1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],\n')]];
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(sprintf('\t'),1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-1:end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function val=jsonopt(key,default,varargin)
val=default;
if(nargin<=2) return; end
opt=varargin{1};
if(isstruct(opt) && isfield(opt,key))
val=getfield(opt,key);
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
|
github
|
mc225/Softwares_Tom-master
|
loadjson.m
|
.m
|
Softwares_Tom-master/ThirdPartyDependencies/jsonlab/loadjson.m
| 15,312 |
ibm852
|
54a5e8d8b39c77904a572c96f3df77a5
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% date: 2011/09/09
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% date: 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% date: 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% date: 2008/07/03
%
% $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs. The param string is equivallent
% to a field in opt.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rt');
string = fscanf(fid,'%c');
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
else
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
if next_char ~= ']'
[endpos e1l e1r maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(find(arraystr==sprintf('\n')))=[];
arraystr(find(arraystr==sprintf('\r')))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(find(astr==sprintf('\n')))=[];
astr(find(astr==sprintf('\r')))=[];
astr(find(astr==' '))='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(find(astr==' '))='';
[obj count errmsg nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(find(astr=='['))='';
astr(find(astr==']'))='';
astr(find(astr==' '))='';
[obj count errmsg nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
try
object=cell2mat(object')';
if(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
parse_char(']');
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
mc225/Softwares_Tom-master
|
DataHash.m
|
.m
|
Softwares_Tom-master/ThirdPartyDependencies/DataHash/DataHash.m
| 15,429 |
utf_8
|
e725a80cb9180de1eb03e47b850a95dc
|
function Hash = DataHash(Data, Opt)
% DATAHASH - Checksum for Matlab array of any type
% This function creates a hash value for an input of any type. The type and
% dimensions of the input are considered as default, such that UINT8([0,0]) and
% UINT16(0) have different hash values. Nested STRUCTs and CELLs are parsed
% recursively.
%
% Hash = DataHash(Data, Opt)
% INPUT:
% Data: Array of these built-in types:
% (U)INT8/16/32/64, SINGLE, DOUBLE, (real or complex)
% CHAR, LOGICAL, CELL (nested), STRUCT (scalar or array, nested),
% function_handle.
% Opt: Struct to specify the hashing algorithm and the output format.
% Opt and all its fields are optional.
% Opt.Method: String, known methods for Java 1.6 (Matlab 2009a):
% 'SHA-1', 'SHA-256', 'SHA-384', 'SHA-512', 'MD2', 'MD5'.
% Known methods for Java 1.3 (Matlab 6.5):
% 'MD5', 'SHA-1'.
% Default: 'MD5'.
% Opt.Format: String specifying the output format:
% 'hex', 'HEX': Lower/uppercase hexadecimal string.
% 'double', 'uint8': Numerical vector.
% 'base64': Base64 encoded string, only printable
% ASCII characters, 33% shorter than 'hex'.
% Default: 'hex'.
% Opt.Input: Type of the input as string, not case-sensitive:
% 'array': The contents, type and size of the input [Data] are
% considered for the creation of the hash. Nested CELLs
% and STRUCT arrays are parsed recursively. Empty arrays of
% different type reply different hashs.
% 'file': [Data] is treated as file name and the hash is calculated
% for the files contents.
% 'bin': [Data] is a numerical, LOGICAL or CHAR array. Only the
% binary contents of the array is considered, such that
% e.g. empty arrays of different type reply the same hash.
% Default: 'array'.
%
% OUTPUT:
% Hash: String, DOUBLE or UINT8 vector. The length depends on the hashing
% method.
%
% EXAMPLES:
% % Default: MD5, hex:
% DataHash([]) % 7de5637fd217d0e44e0082f4d79b3e73
% % MD5, Base64:
% Opt.Format = 'base64';
% Opt.Method = 'MD5';
% DataHash(int32(1:10), Opt) % bKdecqzUpOrL4oxzk+cfyg
% % SHA-1, Base64:
% S.a = uint8([]);
% S.b = {{1:10}, struct('q', uint64(415))};
% Opt.Method = 'SHA-1';
% DataHash(S, Opt) % ZMe4eUAp0G9TDrvSW0/Qc0gQ9/A
% % SHA-1 of binary values:
% Opt.Method = 'SHA-1';
% Opt.Input = 'bin';
% DataHash(1:8, Opt) % 826cf9d3a5d74bbe415e97d4cecf03f445f69225
%
% NOTE:
% Function handles and user-defined objects cannot be converted uniquely:
% - The subfunction ConvertFuncHandle uses the built-in function FUNCTIONS,
% but the replied struct can depend on the Matlab version.
% - It is tried to convert objects to UINT8 streams in the subfunction
% ConvertObject. A conversion by STRUCT() might be more appropriate.
% Adjust these subfunctions on demand.
%
% MATLAB CHARs have 16 bits! In consequence the string 'hello' is treated as
% UINT16('hello') for the binary input method.
%
% DataHash uses James Tursa's smart and fast TYPECASTX, if it is installed:
% http://www.mathworks.com/matlabcentral/fileexchange/17476
% As fallback the built-in TYPECAST is used automatically, but for large
% inputs this can be more than 100 times slower.
% For Matlab 6.5 installing typecastx is obligatory to run DataHash.
%
% Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64
% Author: Jan Simon, Heidelberg, (C) 2011-2012 matlab.THISYEAR(a)nMINUSsimon.de
%
% See also: TYPECAST, CAST.
% FEX:
% Michael Kleder, "Compute Hash", no structs and cells:
% http://www.mathworks.com/matlabcentral/fileexchange/8944
% Tim, "Serialize/Deserialize", converts structs and cells to a byte stream:
% http://www.mathworks.com/matlabcentral/fileexchange/29457
% Jan Simon, "CalcMD5", MD5 only, faster C-mex, no structs and cells:
% http://www.mathworks.com/matlabcentral/fileexchange/25921
% $JRev: R-k V:011 Sum:kZG25iszfKbg Date:28-May-2012 12:48:06 $
% $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
% $File: Tools\GLFile\DataHash.m $
% History:
% 001: 01-May-2011 21:52, First version.
% 007: 10-Jun-2011 10:38, [Opt.Input], binary data, complex values considered.
% 011: 26-May-2012 15:57, Fails for binary input and empty data.
% Main function: ===============================================================
% Java is needed:
if ~usejava('jvm')
error(['JSimon:', mfilename, ':NoJava'], ...
'*** %s: Java is required.', mfilename);
end
% typecastx creates a shared data copy instead of the deep copy as Matlab's
% TYPECAST - for a [1000x1000] DOUBLE array this is 100 times faster!
persistent usetypecastx
if isempty(usetypecastx)
usetypecastx = ~isempty(which('typecastx')); % Run the slow WHICH once only
end
% Default options: -------------------------------------------------------------
Method = 'MD5';
OutFormat = 'hex';
isFile = false;
isBin = false;
% Check number and type of inputs: ---------------------------------------------
nArg = nargin;
if nArg == 2
if isa(Opt, 'struct') == 0 % Bad type of 2nd input:
error(['JSimon:', mfilename, ':BadInput2'], ...
'*** %s: 2nd input [Opt] must be a struct.', mfilename);
end
% Specify hash algorithm:
if isfield(Opt, 'Method')
Method = upper(Opt.Method);
end
% Specify output format:
if isfield(Opt, 'Format')
OutFormat = Opt.Format;
end
% Check if the Input type is specified - default: 'array':
if isfield(Opt, 'Input')
if strcmpi(Opt.Input, 'File')
isFile = true;
if ischar(Data) == 0
error(['JSimon:', mfilename, ':CannotOpen'], ...
'*** %s: 1st input is not a file name', mfilename);
end
if exist(Data, 'file') ~= 2
error(['JSimon:', mfilename, ':FileNotFound'], ...
'*** %s: File not found: %s.', mfilename, Data);
end
elseif strncmpi(Opt.Input, 'bin', 3) % Accept 'binary'
isBin = true;
if (isnumeric(Data) || ischar(Data) || islogical(Data)) == 0
error(['JSimon:', mfilename, ':BadDataType'], ...
'*** %s: 1st input is not numeric, CHAR or LOGICAL.', mfilename);
end
end
end
elseif nArg ~= 1 % Bad number of arguments:
error(['JSimon:', mfilename, ':BadNInput'], ...
'*** %s: 1 or 2 inputs required.', mfilename);
end
% Create the engine: -----------------------------------------------------------
try
Engine = java.security.MessageDigest.getInstance(Method);
catch
error(['JSimon:', mfilename, ':BadInput2'], ...
'*** %s: Invalid algorithm: [%s].', mfilename, Method);
end
% Create the hash value: -------------------------------------------------------
if isFile
% Read the file and calculate the hash:
FID = fopen(Data, 'r');
if FID < 0
error(['JSimon:', mfilename, ':CannotOpen'], ...
'*** %s: Cannot open file: %s.', mfilename, Data);
end
Data = fread(FID, Inf, '*uint8');
fclose(FID);
Engine.update(Data);
if usetypecastx
Hash = typecastx(Engine.digest, 'uint8');
else
Hash = typecast(Engine.digest, 'uint8');
end
elseif isBin % Contents of an elementary array:
if isempty(Data) % Nothing to do, Engine.update fails for empty input!
Hash = typecastx(Engine.digest, 'uint8');
elseif usetypecastx % Faster typecastx:
if isreal(Data)
Engine.update(typecastx(Data(:), 'uint8'));
else
Engine.update(typecastx(real(Data(:)), 'uint8'));
Engine.update(typecastx(imag(Data(:)), 'uint8'));
end
Hash = typecastx(Engine.digest, 'uint8');
else % Matlab's TYPECAST is less elegant:
if isnumeric(Data)
if isreal(Data)
Engine.update(typecast(Data(:), 'uint8'));
else
Engine.update(typecast(real(Data(:)), 'uint8'));
Engine.update(typecast(imag(Data(:)), 'uint8'));
end
elseif islogical(Data) % TYPECAST cannot handle LOGICAL
Engine.update(typecast(uint8(Data(:)), 'uint8'));
elseif ischar(Data) % TYPECAST cannot handle CHAR
Engine.update(typecast(uint16(Data(:)), 'uint8'));
Engine.update(typecast(Data(:), 'uint8'));
end
Hash = typecast(Engine.digest, 'uint8');
end
elseif usetypecastx % Faster typecastx:
Engine = CoreHash_(Data, Engine);
Hash = typecastx(Engine.digest, 'uint8');
else % Slower built-in TYPECAST:
Engine = CoreHash(Data, Engine);
Hash = typecast(Engine.digest, 'uint8');
end
% Convert hash specific output format: -----------------------------------------
switch OutFormat
case 'hex'
Hash = sprintf('%.2x', double(Hash));
case 'HEX'
Hash = sprintf('%.2X', double(Hash));
case 'double'
Hash = double(reshape(Hash, 1, []));
case 'uint8'
Hash = reshape(Hash, 1, []);
case 'base64'
Hash = fBase64_enc(double(Hash));
otherwise
error(['JSimon:', mfilename, ':BadOutFormat'], ...
'*** %s: [Opt.Format] must be: HEX, hex, uint8, double, base64.', ...
mfilename);
end
% return;
% ******************************************************************************
function Engine = CoreHash_(Data, Engine)
% This mothod uses the faster typecastx version.
% Consider the type and dimensions of the array to distinguish arrays with the
% same data, but different shape: [0 x 0] and [0 x 1], [1,2] and [1;2],
% DOUBLE(0) and SINGLE([0,0]):
Engine.update([uint8(class(Data)), typecastx(size(Data), 'uint8')]);
if isstruct(Data) % Hash for all array elements and fields:
F = sort(fieldnames(Data)); % Ignore order of fields
Engine = CoreHash_(F, Engine); % Catch the fieldnames
for iS = 1:numel(Data) % Loop over elements of struct array
for iField = 1:length(F) % Loop over fields
Engine = CoreHash_(Data(iS).(F{iField}), Engine);
end
end
elseif iscell(Data) % Get hash for all cell elements:
for iS = 1:numel(Data)
Engine = CoreHash_(Data{iS}, Engine);
end
elseif isnumeric(Data) || islogical(Data) || ischar(Data)
if isempty(Data) == 0
if isreal(Data) % TRUE for LOGICAL and CHAR also:
Engine.update(typecastx(Data(:), 'uint8'));
else % typecastx accepts complex input:
Engine.update(typecastx(real(Data(:)), 'uint8'));
Engine.update(typecastx(imag(Data(:)), 'uint8'));
end
end
elseif isa(Data, 'function_handle')
Engine = CoreHash(ConvertFuncHandle(Data), Engine);
else % Most likely this is a user-defined object:
try
Engine = CoreHash(ConvertObject(Data), Engine);
catch
warning(['JSimon:', mfilename, ':BadDataType'], ...
['Type of variable not considered: ', class(Data)]);
end
end
% return;
% ******************************************************************************
function Engine = CoreHash(Data, Engine)
% This methods uses the slower TYPECAST of Matlab
% See CoreHash_ for comments.
Engine.update([uint8(class(Data)), typecast(size(Data), 'uint8')]);
if isstruct(Data) % Hash for all array elements and fields:
F = sort(fieldnames(Data)); % Ignore order of fields
Engine = CoreHash(F, Engine); % Catch the fieldnames
for iS = 1:numel(Data) % Loop over elements of struct array
for iField = 1:length(F) % Loop over fields
Engine = CoreHash(Data(iS).(F{iField}), Engine);
end
end
elseif iscell(Data) % Get hash for all cell elements:
for iS = 1:numel(Data)
Engine = CoreHash(Data{iS}, Engine);
end
elseif isempty(Data)
elseif isnumeric(Data)
if isreal(Data)
Engine.update(typecast(Data(:), 'uint8'));
else
Engine.update(typecast(real(Data(:)), 'uint8'));
Engine.update(typecast(imag(Data(:)), 'uint8'));
end
elseif islogical(Data) % TYPECAST cannot handle LOGICAL
Engine.update(typecast(uint8(Data(:)), 'uint8'));
elseif ischar(Data) % TYPECAST cannot handle CHAR
Engine.update(typecast(uint16(Data(:)), 'uint8'));
elseif isa(Data, 'function_handle')
Engine = CoreHash(ConvertFuncHandle(Data), Engine);
else % Most likely a user-defined object:
try
Engine = CoreHash(ConvertObject(Data), Engine);
catch
warning(['JSimon:', mfilename, ':BadDataType'], ...
['Type of variable not considered: ', class(Data)]);
end
end
% return;
% ******************************************************************************
function FuncKey = ConvertFuncHandle(FuncH)
% The subfunction ConvertFuncHandle converts function_handles to a struct
% using the Matlab function FUNCTIONS. The output of this function changes
% with the Matlab version, such that DataHash(@sin) replies different hashes
% under Matlab 6.5 and 2009a.
% An alternative is using the function name and name of the file for
% function_handles, but this is not unique for nested or anonymous functions.
% If the MATLABROOT is removed from the file's path, at least the hash of
% Matlab's toolbox functions is (usually!) not influenced by the version.
% Finally I'm in doubt if there is a unique method to hash function handles.
% Please adjust the subfunction ConvertFuncHandles to your needs.
% The Matlab version influences the conversion by FUNCTIONS:
% 1. The format of the struct replied FUNCTIONS is not fixed,
% 2. The full paths of toolbox function e.g. for @mean differ.
FuncKey = functions(FuncH);
% ALTERNATIVE: Use name and path. The <matlabroot> part of the toolbox functions
% is replaced such that the hash for @mean does not depend on the Matlab
% version.
% Drawbacks: Anonymous functions, nested functions...
% funcStruct = functions(FuncH);
% funcfile = strrep(funcStruct.file, matlabroot, '<MATLAB>');
% FuncKey = uint8([funcStruct.function, ' ', funcfile]);
% Finally I'm afraid there is no unique method to get a hash for a function
% handle. Please adjust this conversion to your needs.
% return;
% ******************************************************************************
function DataBin = ConvertObject(DataObj)
% Convert a user-defined object to a binary stream. There cannot be a unique
% solution, so this part is left for the user...
% Perhaps a direct conversion is implemented:
DataBin = uint8(DataObj);
% Or perhaps this is better:
% DataBin = struct(DataObj);
% return;
% ******************************************************************************
function Out = fBase64_enc(In)
% Encode numeric vector of UINT8 values to base64 string.
Pool = [65:90, 97:122, 48:57, 43, 47]; % [0:9, a:z, A:Z, +, /]
v8 = [128; 64; 32; 16; 8; 4; 2; 1];
v6 = [32, 16, 8, 4, 2, 1];
In = reshape(In, 1, []);
X = rem(floor(In(ones(8, 1), :) ./ v8(:, ones(length(In), 1))), 2);
Y = reshape([X(:); zeros(6 - rem(numel(X), 6), 1)], 6, []);
Out = char(Pool(1 + v6 * Y));
% return;
|
github
|
mc225/Softwares_Tom-master
|
poisson.m
|
.m
|
Softwares_Tom-master/ThirdPartyDependencies/poisson/poisson.m
| 934 |
utf_8
|
1df23401d580bc81ca94c8e6aac9f1b5
|
function data = poisson(xm, seed)
%function data = poisson(xm, seed)
%
% Generate Poisson random vector with mean xm.
% For small, use poisson1.m
% For large, use poisson2.m
% see num. rec. C, P. 222
%
% Copyright 1997-4-29, Jeff Fessler, The University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && strcmp(xm, 'test'), poisson_test, return, end
if ~isvar('seed')
seed = [];
end
data = xm;
xm = xm(:);
small = xm < 12;
data( small) = poisson1(xm( small), seed);
data(~small) = poisson2(xm(~small), seed);
%
% run a timing race against matlab's poissrnd
%
function poisson_test
n = 2^8;
t = reshape(linspace(1, 1000, n^2), n, n);
cpu tic
poisson(t);
cpu toc 'fessler poisson time'
tic
poissrnd(t);
cpu toc 'matlab poissrnd time'
if 0 % look for bad values?
poisson(10^6 * ones(n,n));
poisson(1e-6 * ones(n,n));
poisson(linspace(11,13,2^10+1));
poisson(linspace(12700,91800,n^3));
end
|
github
|
mc225/Softwares_Tom-master
|
cpu.m
|
.m
|
Softwares_Tom-master/ThirdPartyDependencies/poisson/cpu.m
| 1,220 |
utf_8
|
63fff9efef6377a81db14161edbf486d
|
function out = cpu(arg, varargin)
%function out = cpu(arg, varargin)
% cpu tic
% cpu toc
% cpu toc printarg
% work like tic/toc except they use cpu time instead of wall time.
% also:
% cpu etic
% cpu etoc
% for elapsed time
if nargin < 1, help(mfilename), error(mfilename), end
if streq(arg, 'test'), cpu_test, return, end
% todo: add default behaviour
persistent t
if ~isvar('t') || isempty(t)
t.tic = [];
t.clock = [];
end
if streq(arg, 'tic')
t.tic = cputime;
if length(varargin), error 'tic takes no option', end
return
elseif streq(arg, 'etic')
t.clock = clock;
if length(varargin), error 'tic takes no option', end
return
end
if streq(arg, 'toc')
if isempty(t.tic)
error 'must initialize cpu with tic first'
end
out = cputime - t.tic;
elseif streq(arg, 'etoc')
if isempty(t.clock)
error 'must initialize cpu with etic first'
end
out = etime(clock, t.clock);
else
error 'bad argument'
end
if length(varargin) == 1
arg = varargin{1};
if ischar(arg)
printf('%s %g', arg, out)
end
if ~nargout
clear out
end
elseif length(varargin) > 1
error 'too many arguments'
end
function cpu_test
cpu tic
cpu toc
cpu toc hello
cpu etic
cpu etoc
cpu etoc goodbye
out = cpu('etoc', 'test');
|
github
|
mc225/Softwares_Tom-master
|
poisson2.m
|
.m
|
Softwares_Tom-master/ThirdPartyDependencies/poisson/poisson2.m
| 1,274 |
utf_8
|
cc7f650c26ba423cb63b682beb1c27e4
|
function data = poisson2(xm, seed)
%function data = poisson2(xm, seed)
% Generate Poisson random column vector with mean xm.
% Uses rejection method - good for large values of xm.
% See "Numerical Recipes in C", P. 222.
if nargin < 2, help(mfilename), error(mfilename), end
if isvar('seed') & ~isempty(seed)
rand('state', seed)
end
data = zeros(size(xm));
if any(xm < 0), error 'negative poisson means?', end
data(xm > 0) = poisson2_positive(xm(xm > 0));
%
% poisson2_positive()
%
function data = poisson2_positive(xm)
sx = sqrt(2.0 * xm);
lx = log(xm);
gx = xm .* lx - gammaln(1 + xm);
data = zeros(size(xm));
id = [1:length(xm)]'; % indicates which data left to do
%factor = 0.9; % from num rec
factor = 0.85; % seems to work better
while any(id)
Tss = sx(id);
Tll = lx(id);
Tgg = gx(id);
Txx = xm(id);
yy = zeros(size(id));
em = zeros(size(id));
ib = true(size(id));
while ib
yy(ib) = tan(pi * rand(size(ib)));
em(ib) = Tss(ib) .* yy(ib) + Txx(ib);
ib = find(em < 0);
end
em = floor(em);
tt = factor * (1+yy.*yy) .* exp(em .* Tll - gammaln(em+1) - Tgg);
if any(tt > 1)
% pr xm(tt > 1)
% pr max(tt)
error('factor is too large! please report xm value(s)')
end
ig = rand(size(id)) < tt;
data(id(ig(:))) = em(ig);
id = id(~ig(:));
end
|
github
|
mc225/Softwares_Tom-master
|
dftregistration.m
|
.m
|
Softwares_Tom-master/ThirdPartyDependencies/efficient_subpixel_registration/dftregistration.m
| 8,250 |
utf_8
|
93265582c4fb73f52c4000db5038f40f
|
% function [output Greg] = dftregistration(buf1ft,buf2ft,usfac);
%
% Efficient subpixel image registration by crosscorrelation. This code
% gives the same precision as the FFT upsampled cross correlation in a
% small fraction of the computation time and with reduced memory
% requirements. It obtains an initial estimate of the crosscorrelation peak
% by an FFT and then refines the shift estimation by upsampling the DFT
% only in a small neighborhood of that estimate by means of a
% matrix-multiply DFT. With this procedure all the image points are used to
% compute the upsampled crosscorrelation.
% Manuel Guizar - Dec 13, 2007
%
% Portions of this code were taken from code written by Ann M. Kowalczyk
% and James R. Fienup.
% J.R. Fienup and A.M. Kowalczyk, "Phase retrieval for a complex-valued
% object by using a low-resolution image," J. Opt. Soc. Am. A 7, 450-458
% (1990).
%
% Citation for this algorithm:
% Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup,
% "Efficient subpixel image registration algorithms," Opt. Lett. 33,
% 156-158 (2008).
%
% Inputs
% buf1ft Fourier transform of reference image,
% DC in (1,1) [DO NOT FFTSHIFT]
% buf2ft Fourier transform of image to register,
% DC in (1,1) [DO NOT FFTSHIFT]
% usfac Upsampling factor (integer). Images will be registered to
% within 1/usfac of a pixel. For example usfac = 20 means the
% images will be registered within 1/20 of a pixel. (default = 1)
%
% Outputs
% output = [error,diffphase,net_row_shift,net_col_shift]
% error Translation invariant normalized RMS error between f and g
% diffphase Global phase difference between the two images (should be
% zero if images are non-negative).
% net_row_shift net_col_shift Pixel shifts between images
% Greg (Optional) Fourier transform of registered version of buf2ft,
% the global phase difference is compensated for.
%
function [output Greg] = dftregistration(buf1ft,buf2ft,usfac)
% Default usfac to 1
if exist('usfac')~=1, usfac=1; end
% Compute error for no pixel shift
if usfac == 0,
CCmax = sum(sum(buf1ft.*conj(buf2ft)));
rfzero = sum(abs(buf1ft(:)).^2);
rgzero = sum(abs(buf2ft(:)).^2);
error = 1.0 - CCmax.*conj(CCmax)/(rgzero*rfzero);
error = sqrt(abs(error));
diffphase=atan2(imag(CCmax),real(CCmax));
output=[error,diffphase];
% Whole-pixel shift - Compute crosscorrelation by an IFFT and locate the
% peak
elseif usfac == 1,
[m,n]=size(buf1ft);
CC = ifft2(buf1ft.*conj(buf2ft));
[max1,loc1] = max(CC);
[max2,loc2] = max(max1);
rloc=loc1(loc2);
cloc=loc2;
CCmax=CC(rloc,cloc);
rfzero = sum(abs(buf1ft(:)).^2)/(m*n);
rgzero = sum(abs(buf2ft(:)).^2)/(m*n);
error = 1.0 - CCmax.*conj(CCmax)/(rgzero(1,1)*rfzero(1,1));
error = sqrt(abs(error));
diffphase=atan2(imag(CCmax),real(CCmax));
md2 = fix(m/2);
nd2 = fix(n/2);
if rloc > md2
row_shift = rloc - m - 1;
else
row_shift = rloc - 1;
end
if cloc > nd2
col_shift = cloc - n - 1;
else
col_shift = cloc - 1;
end
output=[error,diffphase,row_shift,col_shift];
% Partial-pixel shift
else
% First upsample by a factor of 2 to obtain initial estimate
% Embed Fourier data in a 2x larger array
[m,n,o]=size(buf1ft);
mlarge=m*2;
nlarge=n*2;
CC=zeros(mlarge,nlarge,o);
CC(m+1-fix(m/2):m+1+fix((m-1)/2),n+1-fix(n/2):n+1+fix((n-1)/2),:) = ...
fftshift(buf1ft).*conj(fftshift(buf2ft));
% Compute crosscorrelation and locate the peak
CC = ifft2(ifftshift(CC)); % Calculate cross-correlation
CC = mean(CC,3);
[max1,loc1] = max(CC);
[max2,loc2] = max(max1);
rloc=loc1(loc2);cloc=loc2;
CCmax=CC(rloc,cloc);
% Obtain shift in original pixel grid from the position of the
% crosscorrelation peak
[m,n] = size(CC); md2 = fix(m/2); nd2 = fix(n/2);
if rloc > md2
row_shift = rloc - m - 1;
else
row_shift = rloc - 1;
end
if cloc > nd2
col_shift = cloc - n - 1;
else
col_shift = cloc - 1;
end
row_shift=row_shift/2;
col_shift=col_shift/2;
% If upsampling > 2, then refine estimate with matrix multiply DFT
if usfac > 2,
%%% DFT computation %%%
% Initial shift estimate in upsampled grid
row_shift = round(row_shift*usfac)/usfac;
col_shift = round(col_shift*usfac)/usfac;
dftshift = fix(ceil(usfac*1.5)/2); %% Center of output array at dftshift+1
% Matrix multiply DFT around the current shift estimate
CC = conj(dftups(buf2ft.*conj(buf1ft),ceil(usfac*1.5),ceil(usfac*1.5),usfac,...
dftshift-row_shift*usfac,dftshift-col_shift*usfac))/(md2*nd2*usfac^2);
% Locate maximum and map back to original pixel grid
CC = mean(CC,3);
[max1,loc1] = max(CC);
[max2,loc2] = max(max1);
rloc = loc1(loc2); cloc = loc2;
CCmax = CC(rloc,cloc);
rg00 = dftups(buf1ft.*conj(buf1ft),1,1,usfac)/(md2*nd2*usfac^2);
rf00 = dftups(buf2ft.*conj(buf2ft),1,1,usfac)/(md2*nd2*usfac^2);
rloc = rloc - dftshift - 1;
cloc = cloc - dftshift - 1;
row_shift = row_shift + rloc/usfac;
col_shift = col_shift + cloc/usfac;
% If upsampling = 2, no additional pixel shift refinement
else
rg00 = sum(sum( buf1ft.*conj(buf1ft) ))/m/n;
rf00 = sum(sum( buf2ft.*conj(buf2ft) ))/m/n;
end
rg00 = mean(rg00,3);
rf00 = mean(rf00,3);
error = 1.0 - CCmax.*conj(CCmax)/(rg00*rf00);
error = sqrt(abs(error));
diffphase=atan2(imag(CCmax),real(CCmax));
% If its only one row or column the shift along that dimension has no
% effect. We set to zero.
if md2 == 1,
row_shift = 0;
end
if nd2 == 1,
col_shift = 0;
end
output=[error,diffphase,row_shift,col_shift];
end
% Compute registered version of buf2ft
if (nargout > 1)&&(usfac > 0),
[nr,nc,nBands]=size(buf2ft);
Nr = ifftshift([-fix(nr/2):ceil(nr/2)-1]);
Nc = ifftshift([-fix(nc/2):ceil(nc/2)-1]);
[Nc,Nr] = meshgrid(Nc,Nr);
Greg = buf2ft.*repmat(exp(i*2*pi*(-row_shift*Nr/nr-col_shift*Nc/nc)),[1 1 nBands]);
Greg = Greg*exp(i*diffphase);
elseif (nargout > 1)&&(usfac == 0)
Greg = buf2ft*exp(i*diffphase);
end
return
function out=dftups(in,nor,noc,usfac,roff,coff)
% function out=dftups(in,nor,noc,usfac,roff,coff);
% Upsampled DFT by matrix multiplies, can compute an upsampled DFT in just
% a small region.
% usfac Upsampling factor (default usfac = 1)
% [nor,noc] Number of pixels in the output upsampled DFT, in
% units of upsampled pixels (default = size(in))
% roff, coff Row and column offsets, allow to shift the output array to
% a region of interest on the DFT (default = 0)
% Recieves DC in upper left corner, image center must be in (1,1)
% Manuel Guizar - Dec 13, 2007
% Modified from dftus, by J.R. Fienup 7/31/06
% This code is intended to provide the same result as if the following
% operations were performed
% - Embed the array "in" in an array that is usfac times larger in each
% dimension. ifftshift to bring the center of the image to (1,1).
% - Take the FFT of the larger array
% - Extract an [nor, noc] region of the result. Starting with the
% [roff+1 coff+1] element.
% It achieves this result by computing the DFT in the output array without
% the need to zeropad. Much faster and memory efficient than the
% zero-padded FFT approach if [nor noc] are much smaller than [nr*usfac nc*usfac]
[nr,nc,nBands]=size(in);
% Set defaults
if exist('roff')~=1, roff=0; end
if exist('coff')~=1, coff=0; end
if exist('usfac')~=1, usfac=1; end
if exist('noc')~=1, noc=nc; end
if exist('nor')~=1, nor=nr; end
% Compute kernels and obtain DFT by matrix products
kernc=exp((-i*2*pi/(nc*usfac))*( ifftshift([0:nc-1]).' - floor(nc/2) )*( [0:noc-1] - coff ));
kernr=exp((-i*2*pi/(nr*usfac))*( [0:nor-1].' - roff )*( ifftshift([0:nr-1]) - floor(nr/2) ));
out=zeros(nor,noc,nBands);
for (bandIdx=1:nBands),
out(:,:,bandIdx)=kernr*in(:,:,bandIdx)*kernc;
end
return
|
github
|
mc225/Softwares_Tom-master
|
tutorial_filters.m
|
.m
|
Softwares_Tom-master/ThirdPartyDependencies/plot2svg/tutorial_filters.m
| 5,536 |
utf_8
|
ef877466a3cde2e45877aa3976c3b92c
|
function tutorial_filters
file = 'matterhorn_small.jpg';
fig = figure;
set(fig, 'DefaultAxesFontName', 'Arial')
set(fig, 'DefaultAxesFontSize', 6)
plotCounter = 1;
xPlots = 3;
yPlots = 4;
% a) Original plot with a line, patch, and text object
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
title('a) Original')
% b) Adding a Gaussian blur filter for each object that uses the standard
% color channels for the blur operation. The bounding box is covering
% the axis region for each object. Note: there is no bounding box
% overlap specified. This would lead to some distortion at the border if
% a offset filter followed the blur filter.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'axes', 0, 'off')
svgGaussianBlur(h, 'SourceGraphic', 2, 'blur');
title('b) Blur on (S = SourceGraphic)')
% c) Identical to b) but the blur filter uses the alpha channel. This mode
% is very useful to create shadows.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'axes', 0, 'off')
svgGaussianBlur(h, 'SourceAlpha', 2, 'blur');
title('c) Blur (S = SourceAlpha)')
% d) Adding a image filter that covers the whole axis region. The filter
% replaces the object as no other combine filter is defined. The image
% is scaled to the bounding box. This leads to a distortion of the
% aspect ratio.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'axes', 0, 'on')
svgImage(h, file, 'none', 'pic');
title('d) Pict (BB = axes, none)')
% e) Identical to d) but with correct aspect ratio of the image. The
% setting 'xMidYMid slice' centers the image and scales x and y so that
% both cover the bonding box region defined by the axis region. The
% clipping of the axis object removes the overlap.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'axes', 0, 'on')
svgImage(h, file, 'xMidYMid slice', 'pic');
title('e) Pict (BB = axes, xMidYMid slice)')
% f) Identical to e) but with image scaling 'xMidYMid meet'. This setting
% also conserves the aspect ratio. However, the image may no more cover
% the whole bounding box.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'axes', 0, 'on')
svgImage(h, file, 'xMidYMid meet', 'pic');
title('f) Pict (BB = axes, xMidYMid meet)')
% h) Identical to f) but with bounding box defined by the object. The
% bounding box may be larger than the object extension due to line
% width and marker size.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'element', 0, 'on')
svgImage(h, file, 'xMidYMid meet', 'pic');
title('g) Pict (BB = element, xMidYMid meet)')
% g) Now we add a composite filter that combines the filter result from the
% image filter and the source graphic. The keyword 'atop' restricts the
% image filter to the object boundaries.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'axes', 0, 'on')
svgImage(h, file, 'xMidYMid slice', 'pic');
svgComposite(h, 'pic', 'SourceGraphic', 'atop', 'obj');
title('h) Pict (BB = axes, xMidYMid slice)')
% i) Identical to g) but with a filter bounding box defined by the object
% extension. The image scaling 'xMidYMid meet' is not well suited for
% this application. The image is not covering the whole object.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'element', 0, 'on')
svgImage(h, file, 'xMidYMid meet', 'pic');
svgComposite(h, 'pic', 'SourceGraphic', 'atop', 'obj');
title('i) Pict (BB = element, xMidYMid meet)')
% j) Identical to i) but with a better image scaling that conserves the
% spect ratio and makes sure that the whole bounding box is covered.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'element', 0, 'on')
svgImage(h, file, 'xMidYMid slice', 'pic');
svgComposite(h, 'pic', 'SourceGraphic', 'atop', 'obj');
title('j) Pict (BB = element, xMidYMid slice)')
% k) Identical to j) but with a bounding box overlap of 5 pixel. This is
% important to avoid distortions at the border.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'element', 5, 'on')
svgImage(h, file, 'xMidYMid slice', 'pic');
svgComposite(h, 'pic', 'SourceGraphic', 'atop', 'obj');
title('k) Pict (BB = element, xMidYMid slice)')
% l) Identical to k) but the composition is based on the image filter and a
% blur filter. In addition, the image filter covers the whole axis
% region.
subplot(yPlots, xPlots, plotCounter)
plotCounter = plotCounter + 1;
h = create_plot;
svgBoundingBox(h, 'axes', 0, 'on')
svgImage(h, file, 'xMidYMid slice', 'pic');
svgGaussianBlur(h, 'SourceAlpha', 2, 'blur');
svgComposite(h, 'pic', 'blur', 'atop', 'obj');
title('l) Blur + Pict (BB = axes, xMidYMid slice)')
% Save the result
plot2svg('tutorial_filters.svg')
function handles = create_plot
% Helper function to plot the objects
hold on
s1 = text(3, 1, 'plot2svg', 'FontName', 'Arial', 'FontSize', 16, ...
'Color', 'red', 'FontWeight', 'bold', 'Margin', 0.01, 'Clipping', 'on');
s2 = plot([6 8], [3 6], 'b', 'LineWidth', 20);
s3 = patch([1 2 3 4 3 2 1], [1 3 2 3 4 5 3],'black');
handles = [s1 s2 s3];
box on
grid on
axis([0 10 0 6])
|
github
|
mc225/Softwares_Tom-master
|
recordImagePerWavelength.m
|
.m
|
Softwares_Tom-master/PrincipalComponentAnalysis/recordImagePerWavelength.m
| 3,539 |
utf_8
|
08c86de060c5e8d386822d22b45d3920
|
% recordImagePerWavelength(sampledWavelengths,outputFolder,nbImagesPerWavelength)
%
% Function to record a series of speckle images for various sampledWavelengths
%
% sampledWavelengths: the range of sampledWavelengths (in meters)
% outputFolder: a string indicating where the data is to be saved. Default:
% measurement followed by the data and time.
% nbImagesPerWavelength: the number of images to record per wavelength,
% default: 100
%
function recordImagePerWavelength(sampledWavelengths,outputFolder,nbImagesPerWavelength)
if (nargin<1 || isempty(sampledWavelengths))
% sampledWavelengths=[695:.2:705 706:720]*1e-9;
sampledWavelengths=[745:805]*1e-9;
sampledWavelengths=unique(round(sampledWavelengths*1e15)*1e-15); %Remove doubles (upto fm)
end
if (nargin<2 || isempty(outputFolder))
outputFolder=strcat('D:\SpeckleWaveMeter\BroadBand\Alumina\measurement_',datestr(now(),'YYYY-mm-dd_HH_MM_ss'));
end
if (nargin<3 || isempty(nbImagesPerWavelength))
nbImagesPerWavelength=100;
end
logMessage('Measuring for %d wavelengths.',length(sampledWavelengths));
cam=PikeCam();
cam.regionOfInterest=[0 0 480 320];
cam.integrationTime=25e-3; % initial integration time only
cam.gain=100;
mkdir(outputFolder);
images=[];
for wavelengthIdx=1:length(sampledWavelengths),
wavelength=sampledWavelengths(wavelengthIdx);
logMessage('Set laser wavelength to %0.6f nm and hit enter.',wavelength*1e9);
input('');
logMessage('ACQUIRING! DON''T MOVE!');
images=acquireWithoutSaturating(cam,nbImagesPerWavelength);
images=single(images);
logMessage('Peak intensity %f, interframe error %f, rel. interframe error %f',[max(images(:)) mean(mean(std(images,0,3))) mean(mean(std(images,0,3)))/mean(images(:))]);
% Save output
outputFileName=strcat(outputFolder,sprintf('/imagesForWavelength%0.6fnm.mat',wavelength*1e9));
recordingTime=datestr(clock(),'dd-mmm-yyyy HH:MM:SS.FFF');
camGain=cam.gain;
camIntegrationTime=cam.integrationTime;
camRegionOfInterest=cam.regionOfInterest;
save(outputFileName,'sampledWavelengths','images','recordingTime','camGain','camIntegrationTime','camRegionOfInterest');
logMessage('---------------------- %0.1f%% done ------------------------',100*wavelengthIdx/length(sampledWavelengths));
end
end
function img=acquireWithoutSaturating(cam,nbImagesPerWavelength)
if (nargin<2 || isempty(nbImagesPerWavelength))
nbImagesPerWavelength=1;
end
shortestIntegrationTime=0.01e-3;
longestIntegrationTime=2000e-3;
cam.background=0;
img=cam.acquire();
while ((max(img(:))>=1 && cam.integrationTime>shortestIntegrationTime*2) || (max(img(:))<.5 && cam.integrationTime<longestIntegrationTime/2))
if (max(img(:))>=1)
cam.integrationTime=cam.integrationTime/2;
else
cam.integrationTime=cam.integrationTime*2;
end
% logMessage('Integration time %f ms',cam.integrationTime*1e3);
img=cam.acquire();
end
if (max(img(:))>=1)
logMessage('Too bright!!!');
end
if (max(img(:))<=.5)
logMessage('Too dark!!!');
end
if (nbImagesPerWavelength>1)
img(:,:,nbImagesPerWavelength)=0;
end
for (imgIdx=2:nbImagesPerWavelength)
img(:,:,imgIdx)=cam.acquire();
end
img=img/cam.integrationTime;
end
|
github
|
mc225/Softwares_Tom-master
|
scanVoltages.m
|
.m
|
Softwares_Tom-master/PrincipalComponentAnalysis/scanVoltages.m
| 5,341 |
utf_8
|
b90ef136aeea13d562314a19ada693d8
|
% scanVoltages(voltages,outputFolder,nbImagesPerWavelength,laserStabilizationTime)
%
% Function to record a series of speckle images for various wavelengths
% automatically.
%
% voltages: the range of voltages to drive the Sacher laser
% outputFolder: a string indicating where the data is to be saved. Default:
% D:\SpeckleWaveMeter\NarrowBand\FabryPerot\withoutDiffuserAnd2F\measurement followed by the data and time.
% nbImagesPerWavelength: the number of images to record per wavelength,
% default: 50
% laserStabilizationTime: the number of seconds to wait after changing the wavelength
%
function scanVoltages(voltages,outputFolder,nbImagesPerWavelength,laserStabilizationTime)
if (nargin<1 || isempty(voltages))
%voltages=[-5:0.5:-1 -0.9:0.1:0.9 1:.5:5];
voltages=[-5:0.1:5];
end
if (nargin<2 || isempty(outputFolder))
outputFolder=strcat('D:\SpeckleWaveMeter\NarrowBand\FabryPerot\withoutDiffuserAnd2F\measurement_',datestr(now(),'YYYY-mm-dd_HH_MM_ss'));
end
if (nargin<3 || isempty(nbImagesPerWavelength))
nbImagesPerWavelength=100;
end
if (nargin<4 || isempty(laserStabilizationTime))
laserStabilizationTime=60; % in seconds
end
emailToInformOfProgress='[email protected]';
calibrationVoltages=[-5:5];
calibrationWavelengths=(785+[.067 .096 .139 .186 .239 .296 .357 .414 .473 .535 .596])*1e-9;
voltageWavelengthModel=fit(calibrationVoltages.',calibrationWavelengths.','smoothingspline');
sampledWavelengths=voltageWavelengthModel(voltages);
cam=PikeCam();
cam.regionOfInterest=[0 0 480 320];
cam.integrationTime=4000e-3; % initial integration time only
cam.gain=630;
startTime=clock();
for idx=1:4,
img=cam.acquire();
end
acquisitionTime=etime(clock(),startTime)/4;
logMessage('Measuring %d images at %d wavelengths. This experiment will take approximately %.1f hours',[nbImagesPerWavelength length(sampledWavelengths),length(sampledWavelengths)*(laserStabilizationTime+nbImagesPerWavelength*acquisitionTime)/60/60]);
DAQSession = daq.createSession('ni');
DAQSession.addAnalogOutputChannel('Dev2',0,'Voltage');
mkdir(outputFolder);
logMessage('Setting the initial wavelength...');
% Move to beginning of range in one second
for (fraction=[0:.01:1])
DAQSession.outputSingleScan(voltages(1)*fraction);
pause(.01);
end
%Wait for user to start the experiment
minutesToWait=input('Enter minutes to wait for before starting the experiment (default 0):');
try
if (isempty(minutesToWait))
minutesToWait=0;
else
minutesToWait=minutesToWait(1);
end
if (minutesToWait>0)
logMessage('Waiting for %0.1f minutes.',minutesToWait);
pause(60*minutesToWait);
end
logMessage('Starting now...');
% Scan all wavelengths
images=[];
for wavelengthIdx=1:length(sampledWavelengths),
wavelength=sampledWavelengths(wavelengthIdx);
logMessage('Setting the laser wavelength to %0.6f nm and waiting %0.1f seconds...',[wavelength*1e9 laserStabilizationTime]);
DAQSession.outputSingleScan(voltages(wavelengthIdx));
pause(laserStabilizationTime);
logMessage('Recording...');
for (imageIdx=1:nbImagesPerWavelength)
img=cam.acquire();
if (isempty(images))
images=zeros([size(img,1) size(img,2) nbImagesPerWavelength],'single');
end
images(:,:,imageIdx)=single(img);
end
logMessage('Peak intensity %f, interframe error %f, rel. interframe error %f',[max(images(:)) mean(mean(std(images,0,3))) mean(mean(std(images,0,3)))/mean(images(:))]);
outputFileName=strcat(outputFolder,sprintf('/imagesForWavelength%0.6fnm.mat',wavelength*1e9));
recordingTime=datestr(clock(),'dd-mmm-yyyy HH:MM:SS.FFF');
camGain=cam.gain;
camIntegrationTime=cam.integrationTime;
camRegionOfInterest=cam.regionOfInterest;
save(outputFileName,'sampledWavelengths','images','recordingTime','camGain','camIntegrationTime','camRegionOfInterest','voltages');
logMessage('---------------------- %0.1f%% done ------------------------',100*wavelengthIdx/length(sampledWavelengths));
if (mod(wavelengthIdx,10)==1)
progressMessage=sprintf('%0.1f%% done ---------------------------------',100*wavelengthIdx/length(sampledWavelengths));
logMessage([progressMessage,'\n and written to file: %s'],outputFileName,'[email protected]');
end
end
logMessage('Returning to central wavelength...');
% Move back to center in one second
for (fraction=[1:-.01:0])
DAQSession.outputSingleScan(voltages(end)*fraction);
pause(.01);
end
delete(DAQSession);
logMessage(['Sacher measurement - all done and written to folder ' strrep(outputFolder,'\','/')],[],emailToInformOfProgress);
catch Exc
logMessage('Sacher measurement - error: %s',Exc.message,emailToInformOfProgress);
rethrow(Exc);
end
end
|
github
|
mc225/Softwares_Tom-master
|
determineWavelengthFromSpeckleImage.m
|
.m
|
Softwares_Tom-master/PrincipalComponentAnalysis/determineWavelengthFromSpeckleImage.m
| 2,776 |
utf_8
|
f28b7e4b3758bfb5f0e441b836206000
|
% [wavelength testImagesInPrincipleComponentSpace] = determineWavelengthFromSpeckleImage(img,calibration)
%
% Determines the wavelength corresponding to a speckle image given the
% calibration data.
%
% Inputs:
% img: a 2D image, or a 3D stack of speckle testImages
% calibration: a struct with calibration data
%
% Outputs:
% wavelength: the wavelength corresponding to the speckle image, or a
% vector with values for each image in a stack.
% testImagesInPrincipleComponentSpace: matrix with in the columns the
% coordinates of the testImages in principal component basis
%
%
function [wavelengths testImagesInPrincipleComponentSpace] = determineWavelengthFromSpeckleImage(testImages,calibration)
testInputSize=size(testImages);
if (length(testInputSize)<3)
testInputSize(3)=1;
end
nbTrainingSamplesPerWavelength=numel(calibration.trainingWavelengths)/prod(testInputSize(4:end));
% Preprocess
testImages=testImages./repmat(sqrt(sum(sum(testImages.^2))),[testInputSize(1:2) 1]);
testImages=testImages-repmat(calibration.meanNormalizedImage,[1 1 testInputSize(3:end)]);
% Vectorize the testImages
testImages=reshape(testImages,[prod(testInputSize(1:2)) prod(testInputSize(3:end))]);
% Classify the input
testImagesInPrincipleComponentSpace=calibration.principalComponentsInImageSpace*testImages;
%Nearest neighbor
wavelengths=[];
for (imgIdx=1:prod(testInputSize(3:end)))
ind=dsearchn(calibration.trainingImagesInPrincipalComponentSpace',testImagesInPrincipleComponentSpace(:,imgIdx)');
wavelengths(end+1)=calibration.trainingWavelengths(ind);
detectedWavelengthIdx=1+floor((ind-1)/nbTrainingSamplesPerWavelength);
end
% %Linear
% wavelengths = classify(testImagesInPrincipleComponentSpace',calibration.trainingImagesInPrincipalComponentSpace',calibration.trainingWavelengths,'linear');
% %Mahalanobis
% wavelengths = classify(testImagesInPrincipleComponentSpace',calibration.trainingImagesInPrincipalComponentSpace',calibration.trainingWavelengths,'mahalanobis');
% %Support Vector Machine
% wavelengthIndexes = multisvm(calibration.trainingImagesInPrincipalComponentSpace',calibration.trainingWavelengths(:),testImagesInPrincipleComponentSpace');
% wavelengths=calibration.trainingWavelengths(wavelengthIndexes);
% Shape back to input dimensions
if (length(testInputSize)>3)
wavelengths=reshape(wavelengths,testInputSize(3:end));
end
nbPrincipalComponents=size(calibration.principalComponentsInImageSpace,1);
testImagesInPrincipleComponentSpace=reshape(testImagesInPrincipleComponentSpace,[nbPrincipalComponents testInputSize(3:end)]);
end
|
github
|
mc225/Softwares_Tom-master
|
analyzeSpeckleImages.m
|
.m
|
Softwares_Tom-master/PrincipalComponentAnalysis/analyzeSpeckleImages.m
| 7,432 |
utf_8
|
b7afb1ec12c2e26235734dcf7fd22e27
|
% analyzeSpeckleImages(inputFolderName,outputFileName)
%
% inputFolderName: a string representing the input folder created by analyzeSpeckleImages.m
% outputFileName: the filename of the output .mat file.#
% Default: the same as the input folder.
%
function analyzeSpeckleImages(inputFolderName,outputFileName)
close all;
if (nargin<1 || isempty(inputFolderName))
% inputFolderName='measurement_2013-01-16_12_10_55_alumina1_50pm';
% inputFolderName='measurement2013-01-15_13_20_53_alumina1_10pm';
% inputFolderName='measurement_2013-01-16_12_40_07_beamprofile_50pm';
% inputFolderName='D:\alumina2\measurement_2013-01-17_17_21_20_longAndRedone';
% inputFolderName='D:\alumina2\measurement_2013-01-17_21_02_12_785.3032nm_repeated';
% inputFolderName='D:\SpeckleWaveMeter\NarrowBand\FabryPerot\withoutDiffuserAnd2F\measurement_2013-01-27_12_53_23_2Fsetup';
% inputFolderName='D:\SpeckleWaveMeter\BroadBand\Alumina\measurement_2013-01-27_21_28_41_gain0_100pm_695nm_705nm';
inputFolderName='D:\SpeckleWaveMeter\BroadBand\FabryPerot\measurement_2013-01-27_18_47_13_gain0_100pm_695nm_700nm_and_1000pm_700nm_720nm';
end
if (nargin<2 || isempty(outputFileName))
outputFileName=strcat(inputFolderName,'.mat');
end
%
% Read measurement data from disk
%
% Detect which measurements have been done
files=dir(strcat(inputFolderName,'/imagesForWavelength*nm.mat'));
fileNames={files.name}; clear files;
wavelengths=regexp(fileNames,'imagesForWavelength([\d]+(\.[\d]*)?)nm.mat','tokens','once');
wavelengths=cellfun(@(c) str2double(c)*1e-9,wavelengths);
% Use all wavelengths
wavelengthSelection=logical(ones(size(wavelengths)));
% Handle only selected wavelengths
%wavelengthSelection=wavelengths<=785.170e-9 & wavelengths>=785.160e-9;
% wavelengthSelection=mod(wavelengths,5e-12)==0 | abs(wavelengths-785.174e-9)<1e-15;
% Some configuration
nbOfTrainingImages=50;
nbOfTestImages=10;
calibration={};
calibration.regionOfInterest=[100 0 300 300];
maxNumberOfPrincipalComponents=9;
signalToNoise=10.0;
% Read all files and pick out a smaller section
allImages=single([]);
testWavelengths=[];
for (fileIdx=find(wavelengthSelection))
currentFileName=strcat(inputFolderName,'/',fileNames{fileIdx})
load(currentFileName,'images');
images=images(calibration.regionOfInterest(1)+[1:calibration.regionOfInterest(3)],calibration.regionOfInterest(2)+[1:calibration.regionOfInterest(4)],1:(nbOfTrainingImages+nbOfTestImages));
newTrainingWavelengths=ones(1,nbOfTrainingImages)*wavelengths(fileIdx);
newTestWavelengths=ones(1,nbOfTestImages)*wavelengths(fileIdx);
% images=mean(images,3); % Average to safe memory
if (~isempty(allImages))
allImages(:,:,:,end+1)=images;
calibration.trainingWavelengths(end+[1:nbOfTrainingImages])=newTrainingWavelengths;
testWavelengths(end+[1:nbOfTestImages])=newTestWavelengths;
else
allImages=images;
calibration.trainingWavelengths=newTrainingWavelengths;
testWavelengths=newTestWavelengths;
end
end
wavelengths=wavelengths(wavelengthSelection);
% % Show the intensity spot for the 2F system FP
% figure;
% plot(wavelengths*1e9,1000*squeeze(mean(mean(allImages(125:165,200:232,1,:)))).'); xlim(wavelengths([1 end])*1e9);
%
% Pre-process the data and split it in a training and a test data set
%
%Split data set in training and test set
trainingImages=allImages(:,:,1:nbOfTrainingImages,:);
testImages=allImages(:,:,nbOfTrainingImages+[1:nbOfTestImages],:);
clear allImages;
testInputSize=size(testImages);
trainingInputSize=size(trainingImages);
%Normalize the training images to L2 norm 1 and subtract the mean
trainingImages=trainingImages./repmat(sqrt(sum(sum(trainingImages.^2))),[trainingInputSize(1:2) 1 1]);
calibration.meanNormalizedImage=mean(trainingImages(:,:,:),3);
trainingImages=trainingImages-repmat(calibration.meanNormalizedImage,[1 1 trainingInputSize(3:end)]);
logMessage('Using %d images for training and %d for testing.',[trainingInputSize(3) testInputSize(3)]);
% Vectorize the images, so each images is a column in a 2D matrix
vectorizedImages=reshape(trainingImages,[prod(trainingInputSize(1:2)) prod(trainingInputSize(3:end))]).';
clear trainingImages;
%
% Calculate the principal components
%
[eigenVectors,eigenValues]=eig(vectorizedImages*vectorizedImages');
%Determine how many principal components we want to use
energyPerEigenValue=cumsum(eigenValues(end:-1:1));
energyPerEigenValue=energyPerEigenValue/energyPerEigenValue(end);
numberOfComponentsToUse=min(maxNumberOfPrincipalComponents,find(energyPerEigenValue>(1-1/signalToNoise),1,'first'));
% Show the principle components in 'image' space
numberOfProbesToShow=9;
imagesInNormalizedPCBasis=diag(1./sqrt(diag(eigenValues)))*eigenVectors'*vectorizedImages;
figure();
for (probeIdx=1:numberOfProbesToShow)
subplot(floor(sqrt(numberOfProbesToShow)),ceil(numberOfProbesToShow/floor(sqrt(numberOfProbesToShow))),probeIdx);
imagesc(reshape(imagesInNormalizedPCBasis(end+1-probeIdx,:),trainingInputSize(1:2)));
drawnow();
end
% Calculate the principal components and project the calibration images onto it
calibration.principalComponentsInImageSpace=eigenVectors'*vectorizedImages;
calibration.principalComponentsInImageSpace=calibration.principalComponentsInImageSpace(end-numberOfComponentsToUse+1:end,:);
calibration.trainingImagesInPrincipalComponentSpace=calibration.principalComponentsInImageSpace*vectorizedImages';
%
% Save the principal components and other relevant data
%
logMessage('Saving processed data to file %s.',outputFileName);
save(outputFileName,'-struct','calibration');
%
% Test
%
relativeEigenValues=diag(eigenValues)/sum(diag(eigenValues));
variabilityConsidered=sum(relativeEigenValues(end-numberOfComponentsToUse+1:end))
%% Check if we have test inputs
if (nbOfTestImages>0)
[detectedWavelengths testImagesInPrincipleComponentSpace] = determineWavelengthFromSpeckleImage(testImages,calibration);
%
% Output results
%
figure();
deltaLambda=diff(wavelengths(1:2));
wavelengthIndexMismatch=(detectedWavelengths(:).'-testWavelengths)/deltaLambda;
detectionEfficiency=sum(wavelengthIndexMismatch<1)/length(wavelengthIndexMismatch)
hist(wavelengthIndexMismatch(:),50)
figure();
subplot(221);scatter(testImagesInPrincipleComponentSpace(end,:),testImagesInPrincipleComponentSpace(end-1,:),'+'); title('1-2');
subplot(222);scatter(testImagesInPrincipleComponentSpace(end,:),testImagesInPrincipleComponentSpace(end-2,:),'+'); title('1-3');
subplot(223);scatter(testImagesInPrincipleComponentSpace(end-1,:),testImagesInPrincipleComponentSpace(end-2,:),'+'); title('2-3');
subplot(224);scatter3(testImagesInPrincipleComponentSpace(end,:),testImagesInPrincipleComponentSpace(end-1,:),testImagesInPrincipleComponentSpace(end-2,:),'+'); title('1-2-3');
end
%%
end
|
github
|
mc225/Softwares_Tom-master
|
testDisorderSpectrometer.m
|
.m
|
Softwares_Tom-master/SpeckleSpectrometer/testDisorderSpectrometer.m
| 2,786 |
utf_8
|
dc177aec1ad2fe01958edbcf500e1f78
|
%
%
function testDisorderSpectrometer(transferMatrix,wavelengths,cam,slm,source)
if (nargin<1)
logMessage('Please specify the transferMatrix!');
return;
end
if (nargin<2 || isempty(wavelengths))
nbWavelengths=[size(transferMatrix,3) size(transferMatrix,4)];
wavelengths=[500+[1:prod(nbWavelengths)]]*1e-9;
wavelengths=reshape(wavelengths,nbWavelengths);
end
if (nargin<3 || isempty(slm))
slm=PhaseSLM(1); %Use the whole of display 1
slm.referenceDeflectionFrequency=[1/10 1/10];
end
if (nargin<4 || isempty(cam))
cam=BaslerGigECam();
cam.integrationTime=5e-3;
cam.gain=1;
end
if (nargin<5 || isempty(source))
% Initialize the SuperK
source=SuperK();
source.targetPower=0.50; % Half power
end
% Adjust the grating so that the first order diffraction always goes
% through the same spot in the iris, independently of the wavelength
baseWavelength=500e-9;
baseDeflectionFrequency=slm.referenceDeflectionFrequency*baseWavelength;
baseTwoPiEquivalent=slm.twoPiEquivalent/baseWavelength;
% Calculate the final mask
nbWavelengths=size(wavelengths);
amplificationLimit=3;
spectrometerSuperpositionMask=zeros(slm.regionOfInterest(3:4));
for (wavelengthIdx=1:prod(nbWavelengths))
pupilFunctionCorrection=calcCorrectionFromPupilFunction(transferMatrix(:,:,wavelengthIdx),amplificationLimit);
spectrometerSuperpositionMask=spectrometerSuperpositionMask+pupilFunctionCorrection;
end
% Load the mask permanently onto the SLM
slm.correctionFunction=spectrometerSuperpositionMask;
% Display
fig=figure;
try
wavelengthIdx=1;
while(ishandle(fig))
wavelength=wavelengths(wavelengthIdx);
%Adjust the SLM for the new wavelength
slm.referenceDeflectionFrequency=baseDeflectionFrequency/wavelength; % Keep tilt the same on the sample
slm.twoPiEquivalent=baseTwoPiEquivalent*wavelength; % Keep efficiency identical
% slm.correctionFunction=calcCorrectionFromPupilFunction(transferMatrix(:,:,wavelengthIdx),amplificationLimit);
slm.modulate(1); % Update the SLM with the new grating
% Set the source wavelength now
source.setWavelengths(wavelength);
img=cam.acquire();
if (ishandle(fig))
figure(fig);
showImage(img);
title(sprintf('Wavelength: %0.1f nm',wavelength*1e9));
drawnow();
pause(.05);
wavelengthIdx=1+mod(wavelengthIdx,numel(wavelengths));
end
end
catch Exc
logMessage(Exc);
end
end
|
github
|
mc225/Softwares_Tom-master
|
calibrateDisorderSpectrometer.m
|
.m
|
Softwares_Tom-master/SpeckleSpectrometer/calibrateDisorderSpectrometer.m
| 5,646 |
utf_8
|
1251a14260a2d949e0a73769113d7f78
|
% calibrateSpectrometer(wavelengths,slm,cam,outputFileName)
%
%
function calibrateDisorderSpectrometer(wavelengths,slm,cam,source,outputFileName,emailsToNotify)
if (nargin<1 || isempty(wavelengths))
wavelengths=[550 650 600]*1e-9;
% Put them in a rectangle
factors=factor(numel(wavelengths));
gridSize(1)=prod(factors([1:floor(end/4) (floor(3*end/4)+1):end]));
gridSize(2)=numel(wavelengths)/gridSize(1);
wavelengths=reshape(wavelengths,gridSize).';
logMessage('Creating a grid of %dx%d for %d wavelengths.',[gridSize numel(wavelengths)]);
end
if (nargin<2 || isempty(slm))
slm=PhaseSLM(1); %Use the whole of display 1
slm.referenceDeflectionFrequency=[1/10 1/10];
end
if (nargin<3 || isempty(cam))
cam=BaslerGigECam();
cam.integrationTime=3e-3;
cam.gain=1;
end
if (nargin<4 || isempty(source))
% Initialize the SuperK
source=SuperK();
source.targetPower=0.50; % Half power
end
if (nargin<5 || isempty(outputFileName))
outputFileName=[pwd(),'/spectrometerCalibration_',datestr(now(),'YYYY-mm-DD_HH-MM'),'.mat'];
end
progressEmailAddresses={'[email protected]','[email protected]'};
if (nargin<6 || isempty(emailsToNotify))
emailsToNotify=progressEmailAddresses;
end
nbWavelengths=size(wavelengths);
baseWavelength=500e-9;
probeGridSize=[25 25 3];
function cont=progressFunctor(fractionDone)
cont=true;
if (floor(fractionDone*100)>floor(prevFractionDone*100))
logMessage('%0.0f%% done.',100*fractionDone);
prevFractionDone=fractionDone;
end
end
baseDeflectionFrequency=slm.referenceDeflectionFrequency*baseWavelength;
baseTwoPiEquivalent=slm.twoPiEquivalent/baseWavelength;
initialCorrection=slm.correctionFunction;
gridSpacing=[1 1]*min(cam.regionOfInterest(3)/nbWavelengths(1),cam.regionOfInterest(4)/nbWavelengths(2));
[targetPosY targetPosX]=ndgrid(round(cam.regionOfInterest(3)/2+([1:nbWavelengths(1)]-nbWavelengths(1)/2-1/2)*gridSpacing(1)),round(cam.regionOfInterest(4)/2+([1:nbWavelengths(2)]-nbWavelengths(2)/2-1/2)*gridSpacing(2)));
minutesToWait=input('Enter the number of minutes to wait before starting the experiment: ');
if (~isempty(minutesToWait))
logMessage('Waiting for %0.0f minutes to start experiment.',minutesToWait,emailsToNotify);
originalSetPower=source.targetPower;
pause(minutesToWait*60);
logMessage('Starting measurement...');
source.targetPower=originalSetPower;
else
logMessage('Starting measurement immediately...');
end
source.targetPower=0.50; % Half power
transferMatrix=zeros([slm.regionOfInterest(3:4) nbWavelengths]);
for (wavelengthIdx=1:prod(nbWavelengths))
wavelength=wavelengths(wavelengthIdx);
targetPos=[targetPosY(wavelengthIdx) targetPosX(wavelengthIdx)];
%Adjust the SLM for the new wavelength
slm.referenceDeflectionFrequency=baseDeflectionFrequency/wavelength; % Keep tilt the same on the sample
slm.twoPiEquivalent=baseTwoPiEquivalent*wavelength; % Keep efficiency identical
logMessage('Setting the wavelength to %0.3f nm',wavelength*1e9);
source.setWavelengths(wavelength,0.5); % half the modulation amplitude
prevFractionDone=0;
[measuredPupilFunction eigenVector probeField4DMatrix sampleX sampleY]=aberrationMeasurement(slm,probeGridSize,@() probeFunctor(cam,targetPos),@progressFunctor);
transferMatrix(:,:,wavelengthIdx)=measuredPupilFunction./initialCorrection;
save(outputFileName,'wavelengths','transferMatrix');
logMessage('Probing for wavelength %0.0fnm done.',wavelength*1e9,progressEmailAddresses);
logMessage('Partial output written to %s.',outputFileName);
end
% Calculate the final mask
amplificationLimit=1;
spectrometerSuperpositionMask=zeros(slm.regionOfInterest(3:4));
for (wavelengthIdx=1:prod(nbWavelengths))
pupilFunctionCorrection=calcCorrectionFromPupilFunction(transferMatrix(:,:,wavelengthIdx).*conj(initialCorrection),amplificationLimit);
spectrometerSuperpositionMask=spectrometerSuperpositionMask+pupilFunctionCorrection;
end
spectrometerSuperpositionMask=spectrometerSuperpositionMask./max(abs(spectrometerSuperpositionMask(:)));
% Save the results
pupilFunctionCorrection=spectrometerSuperpositionMask;
initialCorrection=slm.correctionFunction;
referenceDeflectionFrequency=slm.referenceDeflectionFrequency;
slmRegionOfInterest=slm.regionOfInterest;
twoPiEquivalent=slm.twoPiEquivalent;
save(outputFileName,'wavelengths','transferMatrix','pupilFunctionCorrection','referenceDeflectionFrequency','slmRegionOfInterest','twoPiEquivalent','initialCorrection','gridSpacing','targetPosX','targetPosY');
logMessage('Experiment done, output written to %s.',outputFileName,emailsToNotify); %,outputFileName);
% logMessage('Done, displaying results now... (Close figure window to exit)');
% testDisorderSpectrometer(transferMatrix,wavelengths,cam,slm,source);
source.delete(); % Shut down
end
function [value auxValues]=probeFunctor(cam,centerPos)
probeSize=[3 3];
img=cam.acquire();
vals=img(centerPos(1)-cam.regionOfInterest(1)+[-floor(probeSize(1)/2):floor((probeSize(1)-1)/2)],centerPos(2)-cam.regionOfInterest(2)+[-floor(probeSize(1)/2):floor((probeSize(1)-1)/2)]);
value=mean(vals(:));
auxValues=[];
end
|
github
|
mc225/Softwares_Tom-master
|
recordScannedWavelength.m
|
.m
|
Softwares_Tom-master/SpeckleSpectrometer/recordScannedWavelength.m
| 5,350 |
utf_8
|
a2019dd9e1e9d8b21f48c320b5657800
|
function recordScannedWavelength(wavelengths,slm,cam,source,outputFileName)
if (nargin<1 || isempty(wavelengths))
wavelengths=[500:1:700]*1e-9;
end
if (nargin<2 || isempty(slm))
slm=PhaseSLM(1); %Use the whole of display 1
slm.referenceDeflectionFrequency=[1/10 1/10];
end
if (nargin<3 || isempty(cam))
cam=BaslerGigECam();
cam.integrationTime=50e-3;
cam.gain=50;
cam.numberOfFramesToAverage=4;
% cam.acquireBackground();
end
if (nargin<4 || isempty(source))
% Initialize the SuperK
source=SuperK();
source.targetPower=1.0;
end
if (nargin<5 || isempty(outputFileName))
outputFileName='scan500to700nmGaPGeEdgeScratch';
end
emailsToNotify={'[email protected]','[email protected]'};
slmMask=@(X,Y) sqrt(X.^2+Y.^2)<200;
% IC=load('C:\Users\nkt\Documents\MATLAB\intensityCorrectionOrig.mat');
% source.setIntensityCorrection(IC.wavelengths,IC.intensityCorrection);
if (nargin==0)
waitForUserSpecifiedTime();
end
nbWavelengths=numel(wavelengths);
% Adjust the grating so that the first order diffraction always goes
% through the same spot in the iris, independently of the wavelength
baseWavelength=500e-9;
baseDeflectionFrequency=slm.referenceDeflectionFrequency*baseWavelength;
baseTwoPiEquivalent=slm.twoPiEquivalent/baseWavelength;
% Open the video output file
recordingObj = VideoWriter([outputFileName,'.avi'],'Uncompressed AVI'); %'Motion JPEG AVI'); %'Uncompressed AVI');
recordingObj.FrameRate=25;
open(recordingObj);
detectorNoise=[];
differencesWithInitial=zeros(1,nbWavelengths);
differencesWithPrevious=zeros(1,nbWavelengths);
measuredIntensities=zeros(1,nbWavelengths);
images=zeros([cam.regionOfInterest(3:4) nbWavelengths],'single');
for (wavelengthIdx=1:nbWavelengths)
wavelength=wavelengths(wavelengthIdx);
logMessage('Doing wavelength %0.1f.',wavelength*1e9);
%Adjust the SLM for the new wavelength
slm.referenceDeflectionFrequency=baseDeflectionFrequency/wavelength; % Keep tilt the same on the sample
slm.twoPiEquivalent=baseTwoPiEquivalent*wavelength; % Keep efficiency identical
slm.modulate(slmMask);
% Set the source to the new wavelength
source.setWavelengths(wavelength);
img=cam.acquire();
writeVideo(recordingObj,max(0,img./max(img(:))));
images(:,:,wavelengthIdx)=img;
measuredIntensities(wavelengthIdx)=mean(img(:));
if (~isempty(detectorNoise))
differenceImageWithInitial=img./norm(img(:))-initialImage./norm(initialImage(:));
differencesWithInitial(wavelengthIdx)=norm(differenceImageWithInitial(:));
differenceImageWithPrevious=img./norm(img(:))-previousImage./norm(previousImage(:));
differencesWithPrevious(wavelengthIdx)=norm(differenceImageWithPrevious(:));
else
initialImage=img;
nbNoiseImages=100;
logMessage('Recording %d images to measure detection noise.',nbNoiseImages);
noiseImages=initialImage;
noiseImages(:,:,nbNoiseImages)=0;
for imgIdx=2:nbNoiseImages,
noiseImages(:,:,imgIdx)=cam.acquire();
end
detectorNoise=mean(mean(std(noiseImages,0,3)));
clear noiseImages;
end
previousImage=img;
end
amplificationLimit=10;
measuredIntensitiesWithoutCorrection=measuredIntensities./source.intensityCorrection(wavelengths);
maxIntensity=max(abs(measuredIntensitiesWithoutCorrection(:)));
intensityCorrection=1./max(1,amplificationLimit*measuredIntensitiesWithoutCorrection./maxIntensity);
save([outputFileName,'.mat'],'images','wavelengths','measuredIntensities','measuredIntensitiesWithoutCorrection','intensityCorrection','differencesWithInitial','differencesWithPrevious','detectorNoise');
close(recordingObj);
logMessage('Wavelength range recording done.',[],emailsToNotify);
% Normalize for power fluctuations
intensityNorms=squeeze(sqrt(sum(sum(abs(images).^2))));
images=images./repmat(permute(intensityNorms,[3 2 1]),[size(images,1) size(images,2) 1]);
meanImage=mean(images,3);
images=images-repmat(meanImage,[1 1 size(images,3)]);
unbiasedIntensityNorms=squeeze(sqrt(sum(sum(abs(images).^2))));
images=images./repmat(permute(unbiasedIntensityNorms,[3 2 1]),[size(images,1) size(images,2) 1]);
images=reshape(images,[],size(images,3));
angleDeviationFromOrthogonal=pi/2-acos(max(-1,min(1,images'*images)));
figure;
showImage(angleDeviationFromOrthogonal/(pi/2)+1e-6i); axis equal; title('Deviation from orthogonal.');
save([outputFileName,'.mat'],'angleDeviationFromOrthogonal','-append');
end
function waitForUserSpecifiedTime()
minutesToWait=input('Enter the number of minutes to wait before starting the experiment: ');
if (~isempty(minutesToWait))
logMessage('Waiting for %0.0f minutes to start experiment.',minutesToWait);
pause(minutesToWait*60);
logMessage('Starting measurement...');
else
logMessage('Starting measurement immediately...');
end
end
|
github
|
mc225/Softwares_Tom-master
|
calibrateAmplitude.m
|
.m
|
Softwares_Tom-master/SLMCalibration/calibrateAmplitude.m
| 2,946 |
utf_8
|
7a8671e841a487e10564b3aa4a14aec7
|
%
% [graylevels,amplitudes]=calibrateAmplitude(slm,cam)
%
% This code is in a beta stage only!
%
% Attempts to measure the amplitude response for a Dual Head SLM.
%
% Input parameters:
% slm: the DualHeadSLM object to measure
% cam: the camera for the measurement
%
% Output parameters:
% graylevels: the measured graylevels, normalized to the dynamic range
% amplitudes: the measured amplitude for each graylevel (square root of the intensity)
%
function [graylevels,amplitudes]=calibrateAmplitude(slm,cam)
if (nargin<1 || isempty(slm))
slm=DualHeadSLM(2,[1/18 1/18]);
end
referenceDeflectionFrequency=slm.referenceDeflectionFrequency;
slm.referenceDeflectionFrequency=[0 0]; %Set to zero for now
if (nargin<2 || isempty(cam))
cam=BaslerGigECam();
cam.integrationTime=25e-3;
cam.defaultNumberOfFramesToAverage=10;
end
origTwoPiEquivalent=slm.twoPiEquivalent;
slm.twoPiEquivalent=1.0;
roiSize=[128 128]; % [height, width]
%Find the zeroth order spot center on the CCD
slm.modulate(1);
zerothOrderImage=cam.acquire();
%Find the first order spot center on the CCD
slm.referenceDeflectionFrequency=referenceDeflectionFrequency; %Set the deflection frequency we are interested in
slm.modulate(1);
initialImage=cam.acquire()-zerothOrderImage;
[ign, maxIdx]=max(initialImage(:));
[maxRow, maxCol]=ind2sub(size(initialImage),maxIdx);
centerPos=[maxRow,maxCol]; % [row, col]
%Adjust the region of interest
centerPos=min(max(centerPos,floor((roiSize+1)/2)),size(initialImage)-floor((roiSize+1)/2));%Make sure that the region of interest is on the CCD
logMessage('Centering the region of interest around the coordinates [row,col]=[%u,%u].',centerPos);
roi=[centerPos([2 1])-floor(roiSize([2 1])/2), roiSize([2 1])]; % [col, row, width, height]
cam.regionOfInterest=roi;
%Get dark image
slm.modulate(0); %The CCD should be black in principle
cam=cam.acquireBackground(100);
graylevels=[0:4:255]./256;
graylevels=fftshift(graylevels); %Start somewhere in the center where there is signal
intensities=zeros(size(graylevels));
probeIdx=0;
for (idx=1:length(graylevels))
slm.modulate(graylevels(idx));
img=cam.acquire();
% intensities(idx)=max(img(:));
if (probeIdx<=0)
[ign probeIdx]=max(img(:));
end
intensities(idx)=median(img(probeIdx+[-size(img,1)-1 -size(img,1) -size(img,1)+1 -1 0 1 size(img,1)-1 size(img,1) size(img,1)+1]));
% imagesc(img); colorbar()
% drawnow;
end
slm.twoPiEquivalent=origTwoPiEquivalent;
graylevels=ifftshift(graylevels);
intensities=ifftshift(intensities);
intensities=max(0,intensities);%Negative intensities are just noise
amplitudes=sqrt(intensities);
plot(graylevels,amplitudes);
end
|
github
|
mc225/Softwares_Tom-master
|
calibrateAmplitudeInducedPhase.m
|
.m
|
Softwares_Tom-master/SLMCalibration/calibrateAmplitudeInducedPhase.m
| 3,495 |
utf_8
|
8e6f2ccda46d0ad39fff1f004fd03b0d
|
%
% [graylevels,phases]=calibrateAmplitudeInducedPhase(slm,cam)
%
% This code is in a beta stage only!
%
% Attempts to measure the phase error when doing amplitude modulation on a Dual Head SLM.
%
% Input parameters:
% slm: the DualHeadSLM object to measure
% cam: the camera for the measurement
%
% Output parameters:
% graylevels: the measured graylevels, normalized to the dynamic range
% phases: the measured phase error for each graylevel
%
function [graylevels,phases]=calibrateAmplitudeInducedPhase(slm,cam)
if (nargin<1 || isempty(slm))
slm=DualHeadSLM(2,[1/18 1/18]);
slm.twoPiEquivalent=1.0;
end
referenceDeflectionFrequency=slm.referenceDeflectionFrequency;
slm.referenceDeflectionFrequency=[0 0]; %Set to zero for now
if (nargin<2 || isempty(cam))
cam=BaslerGigECam();
cam.integrationTime=25e-3;
cam.defaultNumberOfFramesToAverage=10;
end
roiSize=[128 128]; % [height, width]
[X,Y]=meshgrid([1:slm.maxSize(2)],[1:slm.maxSize(1)]);
referenceDeflection=exp(2i*pi*(X*slm.referenceDeflectionFrequency(2)+Y*slm.referenceDeflectionFrequency(1)));
%Find the zeroth order spot center on the CCD
slm.modulate(1);
zerothOrderImage=cam.acquire();
%Find the first order spot center on the CCD
slm.referenceDeflectionFrequency=referenceDeflectionFrequency;
slm.modulate(1);
initialImage=cam.acquire()-zerothOrderImage;
[ign, maxIdx]=max(initialImage(:));
[maxRow, maxCol]=ind2sub(size(initialImage),maxIdx);
centerPos=[maxRow,maxCol]; % [row, col]
%Adjust the region of interest
centerPos=min(max(centerPos,floor((roiSize+1)/2)),size(initialImage)-floor((roiSize+1)/2));%Make sure that the region of interest is on the CCD
logMessage('Centering the region of interest around the coordinates [row,col]=[%u,%u].',centerPos);
roi=[centerPos([2 1])-floor(roiSize([2 1])/2), roiSize([2 1])]; % [col, row, width, height]
cam.regionOfInterest=roi;
%Get dark image
slm.modulate(0); %The CCD should be black in principle
cam=cam.acquireBackground(100);
graylevels=[0:16:255]./256;
graylevels=fftshift(graylevels); %Start somewhere in the centre where there is signal
values=zeros(size(graylevels));
probeIdx=0;
for (idx=1:length(graylevels))
slm.modulate(graylevels(idx)*(angle(referenceDeflection)<0));
img=cam.acquire();
% values(idx)=max(img(:));
if (probeIdx<=0)
[ign probeIdx]=max(img(:));
end
valueTimesIntensity=median(img(probeIdx+[-size(img,1)-1 -size(img,1) -size(img,1)+1 -1 0 1 size(img,1)-1 size(img,1) size(img,1)+1]));
%Compare with amplitude
slm.modulate(graylevels(idx));
img=cam.acquire();
intensity=median(img(probeIdx+[-size(img,1)-1 -size(img,1) -size(img,1)+1 -1 0 1 size(img,1)-1 size(img,1) size(img,1)+1]));
values(idx)=valueTimesIntensity./max(intensity,eps(1));
% imagesc(img); colorbar()
% drawnow;
end
graylevels=ifftshift(graylevels);
values=ifftshift(values);
values=max(0,values);%Negative values are just noise
phases=acos(1-2*sqrt(values(beginIdx:endIdx)./max(values(:))));
figure;
plot(graylevels,phases);
totalStroke=phases(end)+(phases(end)-phases(1))/(length(phases)-1) - phases(1);
title(sprintf('total stroke: %.2fpi',totalStroke/pi));
end
|
github
|
mc225/Softwares_Tom-master
|
estimateTwoPiEquivalent.m
|
.m
|
Softwares_Tom-master/SLMCalibration/estimateTwoPiEquivalent.m
| 2,635 |
utf_8
|
a13759789434e2156382f5fea68e8eff
|
% [twoPiEquivalent slm]=estimateTwoPiEquivalent(slm,cam,probePos,probeSize)
%
% This code is in a beta stage only!
%
% Optimizes the mean intensity in the region of interest using direct search.
%
% Input parameters:
% slm: the SLM object to measure
% cam: the camera for the measurement
% probePos: the position ([bottom,right]) of the focal spot where to measure the intensity change (default center)
% probeSize: the area height and width to measure and take the median of (default [4 4]).
%
% Output parameters:
% twoPiEquivalent: the detected value indicating the fraction of the dynamic range that corresponds to 2pi modulation
% slm: the input slm object with the twoPiEquivalent property updated
%
function [twoPiEquivalent slm]=estimateTwoPiEquivalent(slm,cam,probePos,probeSize)
if (nargin<3 || isempty(probePos))
probePos=cam.regionOfInterest(1:2)+1+floor(cam.regionOfInterest(3:4)/2);
end
if (nargin<4 || isempty(probeSize))
probeSize=[1 1]*5;
end
minIntensity=0.01;
testIntensity=1.0;
while testIntensity>minIntensity && isAlmostSaturated(slm,cam,testIntensity)
testIntensity=testIntensity/2;
end
if (testIntensity>minIntensity)
[twoPiEquivalent,fval,exitflag,output] = fminsearch(@(x) -measureEfficiency(slm,cam,probePos,probeSize,testIntensity,x),slm.twoPiEquivalent,optimset('TolX',0.001,'MaxIter',20,'Display','iter'));
slm.twoPiEquivalent=twoPiEquivalent;
else
twoPiEquivalent=slm.twoPiEquivalent;
logMessage('Couldn''t get phase estimate due to image saturation!');
end
end
function almostSaturated=isAlmostSaturated(slm,cam,testIntensity)
slm.modulate(testIntensity);
img=cam.acquire()+cam.background;
almostSaturated=any(img(:)>.80);
end
function efficiency=measureEfficiency(slm,cam,probePos,probeSize,testIntensity,twoPiEquivalent)
slm.twoPiEquivalent=twoPiEquivalent;
slm.modulate(testIntensity);
img=cam.acquire();
probePos=probePos-cam.regionOfInterest(1:2);
probeRange1=probePos(1)+[-floor(probeSize(1)/2):floor((probeSize(1)-1)/2)];
probeRange2=probePos(2)+[-floor(probeSize(2)/2):floor((probeSize(2)-1)/2)];
img=img(probeRange1(probeRange1>0 & probeRange1<=size(img,1)),probeRange2(probeRange2>0 & probeRange2<=size(img,2)),:);
efficiency=median(img(:));
end
function value=defaultProbeFunctor(img)
rng=[-5:5];
if (size(img,1)>length(rng))
img=img(1+floor(end/2)+rng,:,:);
end
if (size(img,2)>length(rng))
img=img(:,1+floor(end/2)+rng,:);
end
value=median(img(:));
end
|
github
|
playerkk/map-words-faster-rcnn-master
|
classification_demo.m
|
.m
|
map-words-faster-rcnn-master/caffe-fast-rcnn/matlab/demo/classification_demo.m
| 5,412 |
utf_8
|
8f46deabe6cde287c4759f3bc8b7f819
|
function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to you Matlab search PATH to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github
|
playerkk/map-words-faster-rcnn-master
|
voc_eval.m
|
.m
|
map-words-faster-rcnn-master/lib/datasets/VOCdevkit-matlab-wrapper/voc_eval.m
| 1,332 |
utf_8
|
3ee1d5373b091ae4ab79d26ab657c962
|
function res = voc_eval(path, comp_id, test_set, output_dir)
VOCopts = get_voc_opts(path);
VOCopts.testset = test_set;
for i = 1:length(VOCopts.classes)
cls = VOCopts.classes{i};
res(i) = voc_eval_cls(cls, VOCopts, comp_id, output_dir);
end
fprintf('\n~~~~~~~~~~~~~~~~~~~~\n');
fprintf('Results:\n');
aps = [res(:).ap]';
fprintf('%.1f\n', aps * 100);
fprintf('%.1f\n', mean(aps) * 100);
fprintf('~~~~~~~~~~~~~~~~~~~~\n');
function res = voc_eval_cls(cls, VOCopts, comp_id, output_dir)
test_set = VOCopts.testset;
year = VOCopts.dataset(4:end);
addpath(fullfile(VOCopts.datadir, 'VOCcode'));
res_fn = sprintf(VOCopts.detrespath, comp_id, cls);
recall = [];
prec = [];
ap = 0;
ap_auc = 0;
do_eval = (str2num(year) <= 2007) | ~strcmp(test_set, 'test');
if do_eval
% Bug in VOCevaldet requires that tic has been called first
tic;
[recall, prec, ap] = VOCevaldet(VOCopts, comp_id, cls, true);
ap_auc = xVOCap(recall, prec);
% force plot limits
ylim([0 1]);
xlim([0 1]);
print(gcf, '-djpeg', '-r0', ...
[output_dir '/' cls '_pr.jpg']);
end
fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc);
res.recall = recall;
res.prec = prec;
res.ap = ap;
res.ap_auc = ap_auc;
save([output_dir '/' cls '_pr.mat'], ...
'res', 'recall', 'prec', 'ap', 'ap_auc');
rmpath(fullfile(VOCopts.datadir, 'VOCcode'));
|
github
|
svndl/rcaBase-master
|
textExportToRca.m
|
.m
|
rcaBase-master/functions/textExportToRca.m
| 9,408 |
utf_8
|
44fabe2307c472b1ad3601606eb67d23
|
function [cellData,indF,indB,noiseCell1,noiseCell2,freqLabels,binLabels,chanIncluded]=textExportToRca(pathname,dataType)
if nargin<2 || isempty(dataType), dataType='RLS'; fprintf('Using RLS. '); end;
if nargin<1, error('Path to datafiles is required'); end
if ~strcmp(pathname(end),'/'), pathname=cat(2,pathname,'/'); end
switch dataType % check for correct data type
case {'DFT','RLS'}
filenames=dir([pathname sprintf('%s*.txt',dataType)]);
otherwise
error('dataType must be ''RLS'' or ''DFT''');
end
nFilenames=numel(filenames);
if nFilenames<1
error('No %s files were found in %s',dataType,pathname);
end
cellData=cell(nFilenames,1);
noiseCell1=cell(nFilenames,1);
noiseCell2=cell(nFilenames,1);
binLabels=cell(nFilenames,1);
freqLabels=cell(nFilenames,1);
indB=cell(nFilenames,1);
indF=cell(nFilenames,1);
for f=1:length(filenames)
% check filename
if ~strcmp(filenames(f).name(1:3),dataType)
error('inputfile %s is not datatype %s',filenames(f).name,dataType);
else
end
[~,freqCrnt,binLabelsCrnt,data]=getSweepDataFlex(fullfile(pathname,filenames(f).name));
% set values
tempName = filenames(f).name;
condIdx = str2num(tempName(end-6:end-4)); % grab condition number
channelsToUse = unique(data(:,2));
freqsToUse = unique(data(:,3));
binsToUse = unique(data(:,4)); % note, this includes averaged bin
nFreqs=numel(freqsToUse);
nChannels=numel(channelsToUse);
nBins=numel(binsToUse);
% assign frequency and bin labels
binLabels{condIdx} = binLabelsCrnt(1:nBins)';
freqLabels{condIdx} = freqCrnt(freqsToUse);
if isempty(data)
warning('No data found in %s',filenames(f).name)
continue
end
%% check congruency of trials
trials=data(:,1);
trialInds=unique(trials(:));
nTrials=numel(trialInds);
nEntriesPerTrialInd=zeros(nTrials,1);
for tr=1:length(trialInds)
trialData=data(trials==trialInds(tr),:);
nEntriesPerTrialInd(tr)=numel(trialData(:));
end
% only keep trials in which the number of entries is congruent
trialIndsToKeep=trialInds(nEntriesPerTrialInd==mode(nEntriesPerTrialInd));
nTrialsToKeep=numel(trialIndsToKeep);
%% organize in data
eeg=nan(nFreqs*nBins*2,nChannels,nTrialsToKeep);
noise1=nan(nFreqs*nBins*2,nChannels,nTrialsToKeep);
noise2=nan(nFreqs*nBins*2,nChannels,nTrialsToKeep);
for tr=1:nTrialsToKeep
thisTrialInd=trialIndsToKeep(tr);
trialData=data(trials==thisTrialInd,:);
trialChannels=trialData(:,2);
trialFreqs=trialData(:,3);
trialBins=trialData(:,4);
% freqs x bins
for ch=1:nChannels
theseReals=trialData(trialChannels==channelsToUse(ch) & ismember(trialFreqs,freqsToUse) & ismember(trialBins,binsToUse),5);
theseImags=trialData(trialChannels==channelsToUse(ch) & ismember(trialFreqs,freqsToUse) & ismember(trialBins,binsToUse),6);
% noise 1
theseNoiseReals1=trialData(trialChannels==channelsToUse(ch) & ismember(trialFreqs,freqsToUse) & ismember(trialBins,binsToUse),7);
theseNoiseImags1=trialData(trialChannels==channelsToUse(ch) & ismember(trialFreqs,freqsToUse) & ismember(trialBins,binsToUse),8);
% noise 2
theseNoiseReals2=trialData(trialChannels==channelsToUse(ch) & ismember(trialFreqs,freqsToUse) & ismember(trialBins,binsToUse),9);
theseNoiseImags2=trialData(trialChannels==channelsToUse(ch) & ismember(trialFreqs,freqsToUse) & ismember(trialBins,binsToUse),10);
eeg(:,ch,tr)=[theseReals; theseImags];
noise1(:,ch,tr)=[theseNoiseReals1; theseNoiseImags1];
noise2(:,ch,tr)=[theseNoiseReals2; theseNoiseImags2];
end
end
cellData{condIdx}=eeg;
noiseCell1{condIdx}=noise1;
noiseCell2{condIdx}=noise2;
indF{condIdx}=trialFreqs(trialChannels==channelsToUse(1) & ismember(trialFreqs,freqsToUse) & ismember(trialBins,binsToUse));
indB{condIdx}=trialBins(trialChannels==channelsToUse(1) & ismember(trialFreqs,freqsToUse) & ismember(trialBins,binsToUse));
end
chanIncluded = channelsToUse;
end
%%
function [colHdr, freqsAnalyzed, sweepVals, dataMatrix]=getSweepDataFlex(datafile)
%% Imports Sweep Data from a Text File
%
% [colHdr, freqsAnalyzed, sweepVals, dataMatrix]=GetSweepDataFlex(datafile, chanToSave)
%
%% Inputs:
% datafile string containing the data file
% chanToSave the requested electrode(s)
%
%% Outputs:
% colHdr is a string with column fields
% freqsAnalyzed are the individual frequencies of the VEPs ('1F1' etc.)
% sweepVals are the contrasts or stimulus values used
% dataMatrix matrix containing the desired data
fname=datafile;
% SetUp import columns and data formats, from JA
% Asterisk (*) after % exclude selected columns
%
hdrFields = {
'iSess' '%s\t' 0 %1
'iCond' '%f\t' 1 %2
'iTrial' '%f\t' 1 %3
'iCh' '%s\t' 1 %4 This becomes %f later in the function
'iFr' '%f\t' 1 %5
'AF' '%f\t' 1 %6
'xF1' '%f\t' 1 %7
'xF2' '%f\t' 1 %8
'Harm' '%s\t' 2 %9
'FK_Cond' '%f\t' 1 %10
'iBin' '%f\t' 1 %11
'SweepVal' '%f\t' 1 %12
'Sr' '%f\t' 1 %13
'Si' '%f\t' 1 %14
'N1r' '%f\t' 1 %15
'N1i' '%f\t' 1 %16
'N2r' '%f\t' 1 %17
'N2i' '%f\t' 1 %18
'Signal' '%f\t' 1 %19
'Phase' '%f\t' 1 %20
'Noise' '%f\t' 1 %21
'StdErr' '%f\t' 1 %22
'PVal' '%f\t' 1 %23
'SNR' '%f\t' 2 %24
'LSB' '%f\t' 2 %25
'RSB' '%f\t' 2 %26
'UserSc' '%s\t' 2 %27
'Thresh' '%f\t' 2 %28
'ThrBin' '%f\t' 2 %29
'Slope' '%f\t' 2 %30
'ThrInRange' '%s\t' 2 %31
'MaxSNR' '%f\t' 2 };%32
channelIx = 4;
freqIx = 5;
harmIx = 9;
fid=fopen(fname);
if fid == -1
error('File %s could not be opened.',fname);
end
tline=fgetl(fid);
dati=textscan(fid, [hdrFields{:,2}], 'delimiter', '\t', 'EmptyValue', nan);
fclose(fid);
% Convert the channel identifier string into digit only
for i=1:size(dati{1,channelIx})
chan{1,i}=sscanf(dati{1, channelIx}{i}, 'hc%d');
end
dati{1,channelIx}=chan';
usCols=[3 4 5 11 13 14 15 16 17 18];
% Fill in essential matrix
for s=1:length(usCols)
o=usCols(s);
if o ~= channelIx
dataMatrix(:,s)=(dati{1, o}(:));
else
if isempty(cell2mat((dati{1, o}(:))))
colHdr = {};
freqsAnalyzed ={};
sweepVals= nan;
dataMatrix = nan;
fprintf('ERROR! rawdata is empty..\n')
return;
else
dataMatrix(:,s)=cell2mat((dati{1, o}(:)));
end
end
end
binIndices = unique(dataMatrix(:, 4)); % this will always include 0
sweepTemp=(dati{1, 12}(1:length(binIndices))); % the 12th column in dati are the bin levels, aka "SweepVal"s, include the zeroth bin, which has nan
sweepTemp=sweepTemp';
sweepVals = arrayfun(@(x) num2str(x,'%.4f'), sweepTemp,'uni',false);
sweepVals(1) = {'ave'};
%if ~isempty(chanToSave)
% dataMatrix=dataMatrix(ismember(int16(dataMatrix(:, 2)),int16(chanToSave(:))),:); % Restricts the running matrix to the selected electrodes
%end
% dataMatrix=dataMatrix(dataMatrix(:, 4)>0, :); % Selects all bins but the 0th one (i.e. the average bin)
dataMatrix=dataMatrix(dataMatrix(:, 1)>0, :); % Selects all trials but the 0th one (i.e. the average trial)
[freqsAnalyzed,tmpIx]=unique(dati{1, harmIx}(:));
freqNum = nan(1,length(freqsAnalyzed));
for f = 1:length(freqsAnalyzed)
freqNum(f) = dati{1,freqIx}(tmpIx(f));
end
[tmp,tmpIx] = sort(freqNum);
freqsAnalyzed = freqsAnalyzed(tmpIx);
for m = 1:length(usCols)
colHdr{m} = hdrFields{usCols(m),1};
end
dataMatrix(:,end+1)=sqrt(dataMatrix(:,end-1).^2+dataMatrix(:,end).^2); % Computes amplitudes in final column
% replace samples with zero amplitudes with NaN because 0 is PowerDiva's
% indicator of a rejected epoch
zeroAmpRows = dataMatrix(:,end)==0;
dataMatrix(zeroAmpRows,5:end) = nan;
colHdr{end+1} = 'ampl';
end
|
github
|
svndl/rcaBase-master
|
selectDataForTraining.m
|
.m
|
rcaBase-master/functions/selectDataForTraining.m
| 5,500 |
utf_8
|
ee35192a3b33549716213ec182ff17cc
|
function [signalDataSel,noise1Sel,noise2Sel,indFSel,indBSel,freqLabelsSel,binLabelsSel,trialsSel] = selectDataForTraining(sourceDataFileName,binsToUse,freqsToUse,condsToUse,trialsToUse)
%
% [signalData,noise1,noise2,indF,indB,,freqLabelsSel,binLevelsSel,trialsSel] = selectDataForTraining(sourceDataFileName,binsToUse,freqsToUse,condsToUse,trialsToUse)
%
% Return only the desired subset of data contained in sourceDataFileName
% which contains only binsToUse, freqsToUse, condsToUse, trialsToUse
load(sourceDataFileName); % should contain these variables: signalData,indF,indB,noise1,noise2,freqLabels,binLevels,chanIncluded
if nargin < 5
trialsToUse = [];
else
end
if nargin < 4 || isempty(condsToUse)
condsToUse = 1:size(signalData,1);
else
end
if nargin < 3
freqsToUse = [];
else
end
if nargin < 2
binsToUse = [];
else
end
nConds = length(condsToUse);
signalDataSel = cell(nConds,1);
noise1Sel = cell(nConds,1);
noise2Sel = cell(nConds,1);
binLabelsSel = cell(nConds,1);
freqLabelsSel = cell(nConds,1);
trialsSel = cell(nConds,1);
indBSel = cell(nConds,1);
indFSel = cell(nConds,1);
for c = 1:nConds
if condsToUse(c) > size(signalData,1) || isempty(signalData{condsToUse(c)});
signalDataSel{c} = [];
noise1Sel{c} = [];
noise2Sel{c} = [];
indFSel{c} = [];
indBSel{c} = [];
freqLabelsSel{c} = [];
binLabelsSel{c} = [];
trialsSel{c} = [];
else
if isempty(binsToUse)
% use all available bins
% (note: canmot differ across conditions)
binsToUse = unique(indB{condsToUse(c)});
%binsToUse = binsToUse(binsToUse>0); % use all bins except the average bin
else
end
if isempty(freqsToUse)
% use all available frequencies
% (note: canmot differ across conditions)
freqsToUse = unique(indF{condsToUse(c)});
else
end
selRowIx = ismember(indB{condsToUse(c)},binsToUse) & ismember(indF{condsToUse(c)},freqsToUse);
if isempty(trialsToUse)
% use all available trials
% (note: can differ across conditions)
curTrials = 1:size(signalData{condsToUse(c)},3); % use all trials
else
curTrials = trialsToUse;
end
missingIdx = find(~ismember(curTrials,1:size(signalData{condsToUse(c)},3)));
if ~isempty(missingIdx)
error('Input trial indices "%s" is not among set of trials',num2str(curTrials(missingIdx),'%d,'));
else
end
signalDataSel{c} = signalData{condsToUse(c)}(repmat(selRowIx,[2,1]),:,curTrials); % repmat because the first half is real, second half is imag with same ordering
noise1Sel{c} = noise1{condsToUse(c)}(repmat(selRowIx,[2,1]),:,curTrials);
noise2Sel{c} = noise2{condsToUse(c)}(repmat(selRowIx,[2,1]),:,curTrials);
% find non-empty frequency indices
nonEmpty = find(cell2mat(cellfun(@(x) ~isempty(x),indF,'uni',false)));
% find first among conditions to use
nonEmpty = min(nonEmpty(ismember(nonEmpty,condsToUse)));
% check if indices are unequal
if any ( indF{nonEmpty} ~= indF{condsToUse(c)} )
error('frequency indices are not matched across conditions');
elseif any ( indB{nonEmpty} ~= indB{condsToUse(c)} )
error('bin indices are not matched across conditions');
else
end
% deal with NaNs in binLabels
if any(contains(binLabels{condsToUse(c)}, 'NaN'))
nan_idx = contains(binLabels{condsToUse(c)}, 'NaN') == 1;
binLabels{condsToUse(c)}(nan_idx) = arrayfun(@(x) sprintf('bin%02d', (x)), 1:sum(nan_idx), 'uni' , false);
else
end
% assign indices and labels of selected data features
% grab bin indices
indBSel{c} = indB{condsToUse(c)}(selRowIx)+1; % add one to turn into proper index
% grab frequency indices
indFSel{c} = indF{condsToUse(c)}(selRowIx);
% grab bin labels
binLabelsSel{c} = binLabels{condsToUse(c)};
% grap frequency labels
freqLabelsSel{c} = freqLabels{condsToUse(c)};
% grap frequency labels
trialsSel{c} = curTrials;
end
end
% now replace missing conditions with NaNs, dude!
signalDataSel = replaceEmpty(signalDataSel);
noise1Sel = replaceEmpty(noise1Sel);
noise2Sel = replaceEmpty(noise2Sel);
indFSel = replaceEmpty(indFSel);
indBSel = replaceEmpty(indBSel);
freqLabelsSel = replaceEmpty(freqLabelsSel);
binLabelsSel = replaceEmpty(binLabelsSel);
trialsSel = replaceEmpty(trialsSel);
end
function cellOut = replaceEmpty(cellIn)
nonEmpty = cell2mat(cellfun(@(x) ~isempty(x),cellIn,'uni',false));
repIdx = find(nonEmpty,1,'first');
cellOut = cellIn;
cellOut(~nonEmpty) = {nan(size(cellIn{repIdx}))};
end
|
github
|
svndl/rcaBase-master
|
aggregateData.m
|
.m
|
rcaBase-master/functions/aggregateData.m
| 17,781 |
utf_8
|
701058e4e436f4b6df5f6d2851402505
|
function rca_struct = aggregateData(rca_struct, keep_conditions, error_type, trial_wise, do_nr)
% rca_struct = aggregateData(rca_struct, keep_conditions, error_type, trial_wise, do_nr)
%
% input:
% rca_struct: created during call to rcaSweep
% keep_conditions: [true]/false
% if false, will average over conditions
% error_type: 'SEM'/'none'/'95CI'
% or a string specifyingn a different percentage
% CI formated following: '%.1fCI'
% trial-wise: [true]/false
% if true, will compute trial-wise errors and stats
% do_nr: harmonic x rc x condition logical,
% indicating when to do Naka-Rushton fitting
% (only makes sense to do for sweep data)
% default is not to do it anywhere
%
% output: function will return rca_struct, and add fields containing
% aggregate statistics for all components (described below).
%
% Note that
% (a) the comparison electrode data is automatically added as
% as an additional component in the output.
% (b) if there is more than one bin in the input (sweep data) the
% vector average across bins will be added as a final bin.
% (c) In the current iteration of rcaSweep, each rca_struct contains
% only one harmonic, but harmonic is nonetheless preserved
% as an output dimension
%
% "mean", with the following subfields:
% real_signal: REAL coefficients, vector-averaged
% imag_signal: IMAGINARY coefficients, vector-averaged
% amp_signal: AMPLITUDES, vector-averaged
% phase_signal: PHASES, vector-averaged
% z_snr: Z_SNR
% amp_noise: NOISE BAND AMPLITUDES, vector-averaged
% all subfields are bin-by-harmonic-by-component-by-condition arrays
%
% "subjects", with the following subfields
% amp_signal: AMPLITUDES
% proj_amp_signal: PROJECTED AMPLITUDES
% amp_noise: NOISE BAND AMPLITUDES
% z_snr: Z_SNR
% all subfields are bin-by-harmonic-by-component-by-subject-by-condition arrays
%
% "stats", with the following subfields
% amp_err_up: upper error bars
%
% amp_err_lo: lower error bars
%
% t_sig: significance (true/false) for student's t-test against zero
% run on projected amplitudes across subjects
%
% t_p: p-values for student's t-test against zero
%
% t_val: t-values for student's t-test against zero
%
% t2_sig: significance (true/false) for Hotelling's T2 against zero
% run on real and imag coefficients across subjects
%
% t2_p: p-values for Hotelling's T2 against zero
%
% t2_val: t-values for Hotelling's T2 against zero
%
% ... all of the above are
% bin-by-harmonic-by-component-by-condition arrays
%
% err_type: string, what type of error bar was computed
%
% naka_rushton: struct of naka-rushton outputs, pretty
% self-explanatory
% mk: changed mean phase calculation from atan to atan2 (05/18/2020)
if nargin<2
keep_conditions=true;
end
if ( nargin<3 ) || isempty(error_type)
error_type = 'SEM';
else
end
if ( nargin<4 ) || isempty(trial_wise)
trial_wise = false;
else
end
if nargin<5
do_nr=[];
else
end
rcaSettings = rca_struct.settings;
% take care of case where subfield is named
%'.data' rather than '.rca_data'
if isfield(rca_struct,'comparisonData')
rca_struct.rca_data = rca_struct.data;
rca_struct = rmfield(rca_struct,'data')
else
end
% add comparison data as last component
if isfield(rca_struct,'comparisonData')
rcaData = cellfun(@(x,y) cat(2,x,y), rca_struct.rca_data,rca_struct.comparisonData,'uni',false);
else
rcaData = rca_struct.rca_data;
end
nSubjects = size(rcaData,2);
if ~keep_conditions
% concatenate conditions, but keep everything else seperate
rcaData = arrayfun(@(x) cat(3,rcaData{:,x}),1:nSubjects,'uni',false);
else
end
nConditions = size(rcaData,1);
% get freqs and bins from the data
dataFreqs = unique(rcaSettings.freqIndices);
dataBins = unique(rcaSettings.binIndices);
nFreqs = length(dataFreqs);
nBins = length(dataBins);
nTrials = max(max(cellfun(@(x) size(x,3),rcaData)));
nCompFromInputData = max(max(cellfun(@(x) size(x,2),rcaData))); % note, includes comparison data
nSampFromInputData = max(max(cellfun(@(x) size(x,1),rcaData)));
if nFreqs*nBins*2 ~= nSampFromInputData
error('number of frequencies and bins does not match the number of samples');
else
end
if nBins > 1
% the average will be computed and added to the bin
nBins = nBins + 1;
else
end
% do the noise
% add comparison data, and compute the amplitudes, which is all you need
if isfield(rca_struct,'noiseLower') && isfield(rca_struct,'noiseHigher')
ampNoiseBins = zeros(nBins,nFreqs,nCompFromInputData,nConditions);
if trial_wise
ampNoiseBinsSubjects = zeros(nBins,nFreqs,nCompFromInputData,nSubjects*nTrials,nConditions);
else
ampNoiseBinsSubjects = zeros(nBins,nFreqs,nCompFromInputData,nSubjects,nConditions);
end
for z = 1:2
if z == 1
% lower
noiseStruct.rca_data = rca_struct.noiseLower;
else
noiseStruct.rca_data = rca_struct.noiseHigher;
end
noiseStruct.settings = rcaSettings;
noiseStruct.Out = aggregateData(noiseStruct, keep_conditions, 'none', []); % do not compute NR or error
ampNoiseBins = noiseStruct.Out.mean.amp_signal + ampNoiseBins;
ampNoiseBinsSubjects = noiseStruct.Out.subjects.amp_signal + ampNoiseBinsSubjects;
clear noiseStruct;
end
ampNoiseBins = ampNoiseBins./2;
ampNoiseBinsSubjects = ampNoiseBinsSubjects./2;
else
ampNoiseBins = nan(nBins,nFreqs,nCompFromInputData,nConditions);
ampNoiseBinsSubjects = nan(nBins,nFreqs,nCompFromInputData,nSubjects,nConditions);
end
% convert to real/imaginary
[rcaDataReal,rcaDataImag] = getRealImag(rcaData);
if ~strcmp(error_type,'none')
ampErrBins = nan(nBins,nFreqs,nCompFromInputData,nConditions,2);
tPval = nan(nBins,nFreqs,nCompFromInputData,nConditions);
tSqrd = nan(nBins,nFreqs,nCompFromInputData,nConditions);
tSig = nan(nBins,nFreqs,nCompFromInputData,nConditions);
end
% nBins + 1, room for average
muRcaDataReal = nan(nBins,nFreqs,nCompFromInputData,nConditions);
muRcaDataImag = nan(nBins,nFreqs,nCompFromInputData,nConditions);
NR_Params = nan(5,nFreqs,nCompFromInputData,nConditions);
NR_R2 = nan(1,nFreqs,nCompFromInputData,nConditions);
NR_Range = nan(1,nFreqs,nCompFromInputData,nConditions);
NR_hModel = [];
NR_JK_SE = nan(5,nFreqs,nCompFromInputData,nConditions);
NR_JK_Params = nan(5,nSubjects,nFreqs,nCompFromInputData,nConditions);
% assign default value to do_nr
if isempty(do_nr)
do_nr = false(nFreqs,nCompFromInputData,nConditions);
else
end
for condNum = 1:nConditions
tempReal = [];
tempImag = [];
tempZ = [];
for s=1:nSubjects
if trial_wise
if s == 1
nanSet = nan(nBins,nFreqs,nCompFromInputData,nSubjects*nTrials);
else
end
% grab all subjects' data, without averaging over trials:
tempReal = cat(3,tempReal,rcaDataReal{condNum,s});
tempImag = cat(3,tempImag,rcaDataImag{condNum,s});
else
if s == 1
nanSet = nan(nBins,nFreqs,nCompFromInputData,nSubjects);
else
end
% grab all subjects' data, averaging over trials:
tempReal = cat(3,tempReal,nanmean(rcaDataReal{condNum,s},3));
tempImag = cat(3,tempImag,nanmean(rcaDataImag{condNum,s},3));
end
tempZ = cat(3,tempZ, computeZsnr(rcaDataReal{condNum,s},rcaDataImag{condNum,s}) );
end
muRcaDataRealAllSubj(:,:,:,:,condNum) = nanSet;
muRcaDataImagAllSubj(:,:,:,:,condNum) = nanSet;
zRcaDataAllSubj(:,:,:,:,condNum) = nanSet;
% split bins and frequencies, and make sure only selected components are included
binLabels = cell2mat(cellfun(@(x) str2num(x), rcaSettings.binLabels,'uni',false));
for rc = 1:nCompFromInputData
for f = 1:nFreqs
for b = 1:nBins
if b == nBins && b > 1
% get the vector average over bins
muRcaDataRealAllSubj(b,f,rc,1:size(tempReal(curIdx,rc,:),3),condNum) = nanmean(muRcaDataRealAllSubj(1:(nBins-1),f,rc,1:size(tempReal(curIdx,rc,:),3),condNum),1);
muRcaDataImagAllSubj(b,f,rc,1:size(tempImag(curIdx,rc,:),3),condNum) = nanmean(muRcaDataImagAllSubj(1:(nBins-1),f,rc,1:size(tempReal(curIdx,rc,:),3),condNum),1);
zRcaDataAllSubj(b,f,rc,1:size(tempZ(curIdx,rc,:),3),condNum) = nanmean(zRcaDataAllSubj(1:(nBins-1),f,rc,1:size(tempZ(curIdx,rc,:),3),condNum));
else
curIdx = find(rcaSettings.freqIndices==dataFreqs(f) & rcaSettings.binIndices==dataBins(b));
muRcaDataRealAllSubj(b,f,rc,1:size(tempReal(curIdx,rc,:),3),condNum) = tempReal(curIdx,rc,:);
muRcaDataImagAllSubj(b,f,rc,1:size(tempImag(curIdx,rc,:),3),condNum) = tempImag(curIdx,rc,:);
zRcaDataAllSubj(b,f,rc,1:size(tempZ(curIdx,rc,:),3),condNum) = tempZ(curIdx,rc,:);
end
end
end
end
% average over trials and subjects for each condition
muRcaDataReal(:,:,:,condNum) = nanmean(muRcaDataRealAllSubj(:,:,:,:,condNum),4); % weights each trial equally
muRcaDataImag(:,:,:,condNum) = nanmean(muRcaDataImagAllSubj(:,:,:,:,condNum),4); % weights each trial equally
zRcaData(:,:,:,condNum) = nanmean(zRcaDataAllSubj(:,:,:,:,condNum),4); % weights each trial equally
% compute projected amplitudes
realVector = permute(muRcaDataRealAllSubj(:,:,:,:,condNum),[4,1,2,3]);
imagVector = permute(muRcaDataImagAllSubj(:,:,:,:,condNum),[4,1,2,3]);
tempProject = vectorProjection(realVector,imagVector);
projectAmpAllSubj(:,:,:,:,condNum) = permute(tempProject,[2,3,4,1]);
end
% fit Naka Rushton on means for all conditions
if any(do_nr(:))
% don't include average in fits
fitData = sqrt(muRcaDataReal.^2+muRcaDataImag.^2);
fitNoise = repmat(nanmean(ampNoiseBins,4),[1,1,1,nConditions]); % use same noise across conditions
% [ NR_Params, NR_R2, NR_Range, NR_hModel ] = FitNakaRushton(binLabels, fitData, ampNoiseBins);
% [ NR_Params, NR_R2, NR_hModel ] = FitNakaRushtonFixed(binLabels, fitData,ampNoiseBins);
[ NR_Params, NR_R2, NR_hModel ] = FitNakaRushtonEq(binLabels, fitData(1:nBins,:,:,:));
% [ NR_Params, NR_R2, NR_hModel ] = FitNakaRushtonNoise(binLabels, fitData,fitNoise);
clear fitData;
else
end
if ~strcmp(error_type,'none')
for condNum = 1:nConditions
for rc=1:nCompFromInputData
for f=1:nFreqs
% do include averages when computing error bars
testReal = reshape(muRcaDataRealAllSubj(:,f,rc,:,condNum), [], nSubjects);
testImag = reshape(muRcaDataImagAllSubj(:,f,rc,:,condNum), [], nSubjects);
for b=1:nBins
xyData = [testReal(b,:)' testImag(b,:)'];
if size(xyData,1)<2
keyboard;
end
nanVals = sum(isnan(xyData),2)>0;
ampErrBins(b,f,rc,condNum,:) = fitErrorEllipse(xyData(~nanVals,:),error_type);
% compute t2-statistic against zero
tStruct = tSquaredFourierCoefs(xyData(~nanVals,:));
tPval(b,f,rc,condNum) = tStruct.pVal;
tSqrd(b,f,rc,condNum) = tStruct.tSqrd;
tSig(b,f,rc,condNum) = tStruct.H;
end
% do not include averages when computing fitting errors
testReal = squeeze(muRcaDataRealAllSubj(1:(nBins-1),f,rc,:,condNum));
testImag = squeeze(muRcaDataImagAllSubj(1:(nBins-1),f,rc,:,condNum));
testNoise = nanmean(reshape(ampNoiseBinsSubjects(1:(nBins-1),f,rc,:,:),[],nSubjects, nConditions),3);
if do_nr(f,rc,condNum)
for s = 1:size(testReal,2) % number of subjects, or subject x trials
sIdx = true(size(testReal,2),1);
sIdx(s) = false;
jkData(:,s) = sqrt( nanmean(testReal(:,sIdx),2).^2 + nanmean(testImag(:,sIdx),2).^2 );
jkNoise(:,s) = nanmean(testNoise(:,sIdx),2);
end
%jkParams = FitNakaRushton(binLabels, jkData,jkNoise);
jkParams = FitNakaRushtonEq(binLabels, jkData);
%jkParams = FitNakaRushtonNoise(binLabels, jkData,jkNoise);
NR_JK_SE(:,f,rc,condNum) = jackKnifeErr( jkParams' );
NR_JK_Params(:,:,f,rc,condNum) = jkParams;
clear jkParams; clear jkData;
else
end
end
end
end
else
end
% do averaging check
project_mean = permute(mean(projectAmpAllSubj,4),[1,2,3,5,4]);
real_imag_mean = sqrt(muRcaDataReal.^2+muRcaDataImag.^2);
assert(all(real_imag_mean(:) - project_mean(:) < 10^-14))
mean_data.real_signal = muRcaDataReal;
mean_data.imag_signal = muRcaDataImag;
mean_data.amp_signal = real_imag_mean;
% NEW: calculate phase with atan2 (four-quadrant inverse tangent)
% instead of atan (gives phase between + - pi/2 only)
% Old way: mean_data.phase_signal = atan(muRcaDataImag./muRcaDataReal);
mean_data.phase_signal = atan2(muRcaDataImag,muRcaDataReal);
mean_data.amp_noise = ampNoiseBins;
mean_data.z_snr = zRcaData;
rca_struct.mean = mean_data;
sub_data.amp_signal = sqrt(muRcaDataRealAllSubj.^2+muRcaDataImagAllSubj.^2);
sub_data.amp_noise = ampNoiseBinsSubjects;
sub_data.proj_amp_signal = projectAmpAllSubj;
sub_data.z_snr = zRcaDataAllSubj;
rca_struct.subjects = sub_data;
% Naka-Rushton output
stat_data.naka_rushton.Params = NR_Params;
stat_data.naka_rushton.R2 = NR_R2;
stat_data.naka_rushton.hModel = NR_hModel;
if ~strcmp(error_type,'none')
% error bins
stat_data.amp_lo_err = ampErrBins(:,:,:,:,1);
stat_data.amp_up_err = ampErrBins(:,:,:,:,2);
stat_data.err_type = error_type;
% regular old t-test on projected amplitudes
% one-tailed, would never be below zero
t_params = {'alpha',0.05,'dim',4,'tail','right'};
[stat_data.t_sig, stat_data.t_p, ci, sts] = ttest(rca_struct.subjects.proj_amp_signal,0,t_params{:});
stat_data.t_sig = reshape(stat_data.t_sig, nBins, nFreqs, nCompFromInputData, []);
stat_data.t_p = reshape(stat_data.t_p, nBins, nFreqs, nCompFromInputData, []);
stat_data.t_val = reshape(sts.tstat, nBins, nFreqs, nCompFromInputData, []);
% Hotelling's T2
stat_data.t2_sig = tSig;
stat_data.t2_p = tPval;
stat_data.t2_val = tSqrd;
% Naka-Rushton
stat_data.naka_rushton.JackKnife.SE = NR_JK_SE;
stat_data.naka_rushton.JackKnife.Params = NR_JK_Params;
end
rca_struct.stats = stat_data;
end
function outZ = computeZsnr(realVals,imagVals)
% move trial dimension to first
realVals = permute(realVals,[3,2,1]);
imagVals = permute(imagVals,[3,2,1]);
nReal = size( realVals );
nImag = size( imagVals );
if any(nReal ~= nImag)
error('real and imaginary values are not matched');
else
end
nSets = prod( nReal(2:end) );
outZ = nan( [1, nReal(2:end)]);
for z = 1:nSets
xyData = [realVals(:,z),imagVals(:,z)];
nanVals = sum(isnan(xyData),2)>0;
% use standard deviation, to compute the zSNR
if size( xyData(~nanVals,:) , 1 ) > 2
[ampErr,~,zSNR] = fitErrorEllipse(xyData(~nanVals,:),'1STD',false);
else
zSNR = NaN;
end
outZ(:,z) = zSNR;
end
% move trial dimension back to third
outZ = permute(outZ,[3,2,1]);
end
% function pSE = getParSE( pJK )
% % function from Spero for computing jack-knifed SEs for NR parameters
% nDim = ndims( pJK );
% nSubj = size( pJK, nDim );
% pSE = sqrt( ( nSubj - 1 ) / nSubj * sum( bsxfun( @minus, pJK, mean(pJK,nDim) ).^2, nDim ) );
% % p(:) = nSubj * p - ( nSubj - 1 ) * mean( pJK, nDim ); % unbiased estimate of mean. ???making things go negative???, bar graphs should match plot anyhow
% end
|
github
|
svndl/rcaBase-master
|
ssdTrain.m
|
.m
|
rcaBase-master/ssdCode/ssdTrain.m
| 2,021 |
utf_8
|
6d6a6d13589cfda218a1706e7866e3cd
|
% define the ssd function for our application based on signal and noise
% definitions in the fourier domain
function [Wsub, A, W, dGenSort, K] = ssdTrain(C_s, C_n, nComp, K)
% X_s: matrix containing the complex fourier coefficients at the frequency of interest extracted epoch-wise
% X_n2, X_n2: matrix containing the complex fourier coefficients at the neighbor bins of the frequency of interest at different epochs
% note that in this implementation, coefficients are only given for positive frequencies. parseval's theorem is met by
% considering coefficients at negative fequencies as the conjugates of coefficients at positive frequencies
% Soren:
% X_s, X_n1, X_n2: dimensions are [epochs x channels x frequencies]
% (i.e. [trials x channels x frequencies]).
assert(~any(~(size(C_s) == size(C_n))), 'X_s, X_n1, X_n2 should have the same dimensions.');
if (mean(abs(imag(C_s(:))))>10^-10 ) | (mean(abs(imag(C_n(:))))>10^-10 )
warning('something went wrong!')
end
if sum(isnan(C_s(:)))~=0 || sum(isnan(C_n(:)))~=0
warning('Covariance matrices contain NaNs: setting to zero...');
C_s(isnan(C_s))=0; C_n(isnan(C_n))=0;
end
C_s = real(C_s); % When tested, max(imag(C_s(:))) was in the order of e-17. It is discarded as a numerical artifact.
C_n = real(C_n);
% regurlarized based on covariance of signal
[Vpool,Dpool]=eig(C_s);
[dPool,sortIndx]=sort(diag(Dpool),'ascend');
Vpool=Vpool(:,sortIndx); % in case eigenvectors/eigenvalues not sorted
dPool=dPool(end-K:end);
Rw = C_n \ Vpool(:,end-K:end)*diag(dPool)*Vpool(:,end-K:end)';
[Vgen,Dgen]=eig(Rw); % compute generalized eigenvalues/eigenvectors
dGen=diag(Dgen);
[dGenSort,b]=sort(abs(dGen));
W=Vgen(:,b(end:-1:1)); % in case not sorted
if max(abs(imag(W))) > 10e-10
warning('W has imaginary part')
end
W=real(W); % ignore small imaginary component
Wsub=W(:,1:nComp); % return only selected number of components
A=C_s*Wsub / (Wsub'*C_s*Wsub); % return forward models (see Parra et al., 2005, Neuroimage)
end
|
github
|
h2oai/mxnet-master
|
parse_json.m
|
.m
|
mxnet-master/matlab/+mxnet/private/parse_json.m
| 19,095 |
utf_8
|
2d934e0eae2779e69f5c3883b8f89963
|
function data = parse_json(fname,varargin)
%PARSE_JSON parse a JSON (JavaScript Object Notation) file or string
%
% Based on jsonlab (https://github.com/fangq/jsonlab) created by Qianqian Fang. Jsonlab is lisonced under BSD or GPL v3.
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'^\s*(?:\[.+\])|(?:\{.+\})\s*$','once'))
string=fname;
elseif(exist(fname,'file'))
try
string = fileread(fname);
catch
try
string = urlread(['file://',fname]);
catch
string = urlread(['file://',fullfile(pwd,fname)]);
end
end
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
object.(valid_field(str))=val;
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=-1;
if(isfield(varargin{1},'progressbar_'))
pbar=varargin{1}.progressbar_;
end
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
pos=skip_whitespace(pos,inStr,len);
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function newpos=skip_whitespace(pos,inStr,len)
newpos=pos;
while newpos <= len && isspace(inStr(newpos))
newpos = newpos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str);
switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos);
keyboard;
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct
currstr=inStr(pos:min(pos+30,end));
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
if(isfield(varargin{1},'progressbar_'))
waitbar(pos/len,varargin{1}.progressbar_,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
function opt=varargin2struct(varargin)
%
% opt=varargin2struct('param1',value1,'param2',value2,...)
% or
% opt=varargin2struct(...,optstruct,...)
%
% convert a series of input parameters into a structure
%
% input:
% 'param', value: the input parameters should be pairs of a string and a value
% optstruct: if a parameter is a struct, the fields will be merged to the output struct
%
% output:
% opt: a struct where opt.param1=value1, opt.param2=value2 ...
%
len=length(varargin);
opt=struct;
if(len==0) return; end
i=1;
while(i<=len)
if(isstruct(varargin{i}))
opt=mergestruct(opt,varargin{i});
elseif(ischar(varargin{i}) && i<len)
opt=setfield(opt,lower(varargin{i}),varargin{i+1});
i=i+1;
else
error('input must be in the form of ...,''name'',value,... pairs or structs');
end
i=i+1;
end
function val=jsonopt(key,default,varargin)
%
% val=jsonopt(key,default,optstruct)
%
% setting options based on a struct. The struct can be produced
% by varargin2struct from a list of 'param','value' pairs
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
%
% $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $
%
% input:
% key: a string with which one look up a value from a struct
% default: if the key does not exist, return default
% optstruct: a struct where each sub-field is a key
%
% output:
% val: if key exists, val=optstruct.key; otherwise val=default
%
val=default;
if(nargin<=2) return; end
opt=varargin{1};
if(isstruct(opt))
if(isfield(opt,key))
val=getfield(opt,key);
elseif(isfield(opt,lower(key)))
val=getfield(opt,lower(key));
end
end
function s=mergestruct(s1,s2)
%
% s=mergestruct(s1,s2)
%
% merge two struct objects into one
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% date: 2012/12/22
%
% input:
% s1,s2: a struct object, s1 and s2 can not be arrays
%
% output:
% s: the merged struct object. fields in s1 and s2 will be combined in s.
if(~isstruct(s1) || ~isstruct(s2))
error('input parameters contain non-struct');
end
if(length(s1)>1 || length(s2)>1)
error('can not merge struct arrays');
end
fn=fieldnames(s2);
s=s1;
for i=1:length(fn)
s=setfield(s,fn{i},getfield(s2,fn{i}));
end
function newdata=struct2jdata(data,varargin)
%
% newdata=struct2jdata(data,opt,...)
%
% convert a JData object (in the form of a struct array) into an array
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
%
% input:
% data: a struct array. If data contains JData keywords in the first
% level children, these fields are parsed and regrouped into a
% data object (arrays, trees, graphs etc) based on JData
% specification. The JData keywords are
% "_ArrayType_", "_ArraySize_", "_ArrayData_"
% "_ArrayIsSparse_", "_ArrayIsComplex_"
% opt: (optional) a list of 'Param',value pairs for additional options
% The supported options include
% 'Recursive', if set to 1, will apply the conversion to
% every child; 0 to disable
%
% output:
% newdata: the covnerted data if the input data does contain a JData
% structure; otherwise, the same as the input.
%
% examples:
% obj=struct('_ArrayType_','double','_ArraySize_',[2 3],
% '_ArrayIsSparse_',1 ,'_ArrayData_',null);
% ubjdata=struct2jdata(obj);
fn=fieldnames(data);
newdata=data;
len=length(data);
if(jsonopt('Recursive',0,varargin{:})==1)
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
|
github
|
raalf/OPERA-master
|
alphavol.m
|
.m
|
OPERA-master/alphavol.m
| 6,537 |
utf_8
|
ef048ea526531f29fde44a729d4dd6a4
|
function [V,S] = alphavol(X,R,fig)
%ALPHAVOL Alpha shape of 2D or 3D point set.
% V = ALPHAVOL(X,R) gives the area or volume V of the basic alpha shape
% for a 2D or 3D point set. X is a coordinate matrix of size Nx2 or Nx3.
%
% R is the probe radius with default value R = Inf. In the default case
% the basic alpha shape (or alpha hull) is the convex hull.
%
% [V,S] = ALPHAVOL(X,R) outputs a structure S with fields:
% S.tri - Triangulation of the alpha shape (Mx3 or Mx4)
% S.vol - Area or volume of simplices in triangulation (Mx1)
% S.rcc - Circumradius of simplices in triangulation (Mx1)
% S.bnd - Boundary facets (Px2 or Px3)
%
% ALPHAVOL(X,R,1) plots the alpha shape.
%
% % 2D Example - C shape
% t = linspace(0.6,5.7,500)';
% X = 2*[cos(t),sin(t)] + rand(500,2);
% subplot(221), alphavol(X,inf,1);
% subplot(222), alphavol(X,1,1);
% subplot(223), alphavol(X,0.5,1);
% subplot(224), alphavol(X,0.2,1);
%
% % 3D Example - Sphere
% [x,y,z] = sphere;
% [V,S] = alphavol([x(:),y(:),z(:)]);
% trisurf(S.bnd,x,y,z,'FaceColor','blue','FaceAlpha',1)
% axis equal
%
% % 3D Example - Ring
% [x,y,z] = sphere;
% ii = abs(z) < 0.4;
% X = [x(ii),y(ii),z(ii)];
% X = [X; 0.8*X];
% subplot(211), alphavol(X,inf,1);
% subplot(212), alphavol(X,0.5,1);
%
% See also DELAUNAY, TRIREP, TRISURF
% Author: Jonas Lundgren <[email protected]> 2010
% 2010-09-27 First version of ALPHAVOL.
% 2010-10-05 DelaunayTri replaced by DELAUNAYN. 3D plots added.
% 2012-03-08 More output added. DELAUNAYN replaced by DELAUNAY.
if nargin < 2 || isempty(R), R = inf; end
if nargin < 3, fig = 0; end
% Check coordinates
dim = size(X,2);
if dim < 2 || dim > 3
error('alphavol:dimension','X must have 2 or 3 columns.')
end
% Check probe radius
if ~isscalar(R) || ~isreal(R) || isnan(R)
error('alphavol:radius','R must be a real number.')
end
% Unique points
[X,imap] = unique(X,'rows');
% Delaunay triangulation
T = delaunay(X);
% Remove zero volume tetrahedra since
% these can be of arbitrary large circumradius
if dim == 3
n = size(T,1);
vol = volumes(T,X);
epsvol = 1e-12*sum(vol)/n;
T = T(vol > epsvol,:);
holes = size(T,1) < n;
end
% Limit circumradius of simplices
[~,rcc] = circumcenters(TriRep(T,X));
T = T(rcc < R,:);
rcc = rcc(rcc < R);
% Volume/Area of alpha shape
vol = volumes(T,X);
V = sum(vol);
% Return?
if nargout < 2 && ~fig
return
end
% Turn off TriRep warning
warning('off','MATLAB:TriRep:PtsNotInTriWarnId')
% Alpha shape boundary
if ~isempty(T)
% Facets referenced by only one simplex
B = freeBoundary(TriRep(T,X));
if dim == 3 && holes
% The removal of zero volume tetrahedra causes false boundary
% faces in the interior of the volume. Take care of these.
B = trueboundary(B,X);
end
else
B = zeros(0,dim);
end
% Plot alpha shape
if fig
if dim == 2
% Plot boundary edges and point set
x = X(:,1);
y = X(:,2);
plot(x(B)',y(B)','r','linewidth',2), hold on
plot(x,y,'k.'), hold off
str = 'Area';
elseif ~isempty(B)
% Plot boundary faces
trisurf(TriRep(B,X),'FaceColor','red','FaceAlpha',1/3);
str = 'Volume';
else
cla
str = 'Volume';
end
axis equal
str = sprintf('Radius = %g, %s = %g',R,str,V);
title(str,'fontsize',12)
end
% Turn on TriRep warning
warning('on','MATLAB:TriRep:PtsNotInTriWarnId')
% Return structure
if nargout == 2
S = struct('tri',imap(T),'vol',vol,'rcc',rcc,'bnd',imap(B));
end
%--------------------------------------------------------------------------
function vol = volumes(T,X)
%VOLUMES Volumes/areas of tetrahedra/triangles
% Empty case
if isempty(T)
vol = zeros(0,1);
return
end
% Local coordinates
A = X(T(:,1),:);
B = X(T(:,2),:) - A;
C = X(T(:,3),:) - A;
if size(X,2) == 3
% 3D Volume
D = X(T(:,4),:) - A;
BxC = cross(B,C,2);
vol = dot(BxC,D,2);
vol = abs(vol)/6;
else
% 2D Area
vol = B(:,1).*C(:,2) - B(:,2).*C(:,1);
vol = abs(vol)/2;
end
%--------------------------------------------------------------------------
function B = trueboundary(B,X)
%TRUEBOUNDARY True boundary faces
% Remove false boundary caused by the removal of zero volume
% tetrahedra. The input B is the output of TriRep/freeBoundary.
% Surface triangulation
facerep = TriRep(B,X);
% Find edges attached to two coplanar faces
E0 = edges(facerep);
E1 = featureEdges(facerep, 1e-6);
E2 = setdiff(E0,E1,'rows');
% Nothing found
if isempty(E2)
return
end
% Get face pairs attached to these edges
% The edges connects faces into planar patches
facelist = edgeAttachments(facerep,E2);
pairs = cell2mat(facelist);
% Compute planar patches (connected regions of faces)
n = size(B,1);
C = sparse(pairs(:,1),pairs(:,2),1,n,n);
C = C + C' + speye(n);
[~,p,r] = dmperm(C);
% Count planar patches
iface = diff(r);
num = numel(iface);
% List faces and vertices in patches
facelist = cell(num,1);
vertlist = cell(num,1);
for k = 1:num
% Neglect singel face patches, they are true boundary
if iface(k) > 1
% List of faces in patch k
facelist{k} = p(r(k):r(k+1)-1);
% List of unique vertices in patch k
vk = B(facelist{k},:);
vk = sort(vk(:))';
ik = [true,diff(vk)>0];
vertlist{k} = vk(ik);
end
end
% Sort patches by number of vertices
ivert = cellfun(@numel,vertlist);
[ivert,isort] = sort(ivert);
facelist = facelist(isort);
vertlist = vertlist(isort);
% Group patches by number of vertices
p = [0;find(diff(ivert));num] + 1;
ipatch = diff(p);
% Initiate true boundary list
ibound = true(n,1);
% Loop over groups
for k = 1:numel(ipatch)
% Treat groups with at least two patches and four vertices
if ipatch(k) > 1 && ivert(p(k)) > 3
% Find double patches (identical vertex rows)
V = cell2mat(vertlist(p(k):p(k+1)-1));
[V,isort] = sortrows(V);
id = ~any(diff(V),2);
id = [id;0] | [0;id];
id(isort) = id;
% Deactivate faces in boundary list
for j = find(id')
ibound(facelist{j-1+p(k)}) = 0;
end
end
end
% Remove false faces
B = B(ibound,:);
|
github
|
raalf/OPERA-master
|
fcnSTLREAD.m
|
.m
|
OPERA-master/fcnSTLREAD.m
| 3,351 |
utf_8
|
2052a3e965c75c593c1432c122d7b11e
|
function [temp, isBinary] = fcnSTLREAD(stlfile)
%{
% fgetl(fp); % Skipping header line
% count = 1;
% while ~feof(fp)
% try
% % Skip "facet normal" words
% fscanf(fp,'%s',2);
%
% % Normal
% temp(count,:,4) = fscanf(fp,'%f',3);
% fgetl(fp); % Skip to new line
%
% % Skip "outer loop" line
% fgetl(fp);
%
% % Skip "vertex" words
% fscanf(fp,'%s',1);
%
% % Vertex 1 points
% temp(count,:,1) = fscanf(fp,'%f',3);
% fgetl(fp); % Skip to new line
%
% % Skip "vertex" words
% fscanf(fp,'%s',1);
%
% % Vertex 2 points
% temp(count,:,2) = fscanf(fp,'%f',3);
% fgetl(fp); % Skip to new line
%
% % Skip "vertex" words
% fscanf(fp,'%s',1);
%
% % Vertex 3 points
% temp(count,:,3) = fscanf(fp,'%f',3);
% fgetl(fp); % Skip to new line
%
% % Skip "endloop" line
% fgetl(fp);
%
% % Skip "endfacet" line
% fgetl(fp);
%
% count = count + 1;
% catch
% break;
% end
% end
% fclose(fp);
%}
if nargin == 0
warning('No STL-file is specified');
end
try
% Try to read an STL ASCII file
temp = stlAread(stlfile);
isBinary=false;
catch
try
% Try to read an STL binary file
temp = stlBread(stlfile);
isBinary=true;
catch
error('File could not be read!')
end
end
function temp = stlAread(stlfile)
% Reads an STL ASCII file
fid=fopen(stlfile,'r');
fileTitle=sscanf(fgetl(fid),'%*s %s');
vnum=0;
fclr=0;
testASCII=true;
lineCount=0;
while feof(fid) == 0
stlLine=fgetl(fid);
keyWord=sscanf(stlLine,'%s');
if strncmpi(keyWord,'c',1) == 1;
fclr = sscanf(stlLine,'%*s %f %f %f');
elseif strncmpi(keyWord,'v',1) == 1;
vnum = vnum+1;
vertex(:,vnum) = sscanf(stlLine,'%*s %f %f %f');
clr(:,vnum) = fclr;
elseif testASCII
lineCount=lineCount+1;
if lineCount>20
if vnum>2
testASCII=false;
else
error('File is not an STL ASCII file!')
end
end
end
end
temp(:,1:3,1) = [vertex(1,1:3:end)' vertex(2,1:3:end)' vertex(3,1:3:end)'];
temp(:,1:3,2) = [vertex(1,2:3:end)' vertex(2,2:3:end)' vertex(3,2:3:end)'];
temp(:,1:3,3) = [vertex(1,3:3:end)' vertex(2,3:3:end)' vertex(3,3:3:end)'];
fclose(fid);
function temp = stlBread(stlfile)
% Reads an STL binary file
fid = fopen(stlfile,'r');
fileTitle = fread(fid,80,'uchar=>schar');
fnum = fread(fid,1,'int32');
temp = zeros(fnum,3,3);
FVCD = uint8(zeros(3,fnum));
for i=1:fnum
% if mod(fnum/100, i) == 0
% perc = 100*(i/fnum);
% disp(perc);
% end
normal = fread(fid,3,'float32');
vertex1 = fread(fid,3,'float32');
vertex2 = fread(fid,3,'float32');
vertex3 = fread(fid,3,'float32');
clr = fread(fid,1,'uint16');
if bitget(clr,16) == 1
rd = bitshift(bitand(65535,clr),-10);
grn = bitshift(bitand(2047,clr),-5);
bl = bitand(63,clr);
FVCD(:,i) = [rd;grn;bl];
end
temp(i,1:3,1) = [vertex1(1) vertex1(2) vertex1(3)];
temp(i,1:3,2) = [vertex2(1) vertex2(2) vertex2(3)];
temp(i,1:3,3) = [vertex3(1) vertex3(2) vertex3(3)];
end
fclose(fid);
|
github
|
raalf/OPERA-master
|
fcnHINTEGRAL.m
|
.m
|
OPERA-master/Misc/Old Functions/fcnHINTEGRAL.m
| 1,538 |
utf_8
|
0cc0c334c7b28ec183a94d8b1f67a708
|
function [H00, H10, H01, H20, H11, H02] = fcnHINTEGRAL(a,h,l1,l2)
H00 = fcnH00(a,h,l2) - fcnH00(a,h,l1);
H10 = fcnH10(a,h,l2) - fcnH10(a,h,l1);
H01 = fcnH01(a,h,l2) - fcnH01(a,h,l1);
H20 = fcnH20(a,h,l2) - fcnH20(a,h,l1);
H11 = fcnH11(a,h,l2) - fcnH11(a,h,l1);
H02 = fcnH02(a,h,l2) - fcnH02(a,h,l1);
end
function out = fcnH00(a,h,l)
% out = (1./h).*atan((a.*l)./(a.^2 + h.^2 + h.*sqrt(l.^2 + a.^2 + h.^2)));
out = (1./h).*atan2((a.*l), (a.^2 + h.^2 + h.*sqrt(l.^2 + a.^2 + h.^2)));
end
function out = fcnH10(a,h,l)
out = (l./sqrt(l.^2 + a.^2)).*log(sqrt(l.^2 + a.^2 + h.^2) + sqrt(l.^2 + a.^2)) - log(l + sqrt(l.^2 + a.^2 + h.^2)) - ((l.*log(h))./(sqrt(l.^2 + a.^2)));
end
function out = fcnH01(a,h,l)
out = (a./sqrt(l.^2 + a.^2)).*(log(h) - log(sqrt(l.^2 + a.^2 + h.^2) + sqrt(l.^2 + a.^2)));
end
function out = fcnH20(a,h,l)
% out = ((a.*l.*(l.^2 + a.^2 + h.^2 - h.*sqrt(l.^2 + a.^2 + h.^2)))./((l.^2 + a.^2).*sqrt(l.^2 + a.^2 + h.^2))) - (h.*atan(l./a)) + h.*atan((h.*l)./(a.*sqrt(l.^2 + a.^2 + h.^2)));
out = ((a.*l.*(l.^2 + a.^2 + h.^2 - h.*sqrt(l.^2 + a.^2 + h.^2)))./((l.^2 + a.^2).*sqrt(l.^2 + a.^2 + h.^2))) - (h.*atan2(l,a)) + h.*atan2((h.*l),(a.*sqrt(l.^2 + a.^2 + h.^2)));
end
function out = fcnH11(a,h,l)
out = ((-a.^2).*(l.^2 + a.^2 + h.^2 - h.*sqrt(l.^2 + a.^2 + h.^2)))./((l.^2 + a.^2).*sqrt(l.^2 + a.^2 + h.^2));
end
function out = fcnH02(a,h,l)
% out = -h.*atan(l./a) + h.*atan((h.*l)./(a.*sqrt(l.^2 + a.^2 + h.^2)));
out = -h.*atan2(l, a) + h.*atan2((h.*l), (a.*sqrt(l.^2 + a.^2 + h.^2)));
end
|
github
|
gpeyre/2016-shannon-theory-master
|
load_image.m
|
.m
|
2016-shannon-theory-master/code/toolbox/load_image.m
| 20,275 |
utf_8
|
c700b54853577ab37402e27e4ca061b8
|
function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
if iscell(type)
for i=1:length(type)
M{i} = load_image(type{i},n,options);
end
return;
end
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = getoptions(options, 'eta', .1);
gamma = getoptions(options, 'gamma', 1/sqrt(2));
radius = getoptions(options, 'radius', 10);
center = getoptions(options, 'center', [0 0]);
center1 = getoptions(options, 'center1', [0 0]);
w = getoptions(options, 'tube_width', 0.06);
nb_points = getoptions(options, 'nb_points', 9);
scaling = getoptions(options, 'scaling', 1);
theta = getoptions(options, 'theta', 30 * 2*pi/360);
eccentricity = getoptions(options, 'eccentricity', 1.3);
sigma = getoptions(options, 'sigma', 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
if strcmp(type(1:min(12,end)), 'square-tube-')
k = str2double(type(13:end));
c1 = [.22 .5]; c2 = [1-c1(1) .5];
eta = 1.5;
r1 = [c1 c1] + .21*[-1 -eta 1 eta];
r2 = [c2 c2] + .21*[-1 -eta 1 eta];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
if mod(k,2)==0
sel = n/2-k/2+1:n/2+k/2;
else
sel = n/2-(k-1)/2:n/2+(k-1)/2;
end
M( round(.25*n:.75*n), sel ) = 1;
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case 'constant'
M = ones(n);
case 'ramp'
x = linspace(0,1,n);
[Y,M] = meshgrid(x,x);
case 'bump'
s = getoptions(options, 'bump_size', .5);
c = getoptions(options, 'center', [0 0]);
if length(s)==1
s = [s s];
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
X = (X-c(1))/s(1); Y = (Y-c(2))/s(2);
M = exp( -(X.^2+Y.^2)/2 );
case 'periodic'
x = linspace(-pi,pi,n)/1.1;
[Y,X] = meshgrid(x,x);
f = getoptions(options, 'freq', 6);
M = (1+cos(f*X)).*(1+cos(f*Y));
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
M = create_letter(type(8), radius, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.im = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
options.radius = 0.45;
options.center = [.5 .5];
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T-pi/2)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
f = getoptions(options, 'frequency', 30);
eta = getoptions(options, 'width', .3);
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
width = getoptions(options, 'width', round(n/16) );
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'geometrical'
J = getoptions(options, 'Jgeometrical', 4);
sgeom = 100*n/256;
options.bound = 'per';
A = ones(n);
for j=0:J-1
B = A;
for k=1:2^j
I = find(B==k);
U = perform_blurring(randn(n),sgeom,options);
s = median(U(I));
I1 = find( (B==k) & (U>s) );
I2 = find( (B==k) & (U<=s) );
A(I1) = 2*k-1;
A(I2) = 2*k;
end
end
M = A;
case 'lic-texture'
disp('Computing random tensor field.');
options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256);
T = compute_tensor_field_random(n,options);
Flow = perform_tensor_decomp(T); % extract eigenfield.
options.isoriented = 0; % no orientation in streamlines
% initial texture
lic_width = getoptions(options, 'lic_width', 0);
M0 = perform_blurring(randn(n),lic_width);
M0 = perform_histogram_equalization( M0, 'linear');
options.histogram = 'linear';
options.dt = 0.4;
options.M0 = M0;
options.verb = 1;
options.flow_correction = 1;
options.niter_lic = 3;
w = 30;
M = perform_lic(Flow, w, options);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'tv-image'
M = rand(n);
tau = compute_total_variation(M);
options.niter = 400;
[M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options);
M = perform_histogram_equalization(M,'linear');
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'line-windowed'
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
eta = .3;
gamma = getoptions(options, 'gamma', pi/10);
parabola = getoptions(options, 'parabola', 0);
M = (X-eta) - gamma*Y - parabola*Y.^2 < 0;
f = sin( pi*x ).^2;
M = M .* ( f'*f );
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
theta = getoptions(options, 'theta', .2);
freq = getoptions(options, 'freq', .2);
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'twodisks'
M = zeros(n);
options.center = [.25 .25];
M = load_image('disk', n, options);
options.center = [.75 .75];
M = M + load_image('disk', n, options);
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
alpha = getoptions(options, 'alpha', 1);
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
sigma = getoptions(options, 'sigma', 10);
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
c = getoptions(c, 'c', .1);
% angle
theta = getoptions(options, 'theta', pi/sqrt(2));
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
nbr_periods = getoptions(options, 'nbr_periods', 8);
theta = getoptions(options, 'theta', 1/sqrt(2));
skew = getoptions(options, 'skew', 1/sqrt(2) );
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
sigma = getoptions(options, 'sigma', 1);
M = randn(n) * sigma;
case 'disk-corner'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
rho = .3; eta = .1;
M1 = rho*X+eta<Y;
c = [0 .2]; r = .85;
d = (X-c(1)).^2 + (Y-c(2)).^2;
M2 = d<r^2;
M = M1.*M2;
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
if strcmp(type, 'peppers-bw')
M(:,1) = M(:,2);
M(1,:) = M(2,:);
end
if sigma>0
M = perform_blurring(M,sigma);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
M = perform_blurring(M,sigma);
end
M = rescale(M);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
github
|
gpeyre/2016-shannon-theory-master
|
plot_hufftree.m
|
.m
|
2016-shannon-theory-master/code/toolbox/plot_hufftree.m
| 869 |
utf_8
|
4e86eec0b29a5e46f1218e15a6318f5f
|
function plot_hufftree(T,offs)
% plot_hufftree - plot a huffman tree
%
% plot_hufftree(T);
%
% Copyright (c) 2008 Gabriel Peyre
if nargin<2
offs=0;
end
hold on;
plot_tree(T{1},[0,0],1, offs);
hold off;
axis tight;
axis off;
end
%%
function plot_tree(T,x,j, offs)
tw = 15;
lw = 1.5;
ms = 10;
if not(iscell(T))
de = [-.02 -.2];
% display a string
u = text(x(1)+de(1),x(2)+de(2),num2str(T+offs));
set(u,'FontSize',tw);
else
% display a split
h0 = 1/2^j;
h = 1 * h0;
u = plot( [x(1) x(1)-h], [x(2) x(2)-1], '.-' );
set(u,'MarkerSize',ms);
set(u,'LineWidth',lw);
u = plot( [x(1) x(1)+h], [x(2) x(2)-1], '.-' );
set(u,'MarkerSize',ms);
set(u,'LineWidth',lw);
plot_tree(T{1},[x(1)-h x(2)-1],j+1, offs);
plot_tree(T{2},[x(1)+h x(2)-1],j+1, offs);
end
end
|
github
|
gpeyre/2016-shannon-theory-master
|
perform_huffcoding.m
|
.m
|
2016-shannon-theory-master/code/toolbox/perform_huffcoding.m
| 1,491 |
utf_8
|
41a9144e1a2da192d37cf10a40add3e2
|
function y = perform_huffcoding(x,T,dir)
% perform_huffcoding - perform huffman coding
%
% y = perform_huffcoding(x,T,dir);
%
% dir=+1 for coding
% dir=-1 for decoding
%
% T is a Huffman tree, computed with compute_hufftree
%
% Copyright (c) 2008 Gabriel Peyre
if dir==1
%%% CODING %%%
C = huffman_gencode(T);
m = length(C);
x = round(x);
if min(x)<1 || max(x)>m
error('Too small or too large token');
end
y = [];
for i=1:length(x)
y = [y C{x(i)}];
end
else
%%% DE-CODING %%%
t = T{1};
y = [];
while not(isempty(x))
if x(1)==0
t = t{1};
else
t = t{2};
end
x(1) = [];
if not(iscell(t))
y = [y t];
t = T{1};
end
end
y = y(:);
end
%%
function C = huffman_gencode(T)
if not(iscell(T)) % || not(length(T)==2)
C = {};
C{T} = -1;
elseif length(T)==1
C = huffman_gencode(T{1});
% remove traling -1
for i=1:length(C)
C{i} = C{i}(1:end-1);
end
elseif length(T)==2
C1 = huffman_gencode(T{1});
C2 = huffman_gencode(T{2});
C = {};
for i=1:length(C1)
if not(isempty(C1{i}))
C{i} = [0 C1{i}];
end
end
for i=1:length(C2)
if not(isempty(C2{i}))
C{i} = [1 C2{i}];
end
end
else
error('Problem');
end
|
github
|
mowangphy/HOPE-CNN-master
|
cnn_cifar_hope.m
|
.m
|
HOPE-CNN-master/examples/cnn_cifar_hope.m
| 6,248 |
utf_8
|
7001f6382f537fb5735457262d9a42f5
|
function [net, info] = cnn_cifar_hope(varargin)
% ------------ CNN Cifar-10 ------------------------
% iFLYTEK Laboratory for Neural Computing and Machine Learning (iNCML) @ York University
% (https://wiki.eecs.yorku.ca/lab/MLL/start)
% Based on MatconvNet (http://www.vlfeat.org/matconvnet/)
% Coding by: Hengyue Pan ([email protected]), York University, Toronto
%
% If you hope to use this code, please cite:
% @article{pan2016learning,
% title={Learning Convolutional Neural Networks using Hybrid Orthogonal Projection and Estimation},
% author={Pan, Hengyue and Jiang, Hui},
% journal={arXiv preprint arXiv:1606.05929},
% year={2016}
% }
% License: MIT License
%
% Using HOPE model to improve the CNN performance
% Without data augmentation: 7.44% error rate on the validation set
run(fullfile(fileparts(mfilename('fullpath')), '../matlab/vl_setupnn.m')) ;
opts.modelType = 'HOPE' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.train.batchSize = 100 ;
opts.train.numEpochs = 400 ;
switch opts.modelType
case 'HOPE'
lr_schedule = zeros(1, opts.train.numEpochs);
beta_schedule = zeros(1, opts.train.numEpochs);
lr_init = 0.06;
beta_init = 0.15; % the learning rate of the orthogonal penalty term
for i = 1:opts.train.numEpochs
if (mod(i, 25) == 0)
lr_init = lr_init / 2;
beta_init = beta_init / 1.75;
end
lr_schedule(i) = lr_init;
beta_schedule(i) = beta_init;
end
opts.train.learningRate = lr_schedule;
opts.train.beta = beta_schedule;
opts.train.weightDecay = 0.0005 ;
otherwise
error('Unknown model type %s', opts.modelType) ;
end
opts.expDir = fullfile('data','cifar-hope') ; % output folder
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataDir = fullfile('data','cifar') ;
opts.dataClass = 0; % RGB: 0; YUV: 1
opts.whitenData = false ; % if whitening
opts.contrastNormalization = false ;
if (opts.dataClass == 0)
opts.imdbPath = '/eecs/research/asr/hengyue/DFT_DNN/Data/cifar/imdb_cifar.mat';
% imdb data structure:
% imdb.images.data: 32-by-32-by-3-by-60000 (all cifar data)
% imdb.images.labels: 1-by-60000 (all labels)
% imdb.images.set: 1-by-60000: if the ith image is an training sample, then imdb.images.set(i) = 1, otherwise imdb.images.set(i) = 3
else
opts.imdbPath = '/eecs/research/asr/hengyue/dataset/imdb_YUV_normalized.mat';
end
opts.train.continue = false ;
opts.train.gpus = 1 ;
opts.train.expDir = opts.expDir ;
opts.train.momentum = 0.9 ;
opts.train.isDropInput = 0;
opts.train.dropInputRate = 0.0;
opts.train.hopeMethod = 1; % 2, 1, 0
opts.train.isDataAug = 0; % we include rotation, scale, translation and color casting in the file cnn_train_hopefast
opts = vl_argparse(opts, varargin) ;
% --------------------------------------------------------------------
% Prepare data and model
% --------------------------------------------------------------------
switch opts.modelType
case 'HOPE', net = cnn_cifar_init_hope(opts) ;
end
if exist(opts.imdbPath, 'file')
load(opts.imdbPath) ;
if (opts.dataClass == 0)
dataMean = mean(imdb.images.data(:,:,:,1:50000), 4);
imdb.images.data = bsxfun(@minus, imdb.images.data, dataMean);
end
if opts.whitenData
z = reshape(imdb.images.data,[],60000) ;
sigma = z * transpose(z) / size(z, 2);%sigma is a n-by-n matrix
%%perform SVD
[U,S,V] = svd(sigma);
disp('Image processing using ZCAwhitening');
epsilon = 0.01;
z = U * diag(1./sqrt(diag(S) + epsilon)) * U' * z;
imdb.images.data = reshape(z, 32, 32, 3, []) ;
end
else
imdb = getCifarImdb(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
imdb.images.data = single(imdb.images.data);
[net, info] = cnn_train_hope(net, imdb, @getBatch, ...
opts.train, ...
'val', find(imdb.images.set == 3)) ;
valError = min(info.val.error(1, :));
fprintf('Minimum validation error is %.6g \n', valError);
% --------------------------------------------------------------------
function [im, labels] = getBatch(imdb, batch)
% --------------------------------------------------------------------
im = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
%if rand > 0.5, im=fliplr(im) ; end
% --------------------------------------------------------------------
function imdb = getCifarImdb(opts)
% --------------------------------------------------------------------
% Preapre the imdb structure, returns image data with mean image subtracted
unpackPath = fullfile(opts.dataDir, 'cifar-10-batches-mat');
files = [arrayfun(@(n) sprintf('data_batch_%d.mat', n), 1:5, 'UniformOutput', false) ...
{'test_batch.mat'}];
files = cellfun(@(fn) fullfile(unpackPath, fn), files, 'UniformOutput', false);
file_set = uint8([ones(1, 5), 3]);
if any(cellfun(@(fn) ~exist(fn, 'file'), files))
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz' ;
fprintf('downloading %s\n', url) ;
untar(url, opts.dataDir) ;
end
data = cell(1, numel(files));
labels = cell(1, numel(files));
sets = cell(1, numel(files));
for fi = 1:numel(files)
fd = load(files{fi}) ;
data{fi} = permute(reshape(fd.data',32,32,3,[]),[2 1 3 4]) ;
labels{fi} = fd.labels' + 1; % Index from 1
sets{fi} = repmat(file_set(fi), size(labels{fi}));
end
set = cat(2, sets{:});
data = single(cat(4, data{:}));
% remove mean in any case
dataMean = mean(data(:,:,:,set == 1), 4);
data = bsxfun(@minus, data, dataMean);
% normalize by image mean and std as suggested in `An Analysis of
% Single-Layer Networks in Unsupervised Feature Learning` Adam
% Coates, Honglak Lee, Andrew Y. Ng
if opts.contrastNormalization
z = reshape(data,[],60000) ;
z = bsxfun(@minus, z, mean(z,1)) ;
n = std(z,0,1) ;
z = bsxfun(@times, z, mean(n) ./ max(n, 40)) ;
data = reshape(z, 32, 32, 3, []) ;
end
clNames = load(fullfile(unpackPath, 'batches.meta.mat'));
imdb.images.data = data ;
imdb.images.labels = single(cat(2, labels{:})) ;
imdb.images.set = set;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = clNames.label_names;
|
github
|
mowangphy/HOPE-CNN-master
|
cnn_train_hope.m
|
.m
|
HOPE-CNN-master/examples/cnn_train_hope.m
| 20,562 |
utf_8
|
bd9dae5167b22459f3bf29a955c40bea
|
function [net, info] = cnn_train_hope(net, imdb, getBatch, varargin)
% CNN_TRAIN_HOPE: developed based on cnn_train in matconvnet (by Andrea Vedaldi)
% Do network training
% The hope training method is implemented in the function 'map_gradients'
% Data augmentation methods are implemented in the function 'process_epoch'
opts.batchSize = 100 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.numEpochs = 300 ;
opts.gpus = 1 ; % which GPU devices to use (none, one, or more)
opts.learningRate = 0.001 ;
opts.beta = 0.015;
opts.continue = false ;
opts.expDir = fullfile('data','exp') ;
opts.conserveMemory = true ;
opts.backPropDepth = +inf ;
opts.sync = false ;
opts.prefetch = false ;
opts.weightDecay = 0.0005 ;
opts.momentum = 0.9 ;
opts.momentum_hopefast = 0.9;
opts.errorFunction = 'multiclass' ;
opts.errorLabels = {} ;
opts.plotDiagnostics = false ;
opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;
opts.isDropInput = 1;
opts.dropInputRate = 0.1;
opts.hopeMethod = 1; % 0: original; 1: new matrix1; 2: new matrix2
opts.isDataAug = 1;
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isnan(opts.train), opts.train = [] ; end
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
evaluateMode = isempty(opts.train) ;
%save net.mat net;
if ~evaluateMode
for i=1:numel(net.layers)
if isfield(net.layers{i}, 'weights')
J = numel(net.layers{i}.weights) ;
for j=1:J
net.layers{i}.momentum{j} = zeros(size(net.layers{i}.weights{j}), 'single') ;
end
if ~isfield(net.layers{i}, 'learningRate')
net.layers{i}.learningRate = ones(1, J, 'single') ;
end
if ~isfield(net.layers{i}, 'weightDecay')
net.layers{i}.weightDecay = ones(1, J, 'single') ;
end
end
% Legacy code: will be removed
if isfield(net.layers{i}, 'filters')
net.layers{i}.momentum{1} = zeros(size(net.layers{i}.filters), 'single') ;
net.layers{i}.momentum{2} = zeros(size(net.layers{i}.biases), 'single') ;
if ~isfield(net.layers{i}, 'learningRate')
net.layers{i}.learningRate = ones(1, 2, 'single') ;
end
if ~isfield(net.layers{i}, 'weightDecay')
net.layers{i}.weightDecay = single([1 0]) ;
end
end
end
end
%save net2.mat net;
% setup GPUs
numGpus = numel(opts.gpus) ;
if numGpus > 1
if isempty(gcp('nocreate')),
parpool('local',numGpus) ;
spmd, gpuDevice(opts.gpus(labindex)), end
end
elseif numGpus == 1
gpuDevice(opts.gpus)
end
if exist(opts.memoryMapFile), delete(opts.memoryMapFile) ; end
%save net3.mat net;
% setup error calculation function
if isstr(opts.errorFunction)
switch opts.errorFunction
case 'none'
opts.errorFunction = @error_none ;
case 'multiclass'
opts.errorFunction = @error_multiclass ;
if isempty(opts.errorLabels), opts.errorLabels = {'top1e', 'top5e'} ; end
case 'binary'
opts.errorFunction = @error_binary ;
if isempty(opts.errorLabels), opts.errorLabels = {'bine'} ; end
otherwise
error('Uknown error function ''%s''', opts.errorFunction) ;
end
end
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
all_corr_collection = [];
for epoch=1:opts.numEpochs
learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
beta = opts.beta(min(epoch, numel(opts.beta))) ;
% fast-forward to last checkpoint
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
if opts.continue
if exist(modelPath(epoch),'file')
if epoch == opts.numEpochs
load(modelPath(epoch), 'net', 'info') ;
end
continue ;
end
if epoch > 1
fprintf('resuming by loading epoch %d\n', epoch-1) ;
load(modelPath(epoch-1), 'net', 'info') ;
end
end
% move CNN to GPU as needed
if numGpus == 1
net = vl_simplenn_move(net, 'gpu') ;
elseif numGpus > 1
spmd(numGpus)
net_ = vl_simplenn_move(net, 'gpu') ;
end
end
% train one epoch and validate
train = opts.train(randperm(numel(opts.train))) ; % shuffle
val = opts.val ;
if numGpus <= 1
[net,stats.train,all_corr] = process_epoch(opts, getBatch, epoch, train, learningRate, beta, imdb, net) ;
[~,stats.val] = process_epoch(opts, getBatch, epoch, val, 0, 0, imdb, net) ;
else
spmd(numGpus)
[net_, stats_train_,all_corr] = process_epoch(opts, getBatch, epoch, train, learningRate, beta, imdb, net_) ;
[~, stats_val_] = process_epoch(opts, getBatch, epoch, val, 0, 0, imdb, net_) ;
end
stats.train = sum([stats_train_{:}],2) ;
stats.val = sum([stats_val_{:}],2) ;
end
all_corr_collection = [all_corr_collection, all_corr];
% save
if evaluateMode, sets = {'val'} ; else sets = {'train', 'val'} ; end
for f = sets
f = char(f) ;
n = numel(eval(f)) ;
info.(f).speed(epoch) = n / stats.(f)(1) ;
info.(f).objective(epoch) = stats.(f)(2) / n ;
info.(f).error(:,epoch) = stats.(f)(3:end) / n ;
end
if numGpus > 1
spmd(numGpus)
net_ = vl_simplenn_move(net_, 'cpu') ;
end
net = net_{1} ;
else
net = vl_simplenn_move(net, 'cpu') ;
end
if ~evaluateMode
if (mod(epoch, 100) == 0)
save(modelPath(epoch), 'net', 'info') ;
end
end
figure(1) ; clf ;
hasError = isa(opts.errorFunction, 'function_handle') ;
hasHOPE = 1;
subplot(1,1+hasError+hasHOPE,1) ;
if ~evaluateMode
plot(1:epoch, info.train.objective, '.-', 'linewidth', 2) ;
hold on ;
end
plot(1:epoch, info.val.objective, '.--') ;
xlabel('training epoch') ; ylabel('energy') ;
grid on ;
h=legend(sets) ;
set(h,'color','none');
title('objective') ;
if hasError
subplot(1,2+hasHOPE,2) ; leg = {} ;
if ~evaluateMode
plot(1:epoch, info.train.error', '.-', 'linewidth', 2) ;
hold on ;
leg = horzcat(leg, strcat('train ', opts.errorLabels)) ;
end
plot(1:epoch, info.val.error', '.--') ;
leg = horzcat(leg, strcat('val ', opts.errorLabels)) ;
set(legend(leg{:}),'color','none') ;
grid on ;
xlabel('training epoch') ; ylabel('error') ;
title('error') ;
end
if hasHOPE
subplot(1,3,3) ; leg = {} ;
nHOPE = size(all_corr_collection, 1);
if ~evaluateMode
for iHOPE = 1:nHOPE
plot(1:epoch, all_corr_collection(iHOPE, :), '.-', 'linewidth', 2) ;
hold on ;
leg = horzcat(leg, strcat('HOPE ', iHOPE)) ;
end
end
set(legend(leg{:}),'color','none') ;
grid on ;
xlabel('training epoch') ; ylabel('Correlation') ;
title('Correlation') ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
% -------------------------------------------------------------------------
function err = error_multiclass(opts, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
[~,predictions] = sort(predictions, 3, 'descend') ;
error = ~bsxfun(@eq, predictions, reshape(labels, 1, 1, 1, [])) ;
err(1,1) = sum(sum(sum(error(:,:,1,:)))) ;
err(2,1) = sum(sum(sum(min(error(:,:,1:5,:),[],3)))) ;
% -------------------------------------------------------------------------
function err = error_binaryclass(opts, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
error = bsxfun(@times, predictions, labels) < 0 ;
err = sum(error(:)) ;
% -------------------------------------------------------------------------
function err = error_none(opts, labels, res)
% -------------------------------------------------------------------------
err = zeros(0,1) ;
% -------------------------------------------------------------------------
function [net,stats,all_corr,prof] = process_epoch(opts, getBatch, epoch, subset, learningRate, beta, imdb, net)
% -------------------------------------------------------------------------
% validation mode if learning rate is zero
training = learningRate > 0 ;
if training, mode = 'training' ; else, mode = 'validation' ; end
if nargout > 3, mpiprofile on ; end
numGpus = numel(opts.gpus) ;
if numGpus >= 1
one = gpuArray(single(1)) ;
else
one = single(1) ;
end
res = [] ;
mmap = [] ;
stats = [] ;
top_1_Error_collection = zeros(1, 2);
for t=1:opts.batchSize:numel(subset)
fprintf('%s: epoch %02d: batch %3d/%3d: ', mode, epoch, ...
fix(t/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize)) ;
batchSize = min(opts.batchSize, numel(subset) - t + 1) ;
batchTime = tic ;
numDone = 0 ;
error = [] ;
for s=1:opts.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+opts.batchSize-1, numel(subset)) ;
batch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;
[im, labels] = getBatch(imdb, batch) ;
if opts.prefetch
if s==opts.numSubBatches
batchStart = t + (labindex-1) + opts.batchSize ;
batchEnd = min(t+2*opts.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;
getBatch(imdb, nextBatch) ;
end
% Do horizontal flip for 50% images
if training
if opts.isDataAug % && (epoch < (opts.numEpochs-100) )
fprintf('Do image augmentation (rotation+translation+scale+colorspace)... ');
[H0, W0, C0, N0] = size(im);
randIdx = randperm(N0); % translation
randIdx2 = randperm(N0); % rotate
randIdx3 = randperm(N0); % scale
randIdx4 = randperm(N0); % RGB casting
for iN = 1:N0
if (randIdx(iN) <= (N0/2))
transRangeX = (rand(1) - 0.5) * 10;
transRangeY = (rand(1) - 0.5) * 10;
im(:, :, :, iN) = imtranslate(im(:, :, :, iN),[transRangeX, transRangeY]);
end
if (randIdx2(iN) <= (N0/2))
angle = (rand(1) - 0.5) * 10; % -5 ~ 5
im(:, :, :, iN) = imrotate( im(:, :, :, iN), angle, 'bilinear', 'crop' );
end
if (randIdx3(iN) <= (N0/2))
xmin = randperm(4);
ymin = randperm(4);
width = randperm(4) + 24;
height = randperm(4) + 24;
tmpIm = imcrop(im(:, :, :, iN), [xmin(1), ymin(1), width(1), height(1)]);
im(:, :, :, iN) = imresize(tmpIm, [32, 32]);
end
if (randIdx4(iN) <= (N0/2))
tagR = rand(1);
tagG = rand(1);
tagB = rand(1);
% [H0, W0, C0, N0] = size(im);
maskRGB = ( rand(H0, W0, C0, N0)*0.1 - 0.05 ) + 1;% 0-1 -> 0.95-1.05
if (tagR < 0.5)
im(:, :, 1, iN) = im(:, :, 1, iN) .* maskRGB(:, :, 1, iN);
end
if (tagG < 0.5)
im(:, :, 2, iN) = im(:, :, 2, iN) .* maskRGB(:, :, 2, iN);
end
if (tagB < 0.5)
im(:, :, 3, iN) = im(:, :, 3, iN) .* maskRGB(:, :, 3, iN);
end
end
end
fprintf('Done ... \n');
end
end
if opts.isDropInput
if training
fprintf('Do drop input ');
[H, W, C, N] = size(im);
mask = single(rand(H, W) >= opts.dropInputRate) ;
im = bsxfun(@times, im, mask);
else
% im = im * (1 - opts.dropInputRate);
end
end
if numGpus >= 1
im = gpuArray(im) ;
end
% evaluate CNN
net.layers{end}.class = labels ;
if training, dzdy = one; else, dzdy = [] ; end
%'accumulate', s~=1, ...
res = vl_simplenn(net, im, dzdy, res, ...
'accumulate', 0, ...
'disableDropout', ~training, ...
'conserveMemory', opts.conserveMemory, ...
'backPropDepth', opts.backPropDepth, ...
'sync', opts.sync) ;
% accumulate training errors
error = sum([error, [...
sum(double(gather(res(end).x))) ;
reshape(opts.errorFunction(opts, labels, res),[],1) ; ]],2) ;
numDone = numDone + numel(batch) ;
end
% gather and accumulate gradients across labs
all_corr = 0;
if training
if numGpus <= 1
[net, all_corr] = accumulate_gradients(opts, learningRate, beta, batchSize, net, res) ;
else
if isempty(mmap)
mmap = map_gradients(opts.memoryMapFile, net, res, numGpus) ;
end
write_gradients(mmap, net, res) ;
labBarrier() ;
[net, all_corr, res] = accumulate_gradients(opts, learningRate, beta, batchSize, net, res, mmap) ;
end
end
% print learning statistics
batchTime = toc(batchTime) ;
stats = sum([stats,[batchTime ; error]],2); % works even when stats=[]
speed = batchSize/batchTime ;
fprintf(' %.2f s (%.1f data/s)', batchTime, speed) ;
n = (t + batchSize - 1) / max(1,numlabs) ;
fprintf(' obj:%.6g', stats(2)/n) ;
for i=1:numel(opts.errorLabels)
fprintf(' %s:%.3g', opts.errorLabels{i}, stats(i+2)/n) ;
top_1_Error_collection(i) = top_1_Error_collection(i) + stats(i+2)/n;
end
fprintf(' [%d/%d]', numDone, batchSize);
fprintf('\n') ;
% debug info
if opts.plotDiagnostics && numGpus <= 1
figure(2) ; vl_simplenn_diagnose(net,res) ; drawnow ;
end
end
top_1_Error_collection = top_1_Error_collection ./ numel(subset);
top_1_Error_collection = top_1_Error_collection .* opts.batchSize;
fprintf(' Overall top-1 Error: %.6g, overall top-5 Error: %.6g \n', top_1_Error_collection(1), top_1_Error_collection(2)) ;
if nargout > 3
prof = mpiprofile('info');
mpiprofile off ;
end
% -------------------------------------------------------------------------
function [net,all_corr,res] = accumulate_gradients(opts, lr, beta, batchSize, net, res, mmap)
% -------------------------------------------------------------------------
nHOPE = 0;
all_corr = [];
for l=1:numel(net.layers)
for j=1:numel(res(l).dzdw)
if nargin >= 7
tag = sprintf('l%d_%d',l,j) ;
tmp = zeros(size(mmap.Data(labindex).(tag)), 'single') ;
for g = setdiff(1:numel(mmap.Data), labindex)
tmp = tmp + mmap.Data(g).(tag) ;
end
res(l).dzdw{j} = res(l).dzdw{j} + tmp ;
end
end
if isfield(net.layers{l}, 'weights')
thisDecay(1) = opts.weightDecay * net.layers{l}.weightDecay(1) ;
thisLR(1) = lr * net.layers{l}.learningRate(1) ;
thisDecay(2) = opts.weightDecay * net.layers{l}.weightDecay(2) ;
thisLR(2) = lr * net.layers{l}.learningRate(2) ;
if ( strcmp(net.layers{l}.type, 'hope_fast') )
nHOPE = nHOPE + 1;
if (opts.hopeMethod == 0) % slow
L2_W = sqrt(sum(net.layers{l}.weights{1}.^2, 1)); %[1, W, C_in, C_out]
%df_D = zeros(H, W, C_in, C_out, 'single');
%df_D = gpuArray(df_D);
for i2 = 1:net.layers{l}.C_in
for j2 = 1:net.layers{l}.C_out
weight = net.layers{l}.weights{1}(:, :, i2, j2);% can be optimized
% L2_W_S = L2_W_Square(:, :, i2, j2);
L2_W_sub = L2_W(:, :, i2, j2);
L2_W_S = transpose(L2_W_sub)*L2_W_sub;
C_matrix = transpose(weight) * weight;
G_matrix = C_matrix./L2_W_S;
B = sign(C_matrix)./L2_W_S;
% df_D(:, :, i2, j2) = weight*B - (weight./repmat(L2_W_sub.^2,[size(weight,1),1]))* diag(sum(G_matrix,1));
net.layers{l}.df_D(:, :, i2, j2) = weight*B - (bsxfun(@rdivide, weight, L2_W_sub.^2))* diag(sum(G_matrix,1));
end
end
elseif (opts.hopeMethod == 1) % this method that mentioned in our paper
weight = reshape(net.layers{l}.weights{1}, [], net.layers{l}.C_out);
L2_W = sqrt(sum(weight.^2, 1)); %[1, C_out]
L2_W_S = transpose(L2_W)*L2_W; % C_out * C_out
C_matrix = transpose(weight) * weight; % C_out * C_out
G_matrix = C_matrix./L2_W_S;
B = sign(C_matrix)./L2_W_S;
net.layers{l}.df_D = weight*B - (bsxfun(@rdivide, weight, L2_W.^2))* diag(sum(G_matrix,1));
net.layers{l}.df_D = reshape(net.layers{l}.df_D, net.layers{l}.H, net.layers{l}.W, net.layers{l}.C_in, net.layers{l}.C_out);
else
for i = 1:net.layers{l}.C_out
weight = net.layers{l}.weights{1}(:, :, :, i);% can be optimized
weight = reshape(weight, [], 1);
L2_W = sqrt(sum(weight.^2, 1));
L2_W_S = transpose(L2_W)*L2_W;
C_matrix = transpose(weight) * weight;
G_matrix = C_matrix./L2_W_S;
B = sign(C_matrix)./L2_W_S;
df_D0 = weight*B - (bsxfun(@rdivide, weight, L2_W.^2))* diag(sum(G_matrix,1));
net.layers{l}.df_D(:, :, :, i) = reshape(df_D0, net.layers{l}.H, net.layers{l}.W, net.layers{l}.C_in, 1);
end
end
res(l).dzdw{1} = res(l).dzdw{1} + beta .* net.layers{l}.df_D;
net.layers{l}.momentum{1} = ...
opts.momentum_hopefast * net.layers{l}.momentum{1} ...
- thisLR(1) * thisDecay(1) * net.layers{l}.weights{1} ...
- thisLR(1) * (1 / batchSize) * res(l).dzdw{1} ;
net.layers{l}.weights{1} = net.layers{l}.weights{1} + net.layers{l}.momentum{1} ;
if (opts.hopeMethod == 0)
%[H, W, C_in, C_out] = size(net.layers{l}.weights{1});
L2_W = sqrt(sum(net.layers{l}.weights{1}.^2,1));%[1, W, C_in, C_out]
net.layers{l}.weights{1} = bsxfun(@rdivide, net.layers{l}.weights{1}, L2_W);
correlation = sum(sum(abs(transpose(net.layers{l}.weights{1}(:, :, 1, 1) )*net.layers{l}.weights{1}(:, :, 1, 1) ),1),2)-size(net.layers{l}.weights{1}(:, :, 1, 1),2);
elseif (opts.hopeMethod == 1)
weight = reshape(net.layers{l}.weights{1}, [], net.layers{l}.C_out);
L2_W = sqrt(sum(weight.^2, 1)); %[1, C_out]
weight = bsxfun(@rdivide, weight, L2_W);
net.layers{l}.weights{1} = reshape(weight, net.layers{l}.H, net.layers{l}.W, net.layers{l}.C_in, net.layers{l}.C_out);
correlation = sum(sum(abs(transpose(weight)*weight),1),2)-net.layers{l}.C_out;
else
L2_W = sqrt(sum(net.layers{l}.weights{1}.^2,1));%[1, W, C_in, C_out]
net.layers{l}.weights{1} = bsxfun(@rdivide, net.layers{l}.weights{1}, L2_W);
weight2 = net.layers{l}.weights{1}(:, :, :, 1);
weight2 = reshape(weight2, [], 1);
correlation = sum(sum(abs(transpose(weight2)*weight2),1),2)-1;
end
fprintf(' corr %.4f, hopeMethod %d ', correlation, opts.hopeMethod);
all_corr(nHOPE, 1) = gather(correlation);
% clear L2_W;
end
if ( strcmp(net.layers{l}.type, 'conv') )
net.layers{l}.momentum{1} = ...
opts.momentum * net.layers{l}.momentum{1} ...
- thisLR(1) * thisDecay(1) * net.layers{l}.weights{1} ...
- thisLR(1) * (1 / batchSize) * res(l).dzdw{1} ;
net.layers{l}.weights{1} = net.layers{l}.weights{1} + net.layers{l}.momentum{1} ;
net.layers{l}.momentum{2} = ...
opts.momentum * net.layers{l}.momentum{2} ...
- thisLR(2) * thisDecay(2) * net.layers{l}.weights{2} ...
- thisLR(2) * (1 / batchSize) * res(l).dzdw{2} ;
net.layers{l}.weights{2} = net.layers{l}.weights{2} + net.layers{l}.momentum{2} ;
end
if ( strcmp(net.layers{l}.type, 'bnorm') )
net.layers{l}.momentum{1} = ...
opts.momentum * net.layers{l}.momentum{1} ...
- thisLR(1) * thisDecay(1) * net.layers{l}.weights{1} ...
- thisLR(1) * (1 / batchSize) * res(l).dzdw{1} ;
net.layers{l}.weights{1} = net.layers{l}.weights{1} + net.layers{l}.momentum{1} ;
net.layers{l}.momentum{2} = ...
opts.momentum * net.layers{l}.momentum{2} ...
- thisLR(2) * thisDecay(2) * net.layers{l}.weights{2} ...
- thisLR(2) * (1 / batchSize) * res(l).dzdw{2} ;
net.layers{l}.weights{2} = net.layers{l}.weights{2} + net.layers{l}.momentum{2} ;
end
end
%end
end
% -------------------------------------------------------------------------
function mmap = map_gradients(fname, net, res, numGpus)
% -------------------------------------------------------------------------
format = {} ;
for i=1:numel(net.layers)
for j=1:numel(res(i).dzdw)
format(end+1,1:3) = {'single', size(res(i).dzdw{j}), sprintf('l%d_%d',i,j)} ;
end
end
format(end+1,1:3) = {'double', [3 1], 'errors'} ;
if ~exist(fname) && (labindex == 1)
f = fopen(fname,'wb') ;
for g=1:numGpus
for i=1:size(format,1)
fwrite(f,zeros(format{i,2},format{i,1}),format{i,1}) ;
end
end
fclose(f) ;
end
labBarrier() ;
mmap = memmapfile(fname, 'Format', format, 'Repeat', numGpus, 'Writable', true) ;
% -------------------------------------------------------------------------
function write_gradients(mmap, net, res)
% -------------------------------------------------------------------------
for i=1:numel(net.layers)
for j=1:numel(res(i).dzdw)
mmap.Data(labindex).(sprintf('l%d_%d',i,j)) = gather(res(i).dzdw{j}) ;
end
end
|
github
|
mowangphy/HOPE-CNN-master
|
vl_argparse.m
|
.m
|
HOPE-CNN-master/matlab/vl_argparse.m
| 3,148 |
utf_8
|
74459d2b851e027208bd7ca9ea999037
|
function [opts, args] = vl_argparse(opts, args)
% VL_ARGPARSE Parse list of parameter-value pairs
% OPTS = VL_ARGPARSE(OPTS, ARGS) updates the structure OPTS based on
% the specified parameter-value pairs ARGS={PAR1, VAL1, ... PARN,
% VALN}. The function produces an error if an unknown parameter name
% is passed on. Values that are structures are copied recursively.
%
% Any of the PAR, VAL pairs can be replaced by a structure; in this
% case, the fields of the structure are used as paramaters and the
% field values as values.
%
% [OPTS, ARGS] = VL_ARGPARSE(OPTS, ARGS) copies any parameter in
% ARGS that does not match OPTS back to ARGS instead of producing an
% error. Options specified as structures are expaned back to PAR,
% VAL pairs.
%
% Example::
% The function can be used to parse a list of arguments
% passed to a MATLAB functions:
%
% function myFunction(x,y,z,varargin)
% opts.parameterName = defaultValue ;
% opts = vl_argparse(opts, varargin)
%
% If only a subset of the options should be parsed, for example
% because the other options are interpreted by a subroutine, then
% use the form
%
% [opts, varargin] = vl_argparse(opts, varargin)
%
% that copies back to VARARGIN any unknown parameter.
%
% See also: VL_HELP().
% Authors: Andrea Vedaldi
% Copyright (C) 2015 Andrea Vedaldi.
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if ~isstruct(opts), error('OPTS must be a structure') ; end
if ~iscell(args), args = {args} ; end
% convert ARGS into a structure
ai = 1 ;
params = {} ;
values = {} ;
while ai <= length(args)
if isstr(args{ai})
params{end+1} = args{ai} ; ai = ai + 1 ;
values{end+1} = args{ai} ; ai = ai + 1 ;
elseif isstruct(args{ai}) ;
params = horzcat(params, fieldnames(args{ai})') ;
values = horzcat(values, struct2cell(args{ai})') ;
ai = ai + 1 ;
else
error('Expected either a param-value pair or a structure') ;
end
end
args = {} ;
% copy parameters in the opts structure, recursively
for i = 1:numel(params)
field = params{i} ;
if ~isfield(opts, field)
field = findfield(opts, field) ;
end
if ~isempty(field)
if isstruct(values{i})
if ~isstruct(opts.(field))
error('The value of parameter %d is a structure in the arguments but not a structure in OPT.',field) ;
end
if nargout > 1
[opts.(field), rest] = vl_argparse(opts.(field), values{i}) ;
args = horzcat(args, {field, cell2struct(rest(2:2:end), rest(1:2:end), 2)}) ;
else
opts.(field) = vl_argparse(opts.(field), values{i}) ;
end
else
opts.(field) = values{i} ;
end
else
if nargout <= 1
error('Uknown parameter ''%s''', params{i}) ;
else
args = horzcat(args, {params{i}, values{i}}) ;
end
end
end
function field = findfield(opts, field)
fields=fieldnames(opts) ;
i=find(strcmpi(fields, field)) ;
if ~isempty(i)
field=fields{i} ;
else
field=[] ;
end
|
github
|
mowangphy/HOPE-CNN-master
|
vl_compilenn.m
|
.m
|
HOPE-CNN-master/matlab/vl_compilenn.m
| 24,645 |
utf_8
|
8ffdf03179d5108a10b46a7fee6410e9
|
function vl_compilenn( varargin )
% VL_COMPILENN Compile the MatConvNet toolbox
% The `vl_compilenn()` function compiles the MEX files in the
% MatConvNet toolbox. See below for the requirements for compiling
% CPU and GPU code, respectively.
%
% `vl_compilenn('OPTION', ARG, ...)` accepts the following options:
%
% `EnableGpu`:: `false`
% Set to true in order to enable GPU support.
%
% `Verbose`:: 0
% Set the verbosity level (0, 1 or 2).
%
% `Debug`:: `false`
% Set to true to compile the binaries with debugging
% information.
%
% `CudaMethod`:: Linux & Mac OS X: `mex`; Windows: `nvcc`
% Choose the method used to compile the CUDA code. There are two
% methods:
%
% * The **`mex`** method uses the MATLAB MEX command with the
% configuration file
% `<MatConvNet>/matlab/src/config/mex_CUDA_<arch>.[sh/xml]`
% This configuration file is in XML format since MATLAB 8.3
% (R2014a) and is a Shell script for earlier versions. This
% is, principle, the preferred method as it uses the
% MATLAB-sanctioned compiler options.
%
% * The **`nvcc`** method calls the NVIDIA CUDA compiler `nvcc`
% directly to compile CUDA source code into object files.
%
% This method allows to use a CUDA toolkit version that is not
% the one that officially supported by a particular MATALB
% version (see below). It is also the default method for
% compilation under Windows and with CuDNN.
%
% `CudaRoot`:: guessed automatically
% This option specifies the path to the CUDA toolkit to use for
% compilation.
%
% `EnableImreadJpeg`:: `true`
% Set this option to `true` to compile `vl_imreadjpeg`.
%
% `ImageLibrary`:: `libjpeg` (Linux), `gdiplus` (Windows), `quartz` (Mac)
% The image library to use for `vl_impreadjpeg`.
%
% `ImageLibraryCompileFlags`:: platform dependent
% A cell-array of additional flags to use when compiling
% `vl_imreadjpeg`.
%
% `ImageLibraryLinkFlags`:: platform dependent
% A cell-array of additional flags to use when linking
% `vl_imreadjpeg`.
%
% `EnableCudnn`:: `false`
% Set to `true` to compile CuDNN support.
%
% `CudnnRoot`:: `'local/'`
% Directory containing the unpacked binaries and header files of
% the CuDNN library.
%
% ## Compiling the CPU code
%
% By default, the `EnableGpu` option is switched to off, such that
% the GPU code support is not compiled in.
%
% Generally, you only need a C/C++ compiler (usually Xcode, GCC or
% Visual Studio for Mac, Linux, and Windows respectively). The
% compiler can be setup in MATLAB using the
%
% mex -setup
%
% command.
%
% ## Compiling the GPU code
%
% In order to compile the GPU code, set the `EnableGpu` option to
% `true`. For this to work you will need:
%
% * To satisfy all the requirement to compile the CPU code (see
% above).
%
% * A NVIDIA GPU with at least *compute capability 2.0*.
%
% * The *MATALB Parallel Computing Toolbox*. This can be purchased
% from Mathworks (type `ver` in MATLAB to see if this toolbox is
% already comprised in your MATLAB installation; it often is).
%
% * A copy of the *CUDA Devkit*, which can be downloaded for free
% from NVIDIA. Note that each MATLAB version requires a
% particular CUDA Devkit version:
%
% | MATLAB version | Release | CUDA Devkit |
% |----------------|---------|-------------|
% | 2013b | 2013b | 5.5 |
% | 2014a | 2014a | 5.5 |
% | 2014b | 2014b | 6.0 |
%
% A different versions of CUDA may work using the hack described
% above (i.e. setting the `CudaMethod` to `nvcc`).
%
% The following configurations have been tested successfully:
%
% * Windows 7 x64, MATLAB R2014a, Visual C++ 2010 and CUDA Toolkit
% 6.5 (unable to compile with Visual C++ 2013).
% * Windows 8 x64, MATLAB R2014a, Visual C++ 2013 and CUDA
% Toolkit 6.5.
% * Mac OS X 10.9 and 10.10, MATLAB R2013a and R2013b, Xcode, CUDA
% Toolkit 5.5.
% * GNU/Linux, MATALB R2014a, gcc, CUDA Toolkit 5.5.
%
% Furthermore your GPU card must have ComputeCapability >= 2.0 (see
% output of `gpuDevice()`) in order to be able to run the GPU code.
% To change the compute capabilities, for `mex` `CudaMethod` edit
% the particular config file. For the 'nvcc' method, compute
% capability is guessed based on the GPUDEVICE output. You can
% override it by setting the 'CudaArch' parameter (e.g. in case of
% multiple GPUs with various architectures).
%
% See also: [Compliling MatConvNet](../install.md#compiling),
% [Compiling MEX files containing CUDA
% code](http://mathworks.com/help/distcomp/run-mex-functions-containing-cuda-code.html),
% `vl_setup()`, `vl_imreadjpeg()`.
% Copyright (C) 2014-15 Karel Lenc and Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
% Get MatConvNet root directory
root = fileparts(fileparts(mfilename('fullpath'))) ;
addpath(fullfile(root, 'matlab')) ;
% --------------------------------------------------------------------
% Parse options
% --------------------------------------------------------------------
opts.enableGpu = false;
opts.enableImreadJpeg = true;
opts.enableCudnn = false;
opts.imageLibrary = [] ;
opts.imageLibraryCompileFlags = {} ;
opts.imageLibraryLinkFlags = [] ;
opts.verbose = 0;
opts.debug = false;
opts.cudaMethod = [] ;
opts.cudaRoot = [] ;
opts.cudaArch = [] ;
opts.defCudaArch = [...
'-gencode=arch=compute_20,code=\"sm_20,compute_20\" '...
'-gencode=arch=compute_30,code=\"sm_30,compute_30\"'];
opts.cudnnRoot = 'local' ;
opts = vl_argparse(opts, varargin);
% --------------------------------------------------------------------
% Files to compile
% --------------------------------------------------------------------
arch = computer('arch') ;
if isempty(opts.imageLibrary)
switch arch
case 'glnxa64', opts.imageLibrary = 'libjpeg' ;
case 'maci64', opts.imageLibrary = 'quartz' ;
case 'win64', opts.imageLibrary = 'gdiplus' ;
end
end
if isempty(opts.imageLibraryLinkFlags)
switch opts.imageLibrary
case 'libjpeg', opts.imageLibraryLinkFlags = {'-ljpeg'} ;
case 'quartz', opts.imageLibraryLinkFlags = {'LDFLAGS=$LDFLAGS -framework Cocoa -framework ImageIO'} ;
case 'gdiplus', opts.imageLibraryLinkFlags = {'-lgdiplus'} ;
end
end
lib_src = {} ;
mex_src = {} ;
% Files that are compiled as CPP or CU depending on whether GPU support
% is enabled.
if opts.enableGpu, ext = 'cu' ; else, ext='cpp' ; end
lib_src{end+1} = fullfile(root,'matlab','src','bits',['data.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['datamex.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnconv.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnfullyconnected.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnsubsample.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnpooling.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnnormalize.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbnorm.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbias.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconv.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconvt.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnpool.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnnormalize.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbnorm.' ext]) ;
% CPU-specific files
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','tinythread.cpp') ;
% GPU-specific files
if opts.enableGpu
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','datacu.cu') ;
end
% cuDNN-specific files
if opts.enableCudnn
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnconv_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbias_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnpooling_cudnn.cu') ;
end
% Other files
if opts.enableImreadJpeg
mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src', 'bits', 'impl', ['imread_' opts.imageLibrary '.cpp']) ;
end
% --------------------------------------------------------------------
% Setup CUDA toolkit
% --------------------------------------------------------------------
if opts.enableGpu
opts.verbose && fprintf('%s: * CUDA configuration *\n', mfilename) ;
if isempty(opts.cudaRoot), opts.cudaRoot = search_cuda_devkit(opts); end
check_nvcc(opts.cudaRoot);
opts.verbose && fprintf('%s:\tCUDA: using CUDA Devkit ''%s''.\n', ...
mfilename, opts.cudaRoot) ;
switch arch
case 'win64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib', 'x64') ;
case 'maci64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib') ;
case 'glnxa64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib64') ;
otherwise, error('Unsupported architecture ''%s''.', arch) ;
end
opts.nvccPath = fullfile(opts.cudaRoot, 'bin', 'nvcc') ;
% CUDA arch string (select GPU architecture)
if isempty(opts.cudaArch), opts.cudaArch = get_cuda_arch(opts) ; end
opts.verbose && fprintf('%s:\tCUDA: NVCC architecture string: ''%s''.\n', ...
mfilename, opts.cudaArch) ;
% Make sure NVCC is visible by MEX by setting the corresp. env. var
if ~strcmp(getenv('MW_NVCC_PATH'), opts.nvccPath)
warning('Setting the ''MW_NVCC_PATH'' environment variable to ''%s''', ...
opts.nvccPath) ;
setenv('MW_NVCC_PATH', opts.nvccPath) ;
end
end
% --------------------------------------------------------------------
% Compiler options
% --------------------------------------------------------------------
% Build directories
mex_dir = fullfile(root, 'matlab', 'mex') ;
bld_dir = fullfile(mex_dir, '.build');
if ~exist(fullfile(bld_dir,'bits','impl'), 'dir')
mkdir(fullfile(bld_dir,'bits','impl')) ;
end
% Compiler flags
flags.cc = {} ;
flags.link = {} ;
if opts.verbose > 1
flags.cc{end+1} = '-v' ;
flags.link{end+1} = '-v' ;
end
if opts.debug
flags.cc{end+1} = '-g' ;
else
flags.cc{end+1} = '-DNDEBUG' ;
end
if opts.enableGpu, flags.cc{end+1} = '-DENABLE_GPU' ; end
if opts.enableCudnn,
flags.cc{end+1} = '-DENABLE_CUDNN' ;
flags.cc{end+1} = ['-I' opts.cudnnRoot] ;
end
flags.link{end+1} = '-lmwblas' ;
switch arch
case {'maci64', 'glnxa64'}
case {'win64'}
% VisualC does not pass this even if available in the CPU architecture
flags.cc{end+1} = '-D__SSSE3__' ;
end
if opts.enableImreadJpeg
flags.cc = horzcat(flags.cc, opts.imageLibraryCompileFlags) ;
flags.link = horzcat(flags.link, opts.imageLibraryLinkFlags) ;
end
if opts.enableGpu
flags.link{end+1} = ['-L' opts.cudaLibDir] ;
flags.link{end+1} = '-lcudart' ;
flags.link{end+1} = '-lcublas' ;
switch arch
case {'maci64', 'glnxa64'}
flags.link{end+1} = '-lmwgpu' ;
case 'win64'
flags.link{end+1} = '-lgpu' ;
end
if opts.enableCudnn
flags.link{end+1} = ['-L' opts.cudnnRoot] ;
flags.link{end+1} = '-lcudnn' ;
end
end
% For the MEX command
flags.link{end+1} = '-largeArrayDims' ;
flags.mexcc = flags.cc ;
flags.mexcc{end+1} = '-largeArrayDims' ;
flags.mexcc{end+1} = '-cxx' ;
if strcmp(arch, 'maci64')
% CUDA prior to 7.0 on Mac require GCC libstdc++ instead of the native
% Clang libc++. This should go away in the future.
flags.mexcc{end+1} = 'CXXFLAGS=$CXXFLAGS -stdlib=libstdc++' ;
flags.link{end+1} = 'LDFLAGS=$LDFLAGS -stdlib=libstdc++' ;
if ~verLessThan('matlab', '8.5.0')
% Complicating matters, MATLAB 8.5.0 links to Clang c++ by default
% when linking MEX files overriding the option above. More force
% is needed:
flags.link{end+1} = 'LINKLIBS=$LINKLIBS -L"$MATLABROOT/bin/maci64" -lmx -lmex -lmat -lstdc++' ;
end
end
if opts.enableGpu
flags.mexcu = flags.cc ;
flags.mexcu{end+1} = '-largeArrayDims' ;
flags.mexcu{end+1} = '-cxx' ;
flags.mexcu(end+1:end+2) = {'-f' mex_cuda_config(root)} ;
flags.mexcu{end+1} = ['NVCCFLAGS=' opts.cudaArch '$NVCC_FLAGS'] ;
end
% For the cudaMethod='nvcc'
if opts.enableGpu && strcmp(opts.cudaMethod,'nvcc')
flags.nvcc = flags.cc ;
flags.nvcc{end+1} = ['-I"' fullfile(matlabroot, 'extern', 'include') '"'] ;
flags.nvcc{end+1} = ['-I"' fullfile(matlabroot, 'toolbox','distcomp','gpu','extern','include') '"'] ;
if opts.debug
flags.nvcc{end+1} = '-O0' ;
end
flags.nvcc{end+1} = '-Xcompiler' ;
switch arch
case {'maci64', 'glnxa64'}
flags.nvcc{end+1} = '-fPIC' ;
case 'win64'
flags.nvcc{end+1} = '/MD' ;
check_clpath(); % check whether cl.exe in path
end
flags.nvcc{end+1} = opts.cudaArch;
end
if opts.verbose
fprintf('%s: * Compiler and linker configurations *\n', mfilename) ;
fprintf('%s: \tintermediate build products directory: %s\n', mfilename, bld_dir) ;
fprintf('%s: \tMEX files: %s/\n', mfilename, mex_dir) ;
fprintf('%s: \tMEX compiler options: %s\n', mfilename, strjoin(flags.mexcc)) ;
fprintf('%s: \tMEX linker options: %s\n', mfilename, strjoin(flags.link)) ;
end
if opts.verbose & opts.enableGpu
fprintf('%s: \tMEX compiler options (CUDA): %s\n', mfilename, strjoin(flags.mexcu)) ;
end
if opts.verbose & opts.enableGpu & strcmp(opts.cudaMethod,'nvcc')
fprintf('%s: \tNVCC compiler options: %s\n', mfilename, strjoin(flags.nvcc)) ;
end
if opts.verbose & opts.enableImreadJpeg
fprintf('%s: * Reading images *\n', mfilename) ;
fprintf('%s: \tvl_imreadjpeg enabled\n', mfilename) ;
fprintf('%s: \timage library: %s\n', mfilename, opts.imageLibrary) ;
fprintf('%s: \timage library compile flags: %s\n', mfilename, strjoin(opts.imageLibraryCompileFlags)) ;
fprintf('%s: \timage library link flags: %s\n', mfilename, strjoin(opts.imageLibraryLinkFlags)) ;
end
% --------------------------------------------------------------------
% Compile
% --------------------------------------------------------------------
% Intermediate object files
srcs = horzcat(lib_src,mex_src) ;
parfor i = 1:numel(horzcat(lib_src, mex_src))
[~,~,ext] = fileparts(srcs{i}) ; ext(1) = [] ;
if strcmp(ext,'cu')
if strcmp(opts.cudaMethod,'nvcc')
nvcc_compile(opts, srcs{i}, toobj(bld_dir,srcs{i}), flags.nvcc) ;
else
mex_compile(opts, srcs{i}, toobj(bld_dir,srcs{i}), flags.mexcu) ;
end
else
mex_compile(opts, srcs{i}, toobj(bld_dir,srcs{i}), flags.mexcc) ;
end
end
% Link into MEX files
parfor i = 1:numel(mex_src)
[~,base,~] = fileparts(mex_src{i}) ;
objs = toobj(bld_dir, {mex_src{i}, lib_src{:}}) ;
mex_link(opts, objs, mex_dir, flags.link) ;
end
% Reset path adding the mex subdirectory just created
vl_setupnn() ;
% --------------------------------------------------------------------
% Utility functions
% --------------------------------------------------------------------
% --------------------------------------------------------------------
function objs = toobj(bld_dir,srcs)
% --------------------------------------------------------------------
str = fullfile('matlab','src') ;
multiple = iscell(srcs) ;
if ~multiple, srcs = {srcs} ; end
for t = 1:numel(srcs)
i = strfind(srcs{t},str);
objs{t} = fullfile(bld_dir, srcs{t}(i+numel(str):end)) ;
end
if ~multiple, objs = objs{1} ; end
objs = strrep(objs,'.cpp',['.' objext]) ;
objs = strrep(objs,'.cu',['.' objext]) ;
objs = strrep(objs,'.c',['.' objext]) ;
% --------------------------------------------------------------------
function objs = mex_compile(opts, src, tgt, mex_opts)
% --------------------------------------------------------------------
mopts = {'-outdir', fileparts(tgt), src, '-c', mex_opts{:}} ;
opts.verbose && fprintf('%s: MEX CC: %s\n', mfilename, strjoin(mopts)) ;
mex(mopts{:}) ;
% --------------------------------------------------------------------
function obj = nvcc_compile(opts, src, tgt, nvcc_opts)
% --------------------------------------------------------------------
nvcc_path = fullfile(opts.cudaRoot, 'bin', 'nvcc');
nvcc_cmd = sprintf('"%s" -c "%s" %s -o "%s"', ...
nvcc_path, src, ...
strjoin(nvcc_opts), tgt);
opts.verbose && fprintf('%s: NVCC CC: %s\n', mfilename, nvcc_cmd) ;
status = system(nvcc_cmd);
if status, error('Command %s failed.', nvcc_cmd); end;
% --------------------------------------------------------------------
function mex_link(opts, objs, mex_dir, mex_flags)
% --------------------------------------------------------------------
mopts = {'-outdir', mex_dir, mex_flags{:}, objs{:}} ;
opts.verbose && fprintf('%s: MEX LINK: %s\n', mfilename, strjoin(mopts)) ;
mex(mopts{:}) ;
% --------------------------------------------------------------------
function ext = objext()
% --------------------------------------------------------------------
% Get the extension for an 'object' file for the current computer
% architecture
switch computer('arch')
case 'win64', ext = 'obj';
case {'maci64', 'glnxa64'}, ext = 'o' ;
otherwise, error('Unsupported architecture %s.', computer) ;
end
% --------------------------------------------------------------------
function conf_file = mex_cuda_config(root)
% --------------------------------------------------------------------
% Get mex CUDA config file
mver = [1e4 1e2 1] * sscanf(version, '%d.%d.%d') ;
if mver <= 80200, ext = 'sh' ; else ext = 'xml' ; end
arch = computer('arch') ;
switch arch
case {'win64'}
config_dir = fullfile(matlabroot, 'toolbox', ...
'distcomp', 'gpu', 'extern', ...
'src', 'mex', arch) ;
case {'maci64', 'glnxa64'}
config_dir = fullfile(root, 'matlab', 'src', 'config') ;
end
conf_file = fullfile(config_dir, ['mex_CUDA_' arch '.' ext]);
fprintf('%s:\tCUDA: MEX config file: ''%s''\n', mfilename, conf_file);
% --------------------------------------------------------------------
function check_clpath()
% --------------------------------------------------------------------
% Checks whether the cl.exe is in the path (needed for the nvcc). If
% not, tries to guess the location out of mex configuration.
status = system('cl.exe -help');
if status == 1
warning('CL.EXE not found in PATH. Trying to guess out of mex setup.');
cc = mex.getCompilerConfigurations('c++');
if isempty(cc)
error('Mex is not configured. Run "mex -setup".');
end
prev_path = getenv('PATH');
cl_path = fullfile(cc.Location, 'VC','bin','x86_amd64');
setenv('PATH', [prev_path ';' cl_path]);
status = system('cl.exe');
if status == 1
setenv('PATH', prev_path);
error('Unable to find cl.exe');
else
fprintf('Location of cl.exe (%s) successfully added to your PATH.\n', ...
cl_path);
end
end
% -------------------------------------------------------------------------
function paths = which_nvcc(opts)
% -------------------------------------------------------------------------
switch computer('arch')
case 'win64'
[~, paths] = system('where nvcc.exe');
paths = strtrim(paths);
paths = paths(strfind(paths, '.exe'));
case {'maci64', 'glnxa64'}
[~, paths] = system('which nvcc');
paths = strtrim(paths) ;
end
% -------------------------------------------------------------------------
function cuda_root = search_cuda_devkit(opts)
% -------------------------------------------------------------------------
% This function tries to to locate a working copy of the CUDA Devkit.
opts.verbose && fprintf(['%s:\tCUDA: seraching for the CUDA Devkit' ...
' (use the option ''CudaRoot'' to override):\n'], mfilename);
% Propose a number of candidate paths for NVCC
paths = {getenv('MW_NVCC_PATH')} ;
paths = [paths, which_nvcc(opts)] ;
for v = {'5.5', '6.0', '6.5', '7.0'}
switch computer('arch')
case 'glnxa64'
paths{end+1} = sprintf('/usr/local/cuda-%s/bin/nvcc', char(v)) ;
case 'maci64'
paths{end+1} = sprintf('/Developer/NVIDIA/CUDA-%s/bin/nvcc', char(v)) ;
case 'win64'
paths{end+1} = sprintf('C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v%s\\bin\\nvcc.exe', char(v)) ;
end
end
paths{end+1} = sprintf('/usr/local/cuda/bin/nvcc') ;
% Validate each candidate NVCC path
for i=1:numel(paths)
nvcc(i).path = paths{i} ;
[nvcc(i).isvalid, nvcc(i).version] = validate_nvcc(opts,paths{i}) ;
end
if opts.verbose
fprintf('\t| %5s | %5s | %-70s |\n', 'valid', 'ver', 'NVCC path') ;
for i=1:numel(paths)
fprintf('\t| %5d | %5d | %-70s |\n', ...
nvcc(i).isvalid, nvcc(i).version, nvcc(i).path) ;
end
end
% Pick an entry
index = find([nvcc.isvalid]) ;
if isempty(index)
error('Could not find a valid NVCC executable\n') ;
end
nvcc = nvcc(index(1)) ;
cuda_root = fileparts(fileparts(nvcc.path)) ;
if opts.verbose
fprintf('%s:\tCUDA: choosing NVCC compiler ''%s'' (version %d)\n', ...
mfilename, nvcc.path, nvcc.version) ;
end
% -------------------------------------------------------------------------
function [valid, cuver] = validate_nvcc(opts, nvcc_path)
% -------------------------------------------------------------------------
valid = false ;
cuver = 0 ;
if ~isempty(nvcc_path)
[status, output] = system(sprintf('"%s" --version', nvcc_path)) ;
valid = (status == 0) ;
end
if ~valid, return ; end
match = regexp(output, 'V(\d+\.\d+\.\d+)', 'match') ;
if isempty(match), valid = false ; return ; end
cuver = [1e4 1e2 1] * sscanf(match{1}, 'V%d.%d.%d') ;
% --------------------------------------------------------------------
function check_nvcc(cuda_root)
% --------------------------------------------------------------------
% Checks whether the nvcc is in the path. If not, guessed out of CudaRoot.
[status, ~] = system('nvcc --help');
if status ~= 0
warning('nvcc not found in PATH. Trying to guess out of CudaRoot.');
cuda_bin_path = fullfile(cuda_root, 'bin');
prev_path = getenv('PATH');
switch computer
case 'PCWIN64', separator = ';';
case {'GLNXA64', 'MACI64'}, separator = ':';
end
setenv('PATH', [prev_path separator cuda_bin_path]);
[status, ~] = system('nvcc --help');
if status ~= 0
setenv('PATH', prev_path);
error('Unable to find nvcc.');
else
fprintf('Location of nvcc (%s) added to your PATH.\n', cuda_bin_path);
end
end
% --------------------------------------------------------------------
function cudaArch = get_cuda_arch(opts)
% --------------------------------------------------------------------
opts.verbose && fprintf('%s:\tCUDA: determining GPU compute capability (use the ''CudaArch'' option to override)\n', mfilename);
try
gpu_device = gpuDevice();
arch_code = strrep(gpu_device.ComputeCapability, '.', '');
cudaArch = ...
sprintf('-gencode=arch=compute_%s,code=\\\"sm_%s,compute_%s\\\" ', ...
arch_code, arch_code, arch_code) ;
catch
opts.verbose && fprintf(['%s:\tCUDA: cannot determine the capabilities of the installed GPU;' ...
'falling back to default\n'], mfilename);
cudaArch = opts.defCudaArch;
end
|
github
|
mowangphy/HOPE-CNN-master
|
vl_simplenn_display.m
|
.m
|
HOPE-CNN-master/matlab/simplenn/vl_simplenn_display.m
| 10,932 |
utf_8
|
c7ed88fccca92a96ffe9c36dcb72d278
|
function info = vl_simplenn_display(net, varargin)
% VL_SIMPLENN_DISPLAY Simple CNN statistics
% VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET.
%
% INFO=VL_SIMPLENN_DISPLAY(NET) returns instead a structure INFO
% with several statistics for each layer of the network NET.
%
% The function accepts the following options:
%
% `inputSize`:: heuristically set
% Specifies the size of the input tensor X that will be passed
% to the network. This is used in order to estiamte the memory
% required to process the network. If not specified,
% VL_SIMPLENN_DISPLAY uses the value in
% NET.NORMALIZATION.IMAGESIZE assuming a batch size of one
% image, unless otherwise specified by the `batchSize` option.
%
% `batchSize`:: 1
% Specifies the number of data points in a batch in estimating
% the memory consumption (see `inputSize`).
% Copyright (C) 2014-15 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.inputSize = [] ;
opts.batchSize = 1 ;
opts.maxNumColumns = 18 ;
opts.format = 'ascii' ;
opts = vl_argparse(opts, varargin) ;
fields={'layer', 'type', 'name', '-', ...
'support', 'filtd', 'nfilt', 'stride', 'pad', '-', ...
'rfsize', 'rfoffset', 'rfstride', '-', ...
'dsize', 'ddepth', 'dnum', '-', ...
'xmem', 'wmem'};
% get the support, stride, and padding of the operators
for l = 1:numel(net.layers)
ly = net.layers{l} ;
switch ly.type
case 'conv'
if isfield(ly, 'weights')
info.support(1:2,l) = max([size(ly.weights{1},1) ; size(ly.weights{1},2)],1) ;
else
info.support(1:2,l) = max([size(ly.filters,1) ; size(ly.filters,2)],1) ;
end
case 'pool'
info.support(1:2,l) = ly.pool(:) ;
otherwise
info.support(1:2,l) = [1;1] ;
end
if isfield(ly, 'stride')
info.stride(1:2,l) = ly.stride(:) ;
else
info.stride(1:2,l) = 1 ;
end
if isfield(ly, 'pad')
info.pad(1:4,l) = ly.pad(:) ;
else
info.pad(1:4,l) = 0 ;
end
% operator applied to the input image
info.receptiveFieldSize(1:2,l) = 1 + ...
sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...
(info.support(1:2,1:l)-1),2) ;
info.receptiveFieldOffset(1:2,l) = 1 + ...
sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...
((info.support(1:2,1:l)-1)/2 - info.pad([1 3],1:l)),2) ;
info.receptiveFieldStride = cumprod(info.stride,2) ;
end
% get the dimensions of the data
if ~isempty(opts.inputSize) ;
info.dataSize(1:4,1) = opts.inputSize(:) ;
elseif isfield(net, 'normalization') && isfield(net.normalization, 'imageSize')
info.dataSize(1:4,1) = [net.normalization.imageSize(:) ; opts.batchSize] ;
else
info.dataSize(1:4,1) = [NaN NaN NaN opts.batchSize] ;
end
for l = 1:numel(net.layers)
ly = net.layers{l} ;
if strcmp(ly.type, 'custom') && isfield(ly, 'getForwardSize')
sz = ly.getForwardSize(ly, info.dataSize(:,l)) ;
info.dataSize(:,l+1) = sz(:) ;
continue ;
end
info.dataSize(1, l+1) = floor((info.dataSize(1,l) + ...
sum(info.pad(1:2,l)) - ...
info.support(1,l)) / info.stride(1,l)) + 1 ;
info.dataSize(2, l+1) = floor((info.dataSize(2,l) + ...
sum(info.pad(3:4,l)) - ...
info.support(2,l)) / info.stride(2,l)) + 1 ;
info.dataSize(3, l+1) = info.dataSize(3,l) ;
info.dataSize(4, l+1) = info.dataSize(4,l) ;
switch ly.type
case 'conv'
if isfield(ly, 'weights')
f = ly.weights{1} ;
else
f = ly.filters ;
end
if size(f, 3) ~= 0
info.dataSize(3, l+1) = size(f,4) ;
end
case {'loss', 'softmaxloss'}
info.dataSize(3:4, l+1) = 1 ;
case 'custom'
info.dataSize(3,l+1) = NaN ;
end
end
if nargout > 0, return ; end
% print table
table = {} ;
wmem = 0 ;
xmem = 0 ;
for wi=1:numel(fields)
w = fields{wi} ;
switch w
case 'type', s = 'type' ;
case 'stride', s = 'stride' ;
case 'rfsize', s = 'rf size' ;
case 'rfstride', s = 'rf stride' ;
case 'rfoffset', s = 'rf offset' ;
case 'dsize', s = 'data size' ;
case 'ddepth', s = 'data depth' ;
case 'dnum', s = 'data num' ;
case 'nfilt', s = 'num filts' ;
case 'filtd', s = 'filt dim' ;
case 'wmem', s = 'param mem' ;
case 'xmem', s = 'data mem' ;
otherwise, s = char(w) ;
end
table{wi,1} = s ;
% do input pseudo-layer
for l=0:numel(net.layers)
switch char(w)
case '-', s='-' ;
case 'layer', s=sprintf('%d', l) ;
case 'dsize', s=pdims(info.dataSize(1:2,l+1)) ;
case 'ddepth', s=sprintf('%d', info.dataSize(3,l+1)) ;
case 'dnum', s=sprintf('%d', info.dataSize(4,l+1)) ;
case 'xmem'
a = prod(info.dataSize(:,l+1)) * 4 ;
s = pmem(a) ;
xmem = xmem + a ;
otherwise
if l == 0
if strcmp(char(w),'type'), s = 'input';
else s = 'n/a' ; end
else
ly=net.layers{l} ;
switch char(w)
case 'name'
if isfield(ly, 'name')
s=ly.name ;
else
s='' ;
end
case 'type'
switch ly.type
case 'normalize', s='norm';
case 'pool'
if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end
case 'softmax', s='softmx' ;
case 'softmaxloss', s='softmxl' ;
otherwise s=ly.type ;
end
case 'nfilt'
switch ly.type
case 'conv'
if isfield(ly, 'weights'), a = size(ly.weights{1},4) ;
else, a = size(ly.filters,4) ; end
s=sprintf('%d',a) ;
otherwise
s='n/a' ;
end
case 'filtd'
switch ly.type
case 'conv'
if isfield(ly, 'weights'), a = size(ly.weights{1},3) ;
else, a = size(ly.filters,3) ; end
s=sprintf('%d',a) ;
otherwise
s='n/a' ;
end
case 'support'
s = pdims(info.support(:,l)) ;
case 'stride'
s = pdims(info.stride(:,l)) ;
case 'pad'
s = pdims(info.pad(:,l)) ;
case 'rfsize'
s = pdims(info.receptiveFieldSize(:,l)) ;
case 'rfoffset'
s = pdims(info.receptiveFieldOffset(:,l)) ;
case 'rfstride'
s = pdims(info.receptiveFieldStride(:,l)) ;
case 'wmem'
a = 0 ;
if isfield(ly, 'weights') ;
for j=1:numel(ly.weights)
a = a + numel(ly.weights{j}) * 4 ;
end
end
% Legacy code to be removed
if isfield(ly, 'filters') ;
a = a + numel(ly.filters) * 4 ;
end
if isfield(ly, 'biases') ;
a = a + numel(ly.biases) * 4 ;
end
s = pmem(a) ;
wmem = wmem + a ;
end
end
end
table{wi,l+2} = s ;
end
end
for i=2:opts.maxNumColumns:size(table,2)
sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ;
switch opts.format
case 'ascii', pascii(table(:,[1 sel])) ; fprintf('\n') ;
case 'latex', platex(table(:,[1 sel])) ;
case 'csv', pcsv(table(:,[1 sel])) ; fprintf('\n') ;
end
end
fprintf('parameter memory: %s (%.2g parameters)\n', pmem(wmem), wmem/4) ;
fprintf('data memory: %s (for batch size %d)\n', pmem(xmem), info.dataSize(4,1)) ;
% -------------------------------------------------------------------------
function s = pmem(x)
% -------------------------------------------------------------------------
if isnan(x), s = 'NaN' ;
elseif x < 1024^1, s = sprintf('%.0fB', x) ;
elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ;
elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ;
else s = sprintf('%.0fGB', x / 1024^3) ;
end
% -------------------------------------------------------------------------
function s = pdims(x)
% -------------------------------------------------------------------------
if all(x==x(1))
s = sprintf('%.4g', x(1)) ;
else
s = sprintf('%.4gx', x(:)) ;
s(end) = [] ;
end
% -------------------------------------------------------------------------
function pascii(table)
% -------------------------------------------------------------------------
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
for i=1:size(table,1)
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds|', sizes(j)) ;
if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end
fprintf(fmt, s) ;
end
fprintf('\n') ;
end
% -------------------------------------------------------------------------
function pcsv(table)
% -------------------------------------------------------------------------
sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds,', sizes(j)) ;
fprintf(fmt, ['"' s '"']) ;
end
fprintf('\n') ;
end
% -------------------------------------------------------------------------
function platex(table)
% -------------------------------------------------------------------------
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
fprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), fprintf('\\hline\n') ; continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds', sizes(j)) ;
fprintf(fmt, latexesc(s)) ;
if j<size(table,2), fprintf('&') ; end
end
fprintf('\\\\\n') ;
end
fprintf('\\end{tabular}\n') ;
% -------------------------------------------------------------------------
function s = latexesc(s)
% -------------------------------------------------------------------------
s = strrep(s,'\','\\') ;
s = strrep(s,'_','\char`_') ;
% -------------------------------------------------------------------------
function [cpuMem,gpuMem] = xmem(s, cpuMem, gpuMem)
% -------------------------------------------------------------------------
if nargin <= 1
cpuMem = 0 ;
gpuMem = 0 ;
end
if isstruct(s)
for f=fieldnames(s)'
f = char(f) ;
for i=1:numel(s)
[cpuMem,gpuMem] = xmem(s(i).(f), cpuMem, gpuMem) ;
end
end
elseif iscell(s)
for i=1:numel(s)
[cpuMem,gpuMem] = xmem(s{i}, cpuMem, gpuMem) ;
end
elseif isnumeric(s)
if isa(s, 'single')
mult = 4 ;
else
mult = 8 ;
end
if isa(s,'gpuArray')
gpuMem = gpuMem + mult * numel(s) ;
else
cpuMem = cpuMem + mult * numel(s) ;
end
end
|
github
|
mowangphy/HOPE-CNN-master
|
vl_test_economic_relu.m
|
.m
|
HOPE-CNN-master/matlab/xtest/vl_test_economic_relu.m
| 790 |
utf_8
|
35a3dbe98b9a2f080ee5f911630ab6f3
|
% VL_TEST_ECONOMIC_RELU
function vl_test_economic_relu()
x = randn(11,12,8,'single');
w = randn(5,6,8,9,'single');
b = randn(1,9,'single') ;
net.layers{1} = struct('type', 'conv', ...
'filters', w, ...
'biases', b, ...
'stride', 1, ...
'pad', 0);
net.layers{2} = struct('type', 'relu') ;
res = vl_simplenn(net, x) ;
dzdy = randn(size(res(end).x), 'like', res(end).x) ;
clear res ;
res_ = vl_simplenn(net, x, dzdy) ;
res__ = vl_simplenn(net, x, dzdy, [], 'conserveMemory', true) ;
a=whos('res_') ;
b=whos('res__') ;
assert(a.bytes > b.bytes) ;
vl_testsim(res_(1).dzdx,res__(1).dzdx,1e-4) ;
vl_testsim(res_(1).dzdw{1},res__(1).dzdw{1},1e-4) ;
vl_testsim(res_(1).dzdw{2},res__(1).dzdw{2},1e-4) ;
|
github
|
qq8699444/DeepCascade-master
|
use_cimgmatlab.m
|
.m
|
DeepCascade-master/libs/CImg/examples/use_cimgmatlab.m
| 1,242 |
utf_8
|
c7cefea57d7bf6077ec6a77f3bdda6b6
|
/*-----------------------------------------------------------------------
File : use_cimgmatlab.m
Description: Example of use for the CImg plugin 'plugins/cimgmatlab.h'
which allows to use CImg in order to develop matlab external
functions (mex functions).
User should be familiar with Matlab C/C++ mex function concepts,
as this file is by no way a mex programming tutorial.
This simple example implements a mex function that can be called
as
- v = cimgmatlab_cannyderiche(u,s)
- v = cimgmatlab_cannyderiche(u,sx,sy)
- v = cimgmatlab_cannyderiche(u,sx,sy,sz)
The corresponding m-file is cimgmatlab_cannyderiche.m
Copyright : Francois Lauze - http://www.itu.dk/people/francois
This software is governed by the Gnu General Public License
see http://www.gnu.org/copyleft/gpl.html
The plugin home page is at
http://www.itu.dk/people/francois/cimgmatlab.html
for the compilation: using the mex utility provided with matlab, just
remember to add the -I flags with paths to CImg.h and/or cimgmatlab.h.
The default lcc cannot be used, it is a C compiler and not a C++ one!
--------------------------------------------------------------------------*/
function v = cimgmatlab_cannyderiche(u,sx,sy,sz)
|
github
|
mubeipeng/focused_slam-master
|
VisibilityCheck.m
|
.m
|
focused_slam-master/FIRM/VisibilityCheck.m
| 1,580 |
utf_8
|
0cca7e618b1f8a8745dfd835e891f051
|
function Full_data = VisibilityCheck(Full_data)
n_waypoints = size(Full_data.logged_data,1);
for wayPoint_id = 1:n_waypoints
for k = 1 : length(Full_data.logged_data(wayPoint_id,:))
if isempty(Full_data.logged_data(wayPoint_id,k).x)
break
end
x = Full_data.logged_data(wayPoint_id,k).x;
visibility{wayPoint_id,k} = CheckLandmarkVisibility(x,Full_data.landmark_map_GT, Full_data.obstacle_map);
disp([wayPoint_id, k])
end
end
Full_data.visibility = visibility;
end
function YesNo = CheckLandmarkVisibility(x,landmark_map_GT, obstacle_map)
for id_landmark = 1:length(landmark_map_GT)
Lx = landmark_map_GT(1,id_landmark);
Ly = landmark_map_GT(2,id_landmark);
angle = atan2(Ly-x(2), Lx-x(1)) - x(3);
front = 0;
if angle >=-pi/2 && angle <=pi/2
%front = FrontOrBackOfRobot(Lx, Ly, line);
front = 1;
end
YesNo(id_landmark) = 1;
if ~front
YesNo(id_landmark) = 0;
else
N_obst = size(obstacle_map,2);
for ib=1:N_obst
X_obs=[obstacle_map{ib}(:,1);obstacle_map{ib}(1,1)];
Y_obs=[obstacle_map{ib}(:,2);obstacle_map{ib}(1,2)];
X_ray=[x(1), Lx];
Y_ray= [x(2), Ly];
[x_inters,~] = polyxpoly(X_obs,Y_obs,X_ray,Y_ray);
if ~isempty(x_inters)
YesNo(id_landmark) = 0;
break
end
end
end
end
end
|
github
|
mubeipeng/focused_slam-master
|
GetStochasticMap.m
|
.m
|
focused_slam-master/FIRM/GetStochasticMap.m
| 2,095 |
utf_8
|
aefe6228bfc64bbe07099ffa88403a8c
|
function Map_of_landmarks = GetStochasticMap(varargin) % we overwrite the input map
magnifying_focused_cov = 0.1;
GT_landmarks = varargin{1};
lm_file = varargin{2};
% %%% generate_fake_map
%%%% ==========================================================
% for i = 1:size(GT_landmarks.landmarks,2)
% focus_weight = is_focused(GT_landmarks.landmarks(:,i));
% map_landmarks_cov(2*i-1:2*i, 2*i-1:2*i) = eye(2)*magnifying_focused_cov^2*focus_weight^2;
% end
%%%% ==========================================================
% map_landmarks_mean = GT_landmarks.landmarks;
%
% Map_of_landmarks.obsDim = GT_landmarks.obsDim;
% Map_of_landmarks.landmarks = map_landmarks_mean;
% Map_of_landmarks.covariances = map_landmarks_cov;
GT_landmark = [];
Map_of_landmarks.obsDim = size(GT_landmarks.landmarks,2)*2;
map_landmarks_mean = GT_landmarks.landmarks;
map_landmarks_mean(:,lm_file.id) = lm_file.pos;
Map_of_landmarks.landmarks = map_landmarks_mean;
map_landmarks_cov = eye(2*size(GT_landmarks.landmarks,2))*100;
for i = 1:size(lm_file.id,2)
id = 2*lm_file.id(i);
% if ndims(lm_file.cov)==3
% map_landmarks_cov(id-1:id, id-1:id) = lm_file.cov(:,:,i)*magnifying_focused_cov;
% else
map_landmarks_cov(id-1,id-1) = magnifying_focused_cov* exp(-lm_file.entropy(i)/2);
map_landmarks_cov(id,id) = map_landmarks_cov(id-1,id-1);
% end
% map_landmarks_cov(id-1:id, id-1:id) = BP_map_cov_update(GT_landmarks.landmarks(:,id/2), lm_file.cov(i));
end
Map_of_landmarks.covariances = map_landmarks_cov;
%% drawing the map
for i = 1:size(map_landmarks_mean, 2)
cov_i = Map_of_landmarks.covariances(2*i-1:2*i, 2*i-1:2*i);
if cov_i(1,1) ~=100
mean_i = map_landmarks_mean(:,i);
line_width = 3;
plotUncertainEllip2D(cov_i , mean_i , 'g-', line_width , 0.5);
else
plot(map_landmarks_mean(1,i), map_landmarks_mean(2,i), 's', 'color', [0 0.1 0], 'markersize', 12)
end
end
end
function focusWeight = is_focused(landmark)
focusWeight = 4;
end
|
github
|
mubeipeng/focused_slam-master
|
plot_gaussian_ellipsoid.m
|
.m
|
focused_slam-master/FIRM/General_functions/plot_gaussian_ellipsoid.m
| 3,942 |
utf_8
|
cb6edb0cf621ca98f288aeee309948c9
|
function h = plot_gaussian_ellipsoid(m, C, sdwidth, npts, axh)
% PLOT_GAUSSIAN_ELLIPSOIDS plots 2-d and 3-d Gaussian distributions
%
% H = PLOT_GAUSSIAN_ELLIPSOIDS(M, C) plots the distribution specified by
% mean M and covariance C. The distribution is plotted as an ellipse (in
% 2-d) or an ellipsoid (in 3-d). By default, the distributions are
% plotted in the current axes. H is the graphics handle to the plotted
% ellipse or ellipsoid.
%
% PLOT_GAUSSIAN_ELLIPSOIDS(M, C, SD) uses SD as the standard deviation
% along the major and minor axes (larger SD => larger ellipse). By
% default, SD = 1. Note:
% * For 2-d distributions, SD=1.0 and SD=2.0 cover ~ 39% and 86%
% of the total probability mass, respectively.
% * For 3-d distributions, SD=1.0 and SD=2.0 cover ~ 19% and 73%
% of the total probability mass, respectively.
%
% PLOT_GAUSSIAN_ELLIPSOIDS(M, C, SD, NPTS) plots the ellipse or
% ellipsoid with a resolution of NPTS (ellipsoids are generated
% on an NPTS x NPTS mesh; see SPHERE for more details). By
% default, NPTS = 50 for ellipses, and 20 for ellipsoids.
%
% PLOT_GAUSSIAN_ELLIPSOIDS(M, C, SD, NPTS, AX) adds the plot to the
% axes specified by the axis handle AX.
%
% Examples:
% -------------------------------------------
% % Plot three 2-d Gaussians
% figure;
% h1 = plot_gaussian_ellipsoid([1 1], [1 0.5; 0.5 1]);
% h2 = plot_gaussian_ellipsoid([2 1.5], [1 -0.7; -0.7 1]);
% h3 = plot_gaussian_ellipsoid([0 0], [1 0; 0 1]);
% set(h2,'color','r');
% set(h3,'color','g');
%
% % "Contour map" of a 2-d Gaussian
% figure;
% for sd = [0.3:0.4:4],
% h = plot_gaussian_ellipsoid([0 0], [1 0.8; 0.8 1], sd);
% end
%
% % Plot three 3-d Gaussians
% figure;
% h1 = plot_gaussian_ellipsoid([1 1 0], [1 0.5 0.2; 0.5 1 0.4; 0.2 0.4 1]);
% h2 = plot_gaussian_ellipsoid([1.5 1 .5], [1 -0.7 0.6; -0.7 1 0; 0.6 0 1]);
% h3 = plot_gaussian_ellipsoid([1 2 2], [0.5 0 0; 0 0.5 0; 0 0 0.5]);
% set(h2,'facealpha',0.6);
% view(129,36); set(gca,'proj','perspective'); grid on;
% grid on; axis equal; axis tight;
% -------------------------------------------
%
% Gautam Vallabha, Sep-23-2007, [email protected]
% Revision 1.0, Sep-23-2007
% - File created
% Revision 1.1, 26-Sep-2007
% - NARGOUT==0 check added.
% - Help added on NPTS for ellipsoids
if ~exist('sdwidth', 'var'), sdwidth = 1; end
if ~exist('npts', 'var'), npts = []; end
if ~exist('axh', 'var'), axh = gca; end
if numel(m) ~= length(m),
error('M must be a vector');
end
if ~( all(numel(m) == size(C)) )
error('Dimensionality of M and C must match');
end
if ~(isscalar(axh) && ishandle(axh) && strcmp(get(axh,'type'), 'axes'))
error('Invalid axes handle');
end
set(axh, 'nextplot', 'add');
switch numel(m)
case 2, h=show2d(m(:),C,sdwidth,npts,axh);
case 3, h=show3d(m(:),C,sdwidth,npts,axh);
otherwise
error('Unsupported dimensionality');
end
if nargout==0,
clear h;
end
%-----------------------------
function h = show2d(means, C, sdwidth, npts, axh)
if isempty(npts), npts=50; end
% plot the gaussian fits
tt=linspace(0,2*pi,npts)';
x = cos(tt); y=sin(tt);
ap = [x(:) y(:)]';
[v,d]=eig(C);
d = sdwidth * sqrt(d); % convert variance to sdwidth*sd
bp = (v*d*ap) + repmat(means, 1, size(ap,2));
h = plot(bp(1,:), bp(2,:), '-', 'parent', axh);
%-----------------------------
function h = show3d(means, C, sdwidth, npts, axh)
if isempty(npts), npts=20; end
[x,y,z] = sphere(npts);
ap = [x(:) y(:) z(:)]';
[v,d]=eig(C);
if any(d(:) < 0)
fprintf('warning: negative eigenvalues\n');
d = max(d,0);
end
d = 10*sdwidth * sqrt(d); % convert variance to sdwidth*sd
bp = (v*d*ap) + repmat(means, 1, size(ap,2));
xp = reshape(bp(1,:), size(x));
yp = reshape(bp(2,:), size(y));
zp = reshape(bp(3,:), size(z));
% h = surf(axh, xp,yp,zp);
|
github
|
mubeipeng/focused_slam-master
|
user_GUI.m
|
.m
|
focused_slam-master/FIRM/General_functions/user_GUI.m
| 25,536 |
utf_8
|
67d6b4693e4b315f1a8c83eee8413f70
|
function varargout = user_GUI(varargin)
% USER_GUI MATLAB code for user_GUI.fig
% USER_GUI, by itself, creates a new USER_GUI or raises the existing
% singleton*.
%
% H = USER_GUI returns the handle to a new USER_GUI or the handle to
% the existing singleton*.
%
% USER_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in USER_GUI.M with the given input arguments.
%
% USER_GUI('Property','Value',...) creates a new USER_GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before user_GUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to user_GUI_OpeningFcn via vararginan.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help user_GUI
% Last Modified by GUIDE v2.5 01-Jan-2015 19:58:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @user_GUI_OpeningFcn, ...
'gui_OutputFcn', @user_GUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes during object creation, after setting all properties.
function SFMP_GUI_fig_tag_CreateFcn(hObject, eventdata, handles)
% hObject handle to SFMP_GUI_fig_tag (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
global New_LoadFileName
handles.LoadFileName = New_LoadFileName; % The name of file, from which we want to load the parameters.
if ~isempty(New_LoadFileName)
load(handles.LoadFileName,'par')
else
par = [];
end
handles.old_par = par;
% Update handles structure
guidata(hObject, handles);
% --- Executes just before user_GUI is made visible.
function user_GUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to user_GUI (see VARARGIN)
% Choose default command line output for user_GUI
handles.output_GUI_figure_handle = hObject;
Update_GUI_fields(handles, handles.old_par); % We initialize the GUI fields using this function, based on the latest user parameters.
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes user_GUI wait for user response (see UIRESUME)
uiwait(handles.SFMP_GUI_fig_tag);
% --- Outputs from this function are returned to the command line.
function varargout = user_GUI_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output_GUI_figure_handle; % This is the handle of main GUI figure. This figure is gonna be deleted in next few lines, but this output is generated to keep the convention in Matlab that the first output in plotting something is the handle of figure.
varargout{2} = handles.output_Ok_Cancel; % This output indicates that if the user is pressed Ok or Cancel.
varargout{3} = handles.output_parameters; % This output is the main output and returns all the parameters needed in program execution.
delete(handles.SFMP_GUI_fig_tag);
% --- Executes on button press in OKbutton.
function OKbutton_Callback(hObject, eventdata, handles)
% hObject handle to OKbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Callback called when the OK button is pressed
handles.output_Ok_Cancel ='Ok';
par = gather_parameteres_from_GUI( handles ); % This function gathers all parameters, provided by user in GUI.
handles.output_parameters = par; % If the user presses the Cancel button, we do not return any parameters.
% resume the execution of the GUI
uiresume;
guidata(hObject,handles)
% delete(handles.SFMP_GUI_fig_tag); % Although we should close the GUI
% window here, we do not do it here, because then the information stored in
% handle is get cleared. Thus, we close the window in the
% "user_GUI_OutputFcn" function, which is executed after this function,
% because we have "uiresume" here.
% --- Executes on button press in Cancelbutton.
function Cancelbutton_Callback(hObject, eventdata, handles)
% hObject handle to Cancelbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Callback called when the Cancel button is pressed
handles.output_Ok_Cancel ='Cancel';
handles.output_parameters = []; % If the user presses the Cancel button, we do not return any parameters.
uiresume;
guidata(hObject,handles)
% delete(handles.SFMP_GUI_fig_tag); % Although we should close the GUI
% window here, we do not do it here, because then the information stored in
% handle is get cleared. Thus, we close the window in the
% "user_GUI_OutputFcn" function, which is executed after this function,
% because we have "uiresume" here.
% --- Executes when user attempts to close SFMP_GUI_fig_tag.
function SFMP_GUI_fig_tag_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to SFMP_GUI_fig_tag (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Callback called when the Close button is pressed
% Since the code for pressing the "close button" is exactly the same as the
% code for pressing the cancel button, we just call the
% "Cancelbutton_Callback" function.
Cancelbutton_Callback(handles.Cancelbutton, eventdata, handles)
% --- Executes on selection change in popupmenu_motion_model_selector.
function popupmenu_motion_model_selector_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_motion_model_selector (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_motion_model_selector contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_motion_model_selector
% --- Executes during object creation, after setting all properties.
function popupmenu_motion_model_selector_CreateFcn(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to popupmenu_motion_model_selector (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function handles = Draw_state_space_panel(handles , state_space_param)
% This function draws the state space panel in the GUI figure, based on
% the selected model in the "popupmenu_state_space_selector".
% following code is for initilizing the state of "pop-up" menu, based on
% the selected state space.
D = dir('All_state');
all_ss = {D([D.isdir]==0).name};
set(handles.popupmenu_state_space_selector, 'String', all_ss);
if ~isempty(state_space_param)
string_list = get(handles.popupmenu_state_space_selector, 'String'); % get list of possible state spaces from the pop-up menu
val = find(strcmpi(string_list , state_space_param.label)); % see which state space is chosen
set(handles.popupmenu_state_space_selector, 'Value', val) % set the pop-up menu to the selected state space.
end
function handles = Draw_motion_model_panel(handles , motion_model_param)
% This function draws the motion model panel in the GUI figure, based on
% the selected model in the "popupmenu_motion_model_selector".
% following code is for initilizing the state of "pop-up" menu, based on
% the selected motion model.
D = dir('All_motion_models');
all_mm = {D([D.isdir]==0).name};
set(handles.popupmenu_motion_model_selector, 'String', all_mm);
if ~isempty(motion_model_param)
string_list = get(handles.popupmenu_motion_model_selector, 'String'); % get list of possible motion models from the pop-up menu
val = find(strcmpi(string_list , motion_model_param.label)); % see which motion model is chosen
set(handles.popupmenu_motion_model_selector, 'Value', val) % set the pop-up menu to the selected motion model.
end
function handles = Draw_observation_model_panel(handles , observation_model_param)
% This function draws the observation model panel in the GUI figure, based on
% the selected model in the "popupmenu_observation_model_selector".
% following code is for initilizing the state of "pop-up" menu, based on
% the selected oservation model.
D = dir('All_observation_models');
all_om = {D([D.isdir]==0).name};
set(handles.popupmenu_observation_model_selector, 'String', all_om);
if ~isempty(observation_model_param)
string_list = get(handles.popupmenu_observation_model_selector, 'String'); % get list of possible motion models from the pop-up menu
val = find(strcmpi(string_list , observation_model_param.label)); % see which motion model is chosen
set(handles.popupmenu_observation_model_selector, 'Value', val) % set the pop-up menu to the selected motion model.
end
% This function draws the FIRM method panel (so far only a popup menu - not really a panel) in the GUI figure, based on
% the selected method in the "popupmenu_FIRM_method_selector".
function handles = Draw_FIRM_method_panel(handles,problem_param)
D = dir('All_planning_problems');
all_planning = {D([D.isdir]==0).name};
set(handles.popupmenu_FIRM_method_selector, 'String', all_planning);
if ~isempty(problem_param)
% set up the buttons for offline or online phase selection
set(handles.online_planning_phase_button,'Value',problem_param.Online_phase)
% following code is for initilizing the state of "pop-up" menu, based on
% the selected FIRM method.
selected_FIRM_method = problem_param.solver;
string_list = get(handles.popupmenu_FIRM_method_selector, 'String'); % get list of possible FIRM methods from the pop-up menu
val = find(strcmpi(string_list , selected_FIRM_method.label)); % see which FIRM method is chosen
set(handles.popupmenu_FIRM_method_selector, 'Value', val) % set the pop-up menu to the selected FIRM method.
end
% following code is useful if you want to give the user the freedom to set
% some parameters of the FIRM method. You have to have a "panel" for the
% FIRM method in your GUI. Then, design a edit box for each parameter and
% let the user set its value. A "commented" example has been already done
% for the "motion model panel".
% all_objects_in_FIRM_method_panel = get(handles.panel_FIRM_method,'Children');
% set(all_objects_in_FIRM_method_panel,'visible','off'); % Here, we make all the objects in the motion model invisible.
% For the rest of this code follow the convention in the design of the
% "panel" for the motion model.
function handles = Draw_simulator_panel(handles,simulator_param)
D = dir('All_Simulators');
all_simulators = {D([D.isdir]==0).name};
set(handles.popupmenu_simulator, 'String', all_simulators);
if ~isempty(simulator_param)
% following code is for initilizing the state of "pop-up" menu, based on
% the selected simulator method.
selected_sim_label = simulator_param.label;
string_list = get(handles.popupmenu_simulator, 'String'); % get list of possible FIRM methods from the pop-up menu
val = find(strcmpi(string_list , selected_sim_label)); % see which FIRM method is chosen
set(handles.popupmenu_simulator, 'Value', val) % set the pop-up menu to the selected FIRM method.
end
% --- Executes on key release with focus on SFMP_GUI_fig_tag or any of its controls.
function SFMP_GUI_fig_tag_WindowKeyReleaseFcn(hObject, eventdata, handles)
% hObject handle to SFMP_GUI_fig_tag (see GCBO)
% eventdata structure with the following fields (see FIGURE)
% Key: name of the key that was released, in lower case
% Character: character interpretation of the key(s) that was released
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) released
% handles structure with handles and user data (see GUIDATA)
% For some reason, which is not known to me at this point, without this
% function when we press a keyboard key on the GUI figure it returns an
% error. So, I have to have this function here, although it is empty! I
% guess it has to do something with the "uiwait" function.
function edit_parameter_file_address_Callback(hObject, eventdata, handles)
% hObject handle to edit_parameter_file_address (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_parameter_file_address as text
% str2double(get(hObject,'String')) returns contents of edit_parameter_file_address as a double
% --- Executes during object creation, after setting all properties.
function edit_parameter_file_address_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_parameter_file_address (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton_browse.
function pushbutton_browse_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_browse (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Callback called when the icon file selection button is pressed
filespec = {'*.mat', 'MATLAB MAT files (*.mat)'};
[filename, pathname] = uigetfile(filespec, 'Pick a parameter file', 'output');
if ~isequal(filename,0)
LoadFileName =fullfile(pathname, filename);
set(handles.edit_parameter_file_address,'String',LoadFileName);
load(LoadFileName, 'par')
handles.LoadFileName = LoadFileName;
handles.old_par = par;
Update_GUI_fields(handles,par);
% Update handles structure
guidata(hObject, handles);
end
function Update_GUI_fields(handles,old_par)
try
old_state_space_param = old_par.state_parameters;
catch %#ok<CTCH>
old_state_space_param = [];
end
handles = Draw_state_space_panel(handles , old_state_space_param); % updates the "motion_model" panel (draws the panel based on initially selected motion model.)
try
old_motion_model_param = old_par.motion_model_parameters;
catch %#ok<CTCH>
old_motion_model_param = [];
end
handles = Draw_motion_model_panel(handles , old_motion_model_param); % updates the "motion_model" panel (draws the panel based on initially selected motion model.)
try
old_observation_model_param = old_par.observation_model_parameters;
catch %#ok<CTCH>
old_observation_model_param = [];
end
handles = Draw_observation_model_panel(handles , old_observation_model_param); % updates the "motion_model" panel (draws the panel based on initially selected motion model.)
try
planning_problem_parameters = old_par.planning_problem_parameters;
catch %#ok<CTCH>
planning_problem_parameters = [];
end
handles = Draw_FIRM_method_panel(handles , planning_problem_parameters); % Right now, we only have the "popup_menu"; so, there is no panel really.
try
old_simulator_parameters = old_par.simulator_parameters;
catch %#ok<CTCH>
old_simulator_parameters = [];
end
handles = Draw_simulator_panel(handles, old_simulator_parameters);
guidata(gcf, handles);
% --- Executes on button press in checkbox_obstacles.
function checkbox_obstacles_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_obstacles (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_obstacles
% --- Executes on selection change in popupmenu_observation_model_selector.
function popupmenu_observation_model_selector_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_observation_model_selector (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_observation_model_selector contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_observation_model_selector
% --- Executes during object creation, after setting all properties.
function popupmenu_observation_model_selector_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_observation_model_selector (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in checkbox_landmarks.
function checkbox_landmarks_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_landmarks (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_landmarks
% --- Executes on selection change in popupmenu_FIRM_method_selector.
function popupmenu_FIRM_method_selector_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_FIRM_method_selector (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_FIRM_method_selector contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_FIRM_method_selector
% --- Executes during object creation, after setting all properties.
function popupmenu_FIRM_method_selector_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_FIRM_method_selector (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% This function is for gathering the parameters from the user through GUI.
function par_new = gather_parameteres_from_GUI(handles)
%=========== State Space Parameters
contents = cellstr(get(handles.popupmenu_state_space_selector,'String')); % returns popupmenu_state_space_selector contents as cell array
par_new.state_parameters.label = contents{get(handles.popupmenu_state_space_selector,'Value')}; % returns selected item from popupmenu_state_space_selector
%=========== Motion Model Parameters
contents = cellstr(get(handles.popupmenu_motion_model_selector,'String')); % returns popupmenu_motion_model_selector contents as cell array
par_new.motion_model_parameters.label = contents{get(handles.popupmenu_motion_model_selector,'Value')}; % returns selected item from popupmenu_motion_model_selector
%=========== Observation Model Parameters
contents = cellstr(get(handles.popupmenu_observation_model_selector,'String')); % returns popupmenu_motion_model_selector contents as cell array
par_new.observation_model_parameters.label = contents{get(handles.popupmenu_observation_model_selector,'Value')}; % returns selected item from popupmenu_motion_model_selector
par_new.observation_model_parameters.interactive_OM = get(handles.checkbox_landmarks,'Value');
%=========== Planning Problem (Solver) Parameters
contents = cellstr(get(handles.popupmenu_FIRM_method_selector,'String')); % returns popupmenu_FIRM_Node_selector contents as cell array
par_new.planning_problem_parameters.solver.label = contents{get(handles.popupmenu_FIRM_method_selector,'Value')}; % returns selected item from popupmenu_FIRM_Node_selector
par_new.planning_problem_parameters.Offline_construction_phase = get(handles.offline_construction_phase_button,'Value');
par_new.planning_problem_parameters.Online_phase = get(handles.online_planning_phase_button,'Value');
%========== Simulator Parameters
contents = cellstr(get(handles.popupmenu_simulator,'String')); % returns popupmenu_motion_model_selector contents as cell array
par_new.simulator_parameters.label = contents{get(handles.popupmenu_simulator,'Value')}; % returns selected item from popupmenu_motion_model_selector
par_new.simulator_parameters.intractive_obst = get(handles.checkbox_obstacles,'Value'); % returns toggle state of "checkbox_obstacles"
par_new.simulator_parameters.interactive_PRM = get(handles.checkbox_manual_PRM_2D_nodes,'Value'); % returns toggle state of "checkbox_manual_PRM_2D_nodes"
% --- Executes on button press in checkbox_manual_PRM_2D_nodes.
function checkbox_manual_PRM_2D_nodes_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_manual_PRM_2D_nodes (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_manual_PRM_2D_nodes
% --- Executes on selection change in popupmenu_simulator.
function popupmenu_simulator_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_simulator (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_simulator contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_simulator
% --- Executes during object creation, after setting all properties.
function popupmenu_simulator_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_simulator (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% simulator_lables = {D([D.isdir]==0).name};
% --- Executes on selection change in popupmenu_state_space_selector.
function popupmenu_state_space_selector_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_state_space_selector (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_state_space_selector contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_state_space_selector
% --- Executes during object creation, after setting all properties.
function popupmenu_state_space_selector_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_state_space_selector (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
|
github
|
mubeipeng/focused_slam-master
|
Input_XML_reader.m
|
.m
|
focused_slam-master/FIRM/General_functions/Input_XML_reader.m
| 19,447 |
utf_8
|
1604fa089fac9096c424f92268f5e68e
|
function par_new = Input_XML_reader(old_par, par_new_from_GUI)
% Parameters (they have to go into an XML)
%=======================================================================================
par_new = par_new_from_GUI; % first we copy the newly provided parameters from GUI
%=========== Random seed
seed = 502;
rand('state',seed); %#ok<RAND>
randn('state',seed); %#ok<RAND>
par_new.seed = seed;
%=========== Stabilizer Parameters
par_new.stabilizer_parameters.max_stopping_time = 50;
par_new.stabilizer_parameters.draw_cov_centered_on_nominal = 0;
%=========== MonteCarlo Simulation
par_new.par_n = 20; % number of particles
par_new.cost_gain = 10;
%=========== (LQR design) Node and Edge controller
par_new.LQR_cost_coefs=[0.03*0.1 , 0.03*0.1 , 0.1]; % first entry is the "final state cost coeff". The second is the "state cost coeff", and the third is the "control cost coeff".
par_new.state_cost_ratio_for_stationary_case = 5; % note that "state_cost" is for the trajectory tracking. Usually in point stabilization, we need more force on state and less on control. So, we multiply the "state_cost" to an appropriate ratio, i.e., "state_cost_ratio_for_stationary_case". Note that this ratio has to be greater than 1.
par_new.control_cost_ratio_for_stationary_case = 1/5; % note that "control_cost" is for the trajectory tracking. Usually in point stabilization, we need more force on state and less on control. So, we multiply the "control_cost" to an appropriate ratio, i.e., "control_cost_ratio_for_stationary_case". Note that this ratio has to be LESS than 1.
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%==============================================================================================================
%==============================================================================================================
%==============================================================================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmpi(par_new.motion_model_parameters.label,'Multi RandomWalk robots')
n = par_new.state_parameters.num_robots;
par_new.valid_linearization_domain = repmat([3;3]*4 , n , 1);
elseif strcmpi(par_new.motion_model_parameters.label,'Multi Omni-directional robots')
n = par_new.state_parameters.num_robots;
par_new.valid_linearization_domain = repmat([3;3;75*pi/180]*3 , n , 1);
elseif strcmpi(par_new.motion_model_parameters.label,'Revolute joint 8arm manipulator')
par_new.valid_linearization_domain = ones(par_new.state_parameters.stateDim , 1)*75*pi/180;
elseif strcmpi(par_new.motion_model_parameters.label,'Dynamical planar 8arm manipulator')
par_new.valid_linearization_domain = [ones(par_new.state_parameters.stateDim/2 , 1)*75*pi/180; ones(par_new.state_parameters.stateDim/2 , 1)*1000*pi/180];
elseif strcmpi(par_new.motion_model_parameters.label, 'FixedWing Aircraft')
par_new.valid_linearization_domain = [3;3;3;1;1;1;1]*3;
elseif strcmpi(par_new.motion_model_parameters.label,'Quadrotor')
par_new.valid_linearization_domain = [3;3;3;75*pi/180;75*pi/180;75*pi/180;inf;inf;inf;inf;inf;inf];
else
par_new.valid_linearization_domain = [3;3;75*pi/180]*3;
end
%=========== HBRM cost
par_new.alpha_for_HBRM_cost = [0.01,0.1,1]; % respectively, corresponding to "stopping_time", "success probability", and "filtering_cost".
%=========== Roadmap Type and Construction
par_new.RoadMap = 'FIRM'; % This parameter can be HBRM or FIRM
par_new.No_history = 1;
par_new.No_plot = 1; % this is for plots in construction phase. The execution phase plots are different.
%=========== PRM parameters
par_new.PRM_parameters.neighboring_distance_threshold = 30; %* 1.25 * 1000;% * 0.3;
par_new.PRM_parameters.PRM_node_text = 1; % if this is one, the number of nodes will be written on the figure.
par_new.PRM_parameters.PRM_node_plot_properties = {'RobotShape','triangle','robotSize',0.8};% {'RobotShape','triangle','robotSize',2};
par_new.PRM_parameters.draw_edges_flag = 1;
% =========== Orbit parameters
% par_new.PRM_parameters.orbit_text_size = 12; % Default value for "OrbitTextSize" property.
% par_new.PRM_parameters.orbit_text_shift = 0.8; % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, we return it back by this amount.
% par_new.PRM_parameters.orbit_text_color = 'b'; % Default value for "OrbitTextColor" property.
% par_new.PRM_parameters.orbit_robot_shape = 'triangle'; % The shape of robot (to draw trajectories and to show direction of edges and orbits)
% par_new.PRM_parameters.orbit_robot_size = 1; % Robot size on orbits (to draw trajectories and to show direction of edges and orbits)
par_new.PRM_parameters.node_to_orbit_trajectories_flag = 1; % Make it one if you want to see the node-to-orbit trajectories. Zero, otherwise.
% par_new.PRM_parameters.orbit_color = 'k'; % User-provided value for "orbit_color" property.
% par_new.PRM_parameters.orbit_width = 2; % User-provided value for "orbit_width" property.
% par_new.PRM_parameters.orbit_trajectory_flag = 0; % Make it one if you want to see the orbit trajectories. Zero, otherwise.
% par_new.PRM_parameters.edge_spec = '-b'; % edge line color and type
% par_new.PRM_parameters.edge_width = 2; % edge line width
par_new.PRM_parameters.num_nodes_on_orbits = 3; % number of nodes on each orbit
% par_new.PRM_parameters.orbit_length = 50; % the length of orbit (orbit's time period)
% par_new.PRM_parameters.orbit_radius = 4;
%=========== Dynamic Programming parameters
par_new.initial_values = 100;
par_new.initial_value_goal = 500;
par_new.failure_cost_to_go = 15;
par_new.selected_nodes_for_plotting_feedback_pi = [];%setdiff(1:22, [4,7,19,17,8,20,12,3,6,21]);
par_new.DP_convergence_threshold = 1e-2;
%=========== Replanning
par_new.replanning = 0;
par_new.goBack_to_nearest_node = 0; % this does not work correctly, yet.
%=========== FIRM Node Parameters
if strcmpi(par_new.motion_model_parameters.label,'Multi RandomWalk robots')
error('these parameters should go into the class')
n = par_new.state_parameters.num_robots;
tmp_vector = repmat( [0.08 ; 0.08 ] , n , 1);
par_new.FIRM_node_parameters.mean_neighborhood_size = tmp_vector*mean_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian.
par_new.FIRM_node_parameters.cov_neighborhood_size = tmp_vector*tmp_vector'*cov_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian. % This is a matrix.
% Hbliefe convergece-related parameters:
GHb_conv_reg_thresh = tmp_vector*GHb_magnifyikng_coeff; % distance threshold for either Xg_mean or Xest_mean_mean; Xdist has to be a column vector
elseif strcmpi(par_new.motion_model_parameters.label,'Multi Omni-directional robots')
error('these parameters should go into the class')
n = par_new.state_parameters.num_robots;
tmp_vector = repmat( [0.08 ; 0.08 ; 3 *pi/180 ] , n , 1);
par_new.FIRM_node_parameters.mean_neighborhood_size = tmp_vector*mean_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian.
par_new.FIRM_node_parameters.cov_neighborhood_size = tmp_vector*tmp_vector'*cov_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian. % This is a matrix.
% Hbliefe convergece-related parameters:
GHb_conv_reg_thresh = tmp_vector*GHb_magnifyikng_coeff; % distance threshold for either Xg_mean or Xest_mean_mean; Xdist has to be a column vector
elseif strcmpi(par_new.motion_model_parameters.label,'Revolute joint 8arm manipulator')
error('these parameters should go into the class')
tmp_vector = ones(par_new.state_parameters.stateDim , 1)*5*pi/180;
par_new.FIRM_node_parameters.mean_neighborhood_size = tmp_vector*mean_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian.
par_new.FIRM_node_parameters.cov_neighborhood_size = tmp_vector*tmp_vector'*cov_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian. % This is a matrix.
% Hbliefe convergece-related parameters:
GHb_conv_reg_thresh = tmp_vector*GHb_magnifyikng_coeff; % distance threshold for either Xg_mean or Xest_mean_mean; Xdist has to be a column vector
elseif strcmpi(par_new.motion_model_parameters.label,'Dynamical planar 8arm manipulator')
error('these parameters should go into the class')
tmp_vector = [ones(par_new.state_parameters.stateDim/2 , 1)*5*pi/180;ones(par_new.state_parameters.stateDim/2 , 1)*10*pi/180];
par_new.FIRM_node_parameters.mean_neighborhood_size = tmp_vector*mean_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian.
par_new.FIRM_node_parameters.cov_neighborhood_size = tmp_vector*tmp_vector'*cov_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian. % This is a matrix.
% Hbliefe convergece-related parameters:
GHb_conv_reg_thresh = tmp_vector*GHb_magnifyikng_coeff; % distance threshold for either Xg_mean or Xest_mean_mean; Xdist has to be a column vector
elseif strcmpi(par_new.motion_model_parameters.label,'FixedWing Aircraft')
error('these parameters should go into the class')
tmp_vector = repmat( [0.1 ; 0.1 ; 0.1; 0.1 ; 0.1 ; 0.1 ; 0.1] , 1 , 1);
par_new.FIRM_node_parameters.mean_neighborhood_size = tmp_vector*mean_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian.
par_new.FIRM_node_parameters.cov_neighborhood_size = tmp_vector*tmp_vector'*cov_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian. % This is a matrix.
% Hbliefe convergece-related parameters:
GHb_conv_reg_thresh = tmp_vector*GHb_magnifyikng_coeff; % distance threshold for either Xg_mean or Xest_mean_mean; Xdist has to be a column vector
elseif strcmpi(par_new.motion_model_parameters.label,'Quadrotor')
error('these parameters should go into the class')
tmp_vector = [1 ; 1 ; 1; 20*pi/180 ; 20*pi/180 ; 20*pi/180 ; inf ; inf ; inf ; inf ; inf ; inf];
par_new.FIRM_node_parameters.mean_neighborhood_size = tmp_vector*mean_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian.
par_new.FIRM_node_parameters.cov_neighborhood_size = tmp_vector*tmp_vector'*cov_neighb_magnifying_coeff ; % note that the last entry, ie theta's neighborhood, has to be in radian. % This is a matrix.
% Hbliefe convergece-related parameters:
GHb_conv_reg_thresh = tmp_vector*GHb_magnifyikng_coeff; % distance threshold for either Xg_mean or Xest_mean_mean; Xdist has to be a column vector
else
end
%=======================================================================================
%=======================================================================================
% End of Parameters section!
end
function [motion_model_parameters , state_parameters] = gather_state_and_motion_model_parameters(old_par, selected_motion_model)
% --- This function returns the parameters needed in the selected motion model.
if strcmpi(selected_motion_model,'Omni-directional three wheel robot')
elseif strcmpi(selected_motion_model,'Multi Omni-directional robots')
error('these parameters should go into the class')
n = 2;
state_parameters.num_robots=n;
state_parameters.stateDim = 3*n;
state_parameters.sup_norm_weights_nonNormalized = repmat(1./[1 ; 1 ; inf] , n , 1); % You can think of the right-most vector (in the denominator) as the ractangular neighborhood used in finding neighbor nodes in constructing PRM graph. Note that this must be a column vector.
motion_model_parameters.controlDim=3*n;
motion_model_parameters.robot_link_length = 0.2; %str2double(get(handles.edit_omni_link_length,'String'));
motion_model_parameters.dt = 0.1;
motion_model_parameters.V_const_path_team=ones(1,n); % nominal linear velocity
motion_model_parameters.omega_const_path_team=ones(1,n)*90*pi/180; % nominal angular velocity % note that this is the turning angle in one second. So, it will be multiplied by "dt" to return the turning angle in "dt".
motion_model_parameters.eta_u_omni_team = zeros(3*n,1); % %str2num(get(handles.edit_eta_u_omni,'String'))'; %#ok<ST2NM> % note that eta_u in this case is a three by one vector, reprensing eta for velocity of each of omni-dir wheels.
motion_model_parameters.sigma_b_u_omni_team = zeros(3*n,1); % % note that sigma_b_u in this case is a three by one vector, reprensing sigma_b (bias variance) for linear velocity and angular velocity.
P_rootsqaure_Wg_diags_team = repmat( [0.2 ; 0.2 ; 4*pi/180]*2, n ,1 ); % this is just a vector
motion_model_parameters.P_Wg_team = diag(P_rootsqaure_Wg_diags_team.^2);
elseif strcmpi(selected_motion_model,'Multi RandomWalk robots')
error('these parameters should go into the class')
n = 1;
state_parameters.num_robots=n;
state_parameters.stateDim = 2*n;
state_parameters.sup_norm_weights_nonNormalized = repmat(1./[1 ; 1 ] , n , 1); % You can think of the right-most vector (in the denominator) as the ractangular neighborhood used in finding neighbor nodes in constructing PRM graph. Note that this must be a column vector.
motion_model_parameters.controlDim=2*n;
motion_model_parameters.dt = 0.1;
motion_model_parameters.V_const_path_team=ones(2*n,1)*20; % nominal linear velocity
P_rootsqaure_Wg_diags_team = repmat( [0.2 ; 0.2]*2, n ,1 ); % this is just a vector
motion_model_parameters.P_Wg_team = diag(P_rootsqaure_Wg_diags_team.^2);
elseif strcmpi(selected_motion_model,'Unicycle')
error('these parameters should go into the class')
state_parameters.stateDim = 3;
state_parameters.sup_norm_weights_nonNormalized = 1./[1 ; 1 ; inf]; % You can think of the right-most vector (in the denominator) as the ractangular neighborhood used in finding neighbor nodes in constructing PRM graph. Note that this must be a column vector.
motion_model_parameters.controlDim=2;
motion_model_parameters.base_length = 13; %str2double(get(handles.edit_unicycle_base_length,'String'));
motion_model_parameters.dt = 0.1;
motion_model_parameters.V_const_path = 4; % nominal linear velocity
motion_model_parameters.omega_const_path=25*pi/180; % nominal angular velocity
motion_model_parameters.eta_u_unicycle = [0; 0]; % %str2num(get(handles.edit_eta_u_unicycle,'String'))'; %#ok<ST2NM> % note that eta_u in this case is a two by one vector, reprensing eta for linear velocity and angular velocity.
motion_model_parameters.sigma_b_u_unicycle = [0; 0]; % % note that sigma_b_u in this case is a two by one vector, reprensing sigma_b (bias variance) for linear velocity and angular velocity.
P_rootsqaure_Wg_diags=[0.2 ; 0.2 ; 4*pi/180];
motion_model_parameters.P_Wg=diag(P_rootsqaure_Wg_diags.^2);
elseif strcmpi(selected_motion_model,'Revolute joint 8arm manipulator')
error('these parameters should go into the class')
n = 8;
state_parameters.num_revolute_joints = n;
state_parameters.stateDim = n;
state_parameters.sup_norm_weights_nonNormalized = ones(n , 1); % You can think of the right-most vector (in the denominator) as the ractangular neighborhood used in finding neighbor nodes in constructing PRM graph. Note that this must be a column vector.
motion_model_parameters.controlDim=n;
elseif strcmpi(selected_motion_model,'Dynamical planar 8arm manipulator')
error('these parameters should go into the class')
n = 16;
state_parameters.num_revolute_joints = n/2;
state_parameters.stateDim = n;
state_parameters.sup_norm_weights_nonNormalized = ones(n , 1); % You can think of the right-most vector (in the denominator) as the ractangular neighborhood used in finding neighbor nodes in constructing PRM graph. Note that this must be a column vector.
motion_model_parameters.controlDim = n/2;
elseif strcmpi(selected_motion_model,'FixedWing Aircraft')
error('these parameters should go into the class')
state_parameters.stateDim = 7;
state_parameters.sup_norm_weights_nonNormalized = ones(state_parameters.stateDim , 1);
disp('state norm for aircraft model needs to be fixed')
motion_model_parameters.controlDim = 4;
motion_model_parameters.dt = 0.1;
motion_model_parameters.eta_u_aircraft = [0.005;0.005;0.005;0.005];%[0.01 ; deg2rad(0.025) ; deg2rad(0.025) ; deg2rad(0.025)];
motion_model_parameters.sigma_b_u_aircraft = [0.02; deg2rad(0.25);deg2rad(0.25); deg2rad(0.25)];%[0.01 ; deg2rad(0.2); deg2rad(0.2); deg2rad(0.2)];
P_rootsqaure_Wg_diags = [0.02 ; 0.02 ; 0.02 ; 0.01 ; 0.01 ; 0.01 ; 0.01];
motion_model_parameters.P_Wg = diag(P_rootsqaure_Wg_diags.^2);
elseif strcmpi(selected_motion_model,'Kuka YouBot Base')
error('these parameters should go into the class')
state_parameters.stateDim = 3;
state_parameters.sup_norm_weights_nonNormalized = 1./[1 ; 1 ; inf]; % You can think of the right-most vector (in the denominator) as the ractangular neighborhood used in finding neighbor nodes in constructing PRM graph. Note that this must be a column vector.
motion_model_parameters.controlDim = 4;
motion_model_parameters.dt = 0.1;
motion_model_parameters.eta_u_KukaBase = [0; 0; 0; 0];
motion_model_parameters.sigma_b_u_KukaBase = [0; 0; 0; 0];
P_rootsqaure_Wg_diags=[0.2 ; 0.2 ; 4*pi/180]*2;
motion_model_parameters.P_Wg=diag(P_rootsqaure_Wg_diags.^2);
motion_model_parameters.distBetweenFrontWheels = 0.158*2; % from YouBot datasheet
motion_model_parameters.distBetweenFrontAndBackWheels = 0.228*2; % from YouBot datasheet
elseif strcmpi(selected_motion_model,'Quadrotor')
error('these parameters should go into the class')
state_parameters.stateDim = 12;
state_parameters.sup_norm_weights_nonNormalized = 1./[1 ; 1 ; 1; inf(9,1)]; % You can think of the right-most vector (in the denominator) as the ractangular neighborhood used in finding neighbor nodes in constructing PRM graph. Note that this must be a column vector.
motion_model_parameters.controlDim = 4;
motion_model_parameters.dt = 0.1;
motion_model_parameters.eta_u_quadrotor = [0; 0; 0; 0]; % str2num(get(handles.eta_u_quadrotor,'String'))'; %#ok<ST2NM> % note that eta_u in this case is a four by one vector, reprensing the dependence of control noise on the magnitude of the control vector.
motion_model_parameters.sigma_b_u_quadrotor = [0; 0; 0; 0]; % note that sigma_b_u in this case is a four by one vector, reprensing sigma_b (bias variance) for the control-independent part of the control noise.
P_rootsqaure_Wg_diags=[0.2 ; 0.2 ; 0.2 ; 0.001 ; 0.001 ; 0.001; 4*pi/180 ; 4*pi/180 ; 4*pi/180 ; 0.001 ; 0.001 ; 0.001];
motion_model_parameters.P_Wg=diag(P_rootsqaure_Wg_diags.^2);
else
motion_model_parameters = []; % Here, we load the "old motion model parameters", so that the old information that we do not change, remains unaffected.
state_parameters = [];
end
end
|
github
|
mubeipeng/focused_slam-master
|
read_wobj.m
|
.m
|
focused_slam-master/FIRM/ExternalToolboxes/WOBJ_toolbox_Version2b/read_wobj.m
| 14,274 |
utf_8
|
00b739173054009ea85cd8029e45dbdf
|
function OBJ=read_wobj(fullfilename)
% Read the objects from a Wavefront OBJ file
%
% OBJ=read_wobj(filename);
%
% OBJ struct containing:
%
% OBJ.vertices : Vertices coordinates
% OBJ.vertices_texture: Texture coordinates
% OBJ.vertices_normal : Normal vectors
% OBJ.vertices_point : Vertice data used for points and lines
% OBJ.material : Parameters from external .MTL file, will contain parameters like
% newmtl, Ka, Kd, Ks, illum, Ns, map_Ka, map_Kd, map_Ks,
% example of an entry from the material object:
% OBJ.material(i).type = newmtl
% OBJ.material(i).data = 'vase_tex'
% OBJ.objects : Cell object with all objects in the OBJ file,
% example of a mesh object:
% OBJ.objects(i).type='f'
% OBJ.objects(i).data.vertices: [n x 3 double]
% OBJ.objects(i).data.texture: [n x 3 double]
% OBJ.objects(i).data.normal: [n x 3 double]
%
% Example,
% OBJ=read_wobj('examples\example10.obj');
% FV.vertices=OBJ.vertices;
% FV.faces=OBJ.objects(3).data.vertices;
% figure, patch(FV,'facecolor',[1 0 0]); camlight
%
% Function is written by D.Kroon University of Twente (June 2010)
verbose=true;
if(exist('fullfilename','var')==0)
[filename, filefolder] = uigetfile('*.obj', 'Read obj-file');
fullfilename = [filefolder filename];
end
filefolder = fileparts( fullfilename);
if(verbose),disp(['Reading Object file : ' fullfilename]); end
% Read the DI3D OBJ textfile to a cell array
file_words = file2cellarray( fullfilename);
% Remove empty cells, merge lines split by "\" and convert strings with values to double
[ftype fdata]= fixlines(file_words);
% Vertex data
vertices=[]; nv=0;
vertices_texture=[]; nvt=0;
vertices_point=[]; nvp=0;
vertices_normal=[]; nvn=0;
material=[];
% Surface data
no=0;
% Loop through the Wavefront object file
for iline=1:length(ftype)
if(mod(iline,10000)==0),
if(verbose),disp(['Lines processed : ' num2str(iline)]); end
end
type=ftype{iline}; data=fdata{iline};
% Switch on data type line
switch(type)
case{'mtllib'}
if(iscell(data))
datanew=[];
for i=1:length(data)
datanew=[datanew data{i}];
if(i<length(data)), datanew=[datanew ' ']; end
end
data=datanew;
end
filename_mtl=fullfile(filefolder,data);
material=readmtl(filename_mtl,verbose);
case('v') % vertices
nv=nv+1;
if(length(data)==3)
% Reserve block of memory
if(mod(nv,10000)==1), vertices(nv+1:nv+10001,1:3)=0; end
% Add to vertices list X Y Z
vertices(nv,1:3)=data;
else
% Reserve block of memory
if(mod(nv,10000)==1), vertices(nv+1:nv+10001,1:4)=0; end
% Add to vertices list X Y Z W
vertices(nv,1:4)=data;
end
case('vp')
% Specifies a point in the parameter space of curve or surface
nvp=nvp+1;
if(length(data)==1)
% Reserve block of memory
if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1)=0; end
% Add to vertices point list U
vertices_point(nvp,1)=data;
elseif(length(data)==2)
% Reserve block of memory
if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1:2)=0; end
% Add to vertices point list U V
vertices_point(nvp,1:2)=data;
else
% Reserve block of memory
if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1:3)=0; end
% Add to vertices point list U V W
vertices_point(nvp,1:3)=data;
end
case('vn')
% A normal vector
nvn=nvn+1; if(mod(nvn,10000)==1), vertices_normal(nvn+1:nvn+10001,1:3)=0; end
% Add to vertices list I J K
vertices_normal(nvn,1:3)=data;
case('vt')
% Vertices Texture Coordinate in photo
% U V W
nvt=nvt+1;
if(length(data)==1)
% Reserve block of memory
if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1)=0; end
% Add to vertices texture list U
vertices_texture(nvt,1)=data;
elseif(length(data)==2)
% Reserve block of memory
if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1:2)=0; end
% Add to vertices texture list U V
vertices_texture(nvt,1:2)=data;
else
% Reserve block of memory
if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1:3)=0; end
% Add to vertices texture list U V W
vertices_texture(nvt,1:3)=data;
end
case('l')
no=no+1; if(mod(no,10000)==1), objects(no+10001).data=0; end
array_vertices=[];
array_texture=[];
for i=1:length(data),
switch class(data)
case 'cell'
tvals=str2double(stringsplit(data{i},'/'));
case 'string'
tvals=str2double(stringsplit(data,'/'));
otherwise
tvals=data(i);
end
val=tvals(1);
if(val<0), val=val+1+nv; end
array_vertices(i)=val;
if(length(tvals)>1),
val=tvals(2);
if(val<0), val=val+1+nvt; end
array_texture(i)=val;
end
end
objects(no).type='l';
objects(no).data.vertices=array_vertices;
objects(no).data.texture=array_texture;
case('f')
no=no+1; if(mod(no,10000)==1), objects(no+10001).data=0; end
array_vertices=[];
array_texture=[];
array_normal=[];
for i=1:length(data);
switch class(data)
case 'cell'
tvals=str2double(stringsplit(data{i},'/'));
case 'string'
tvals=str2double(stringsplit(data,'/'));
otherwise
tvals=data(i);
end
val=tvals(1);
if(val<0), val=val+1+nv; end
array_vertices(i)=val;
if(length(tvals)>1),
if(isfinite(tvals(2)))
val=tvals(2);
if(val<0), val=val+1+nvt; end
array_texture(i)=val;
end
end
if(length(tvals)>2),
val=tvals(3);
if(val<0), val=val+1+nvn; end
array_normal(i)=val;
end
end
% A face of more than 3 indices is always split into
% multiple faces of only 3 indices.
objects(no).type='f';
findex=1:min (3,length(array_vertices));
objects(no).data.vertices=array_vertices(findex);
if(~isempty(array_texture)),objects(no).data.texture=array_texture(findex); end
if(~isempty(array_normal)),objects(no).data.normal=array_normal(findex); end
for i=1:length(array_vertices)-3;
no=no+1; if(mod(no,10000)==1), objects(no+10001).data=0; end
findex=[1 2+i 3+i];
findex(findex>length(array_vertices))=findex(findex>length(array_vertices))-length(array_vertices);
objects(no).type='f';
objects(no).data.vertices=array_vertices(findex);
if(~isempty(array_texture)),objects(no).data.texture=array_texture(findex); end
if(~isempty(array_normal)),objects(no).data.normal=array_normal(findex); end
end
case{'#','$'}
% Comment
tline=' %';
if(iscell(data))
for i=1:length(data), tline=[tline ' ' data{i}]; end
else
tline=[tline data];
end
if(verbose), disp(tline); end
case{''}
otherwise
no=no+1;
if(mod(no,10000)==1), objects(no+10001).data=0; end
objects(no).type=type;
objects(no).data=data;
end
end
% Initialize new object list, which will contain the "collapsed" objects
objects2(no).data=0;
index=0;
i=0;
while (i<no), i=i+1;
type=objects(i).type;
% First face found
if((length(type)==1)&&(type(1)=='f'))
% Get number of faces
for j=i:no
type=objects(j).type;
if((length(type)~=1)||(type(1)~='f'))
j=j-1; break;
end
end
numfaces=(j-i)+1;
index=index+1;
objects2(index).type='f';
% Process last face first to allocate memory
objects2(index).data.vertices(numfaces,:)= objects(i).data.vertices;
if(isfield(objects(i).data,'texture'))
objects2(index).data.texture(numfaces,:) = objects(i).data.texture;
else
objects2(index).data.texture=[];
end
if(isfield(objects(i).data,'normal'))
objects2(index).data.normal(numfaces,:) = objects(i).data.normal;
else
objects2(index).data.normal=[];
end
% All faces to arrays
for k=1:numfaces
objects2(index).data.vertices(k,:)= objects(i+k-1).data.vertices;
if(isfield(objects(i).data,'texture'))
objects2(index).data.texture(k,:) = objects(i+k-1).data.texture;
end
if(isfield(objects(i).data,'normal'))
objects2(index).data.normal(k,:) = objects(i+k-1).data.normal;
end
end
i=j;
else
index=index+1;
objects2(index).type=objects(i).type;
objects2(index).data=objects(i).data;
end
end
% Add all data to output struct
OBJ.objects=objects2(1:index);
OBJ.material=material;
OBJ.vertices=vertices(1:nv,:);
OBJ.vertices_point=vertices_point(1:nvp,:);
OBJ.vertices_normal=vertices_normal(1:nvn,:);
OBJ.vertices_texture=vertices_texture(1:nvt,:);
if(verbose),disp('Finished Reading Object file'); end
function twords=stringsplit(tline,tchar)
% Get start and end position of all "words" separated by a char
i=find(tline(2:end-1)==tchar)+1; i_start=[1 i+1]; i_end=[i-1 length(tline)];
% Create a cell array of the words
twords=cell(1,length(i_start)); for j=1:length(i_start), twords{j}=tline(i_start(j):i_end(j)); end
function file_words=file2cellarray(filename)
% Open a DI3D OBJ textfile
fid=fopen(filename,'r');
file_text=fread(fid, inf, 'uint8=>char')';
fclose(fid);
file_lines = regexp(file_text, '\n+', 'split');
file_words = regexp(file_lines, '\s+', 'split');
function [ftype fdata]=fixlines(file_words)
ftype=cell(size(file_words));
fdata=cell(size(file_words));
iline=0; jline=0;
while(iline<length(file_words))
iline=iline+1;
twords=removeemptycells(file_words{iline});
if(~isempty(twords))
% Add next line to current line when line end with '\'
while(strcmp(twords{end},'\')&&iline<length(file_words))
iline=iline+1;
twords(end)=[];
twords=[twords removeemptycells(file_words{iline})];
end
% Values to double
type=twords{1};
stringdold=true;
j=0;
switch(type)
case{'#','$'}
for i=2:length(twords)
j=j+1; twords{j}=twords{i};
end
otherwise
for i=2:length(twords)
str=twords{i};
val=str2double(str);
stringd=~isfinite(val);
if(stringd)
j=j+1; twords{j}=str;
else
if(stringdold)
j=j+1; twords{j}=val;
else
twords{j}=[twords{j} val];
end
end
stringdold=stringd;
end
end
twords(j+1:end)=[];
jline=jline+1;
ftype{jline}=type;
if(length(twords)==1), twords=twords{1}; end
fdata{jline}=twords;
end
end
ftype(jline+1:end)=[];
fdata(jline+1:end)=[];
function b=removeemptycells(a)
j=0; b={};
for i=1:length(a);
if(~isempty(a{i})),j=j+1; b{j}=a{i}; end;
end
function objects=readmtl(filename_mtl,verbose)
if(verbose),disp(['Reading Material file : ' filename_mtl]); end
file_words=file2cellarray(filename_mtl);
% Remove empty cells, merge lines split by "\" and convert strings with values to double
[ftype fdata]= fixlines(file_words);
% Surface data
objects.type(length(ftype))=0;
objects.data(length(ftype))=0;
no=0;
% Loop through the Wavefront object file
for iline=1:length(ftype)
type=ftype{iline}; data=fdata{iline};
% Switch on data type line
switch(type)
case{'#','$'}
% Comment
tline=' %';
if(iscell(data))
for i=1:length(data), tline=[tline ' ' data{i}]; end
else
tline=[tline data];
end
if(verbose), disp(tline); end
case{''}
otherwise
no=no+1;
if(mod(no,10000)==1), objects(no+10001).data=0; end
objects(no).type=type;
objects(no).data=data;
end
end
objects=objects(1:no);
if(verbose),disp('Finished Reading Material file'); end
|
github
|
mubeipeng/focused_slam-master
|
write_wobj.m
|
.m
|
focused_slam-master/FIRM/ExternalToolboxes/WOBJ_toolbox_Version2b/write_wobj.m
| 8,180 |
utf_8
|
0dc52399139f80c689fb89cddc5ebb19
|
function write_wobj(OBJ,fullfilename)
% Write objects to a Wavefront OBJ file
%
% write_wobj(OBJ,filename);
%
% OBJ struct containing:
%
% OBJ.vertices : Vertices coordinates
% OBJ.vertices_texture: Texture coordinates
% OBJ.vertices_normal : Normal vectors
% OBJ.vertices_point : Vertice data used for points and lines
% OBJ.material : Parameters from external .MTL file, will contain parameters like
% newmtl, Ka, Kd, Ks, illum, Ns, map_Ka, map_Kd, map_Ks,
% example of an entry from the material object:
% OBJ.material(i).type = newmtl
% OBJ.material(i).data = 'vase_tex'
% OBJ.objects : Cell object with all objects in the OBJ file,
% example of a mesh object:
% OBJ.objects(i).type='f'
% OBJ.objects(i).data.vertices: [n x 3 double]
% OBJ.objects(i).data.texture: [n x 3 double]
% OBJ.objects(i).data.normal: [n x 3 double]
%
% example reading/writing,
%
% OBJ=read_wobj('examples\example10.obj');
% write_wobj(OBJ,'test.obj');
%
% example isosurface to obj-file,
%
% % Load MRI scan
% load('mri','D'); D=smooth3(squeeze(D));
% % Make iso-surface (Mesh) of skin
% FV=isosurface(D,1);
% % Calculate Iso-Normals of the surface
% N=isonormals(D,FV.vertices);
% L=sqrt(N(:,1).^2+N(:,2).^2+N(:,3).^2)+eps;
% N(:,1)=N(:,1)./L; N(:,2)=N(:,2)./L; N(:,3)=N(:,3)./L;
% % Display the iso-surface
% figure, patch(FV,'facecolor',[1 0 0],'edgecolor','none'); view(3);camlight
% % Invert Face rotation
% FV.faces=[FV.faces(:,3) FV.faces(:,2) FV.faces(:,1)];
%
% % Make a material structure
% material(1).type='newmtl';
% material(1).data='skin';
% material(2).type='Ka';
% material(2).data=[0.8 0.4 0.4];
% material(3).type='Kd';
% material(3).data=[0.8 0.4 0.4];
% material(4).type='Ks';
% material(4).data=[1 1 1];
% material(5).type='illum';
% material(5).data=2;
% material(6).type='Ns';
% material(6).data=27;
%
% % Make OBJ structure
% clear OBJ
% OBJ.vertices = FV.vertices;
% OBJ.vertices_normal = N;
% OBJ.material = material;
% OBJ.objects(1).type='g';
% OBJ.objects(1).data='skin';
% OBJ.objects(2).type='usemtl';
% OBJ.objects(2).data='skin';
% OBJ.objects(3).type='f';
% OBJ.objects(3).data.vertices=FV.faces;
% OBJ.objects(3).data.normal=FV.faces;
% write_wobj(OBJ,'skinMRI.obj');
%
% Function is written by D.Kroon University of Twente (June 2010)
if(exist('fullfilename','var')==0)
[filename, filefolder] = uiputfile('*.obj', 'Write obj-file');
fullfilename = [filefolder filename];
end
[filefolder,filename] = fileparts( fullfilename);
comments=cell(1,4);
comments{1}=' Produced by Matlab Write Wobj exporter ';
comments{2}='';
fid = fopen(fullfilename,'w');
write_comment(fid,comments);
if(isfield(OBJ,'material')&&~isempty(OBJ.material))
filename_mtl=fullfile(filefolder,[filename '.mtl']);
fprintf(fid,'mtllib %s\n',filename_mtl);
write_MTL_file(filename_mtl,OBJ.material)
end
if(isfield(OBJ,'vertices')&&~isempty(OBJ.vertices))
write_vertices(fid,OBJ.vertices,'v');
end
if(isfield(OBJ,'vertices_point')&&~isempty(OBJ.vertices_point))
write_vertices(fid,OBJ.vertices_point,'vp');
end
if(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal))
write_vertices(fid,OBJ.vertices_normal,'vn');
end
if(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture))
write_vertices(fid,OBJ.vertices_texture,'vt');
end
for i=1:length(OBJ.objects)
type=OBJ.objects(i).type;
data=OBJ.objects(i).data;
switch(type)
case 'usemtl'
fprintf(fid,'usemtl %s\n',data);
case 'f'
check1=(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture));
check2=(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal));
if(check1&&check2)
for j=1:size(data.vertices,1)
fprintf(fid,'f %d/%d/%d',data.vertices(j,1),data.texture(j,1),data.normal(j,1));
fprintf(fid,' %d/%d/%d', data.vertices(j,2),data.texture(j,2),data.normal(j,2));
fprintf(fid,' %d/%d/%d\n', data.vertices(j,3),data.texture(j,3),data.normal(j,3));
end
elseif(check1)
for j=1:size(data.vertices,1)
fprintf(fid,'f %d/%d',data.vertices(j,1),data.texture(j,1));
fprintf(fid,' %d/%d', data.vertices(j,2),data.texture(j,2));
fprintf(fid,' %d/%d\n', data.vertices(j,3),data.texture(j,3));
end
elseif(check2)
for j=1:size(data.vertices,1)
fprintf(fid,'f %d//%d',data.vertices(j,1),data.normal(j,1));
fprintf(fid,' %d//%d', data.vertices(j,2),data.normal(j,2));
fprintf(fid,' %d//%d\n', data.vertices(j,3),data.normal(j,3));
end
else
for j=1:size(data.vertices,1)
fprintf(fid,'f %d %d %d\n',data.vertices(j,1),data.vertices(j,2),data.vertices(j,3));
end
end
otherwise
fprintf(fid,'%s ',type);
if(iscell(data))
for j=1:length(data)
if(ischar(data{j}))
fprintf(fid,'%s ',data{j});
else
fprintf(fid,'%0.5g ',data{j});
end
end
elseif(ischar(data))
fprintf(fid,'%s ',data);
else
for j=1:length(data)
fprintf(fid,'%0.5g ',data(j));
end
end
fprintf(fid,'\n');
end
end
fclose(fid);
function write_MTL_file(filename,material)
fid = fopen(filename,'w');
comments=cell(1,2);
comments{1}=' Produced by Matlab Write Wobj exporter ';
comments{2}='';
write_comment(fid,comments);
for i=1:length(material)
type=material(i).type;
data=material(i).data;
switch(type)
case('newmtl')
fprintf(fid,'%s ',type);
fprintf(fid,'%s\n',data);
case{'Ka','Kd','Ks'}
fprintf(fid,'%s ',type);
fprintf(fid,'%5.5f %5.5f %5.5f\n',data);
case('illum')
fprintf(fid,'%s ',type);
fprintf(fid,'%d\n',data);
case {'Ns','Tr','d'}
fprintf(fid,'%s ',type);
fprintf(fid,'%5.5f\n',data);
otherwise
fprintf(fid,'%s ',type);
if(iscell(data))
for j=1:length(data)
if(ischar(data{j}))
fprintf(fid,'%s ',data{j});
else
fprintf(fid,'%0.5g ',data{j});
end
end
elseif(ischar(data))
fprintf(fid,'%s ',data);
else
for j=1:length(data)
fprintf(fid,'%0.5g ',data(j));
end
end
fprintf(fid,'\n');
end
end
comments=cell(1,2);
comments{1}='';
comments{2}=' EOF';
write_comment(fid,comments);
fclose(fid);
function write_comment(fid,comments)
for i=1:length(comments), fprintf(fid,'# %s\n',comments{i}); end
function write_vertices(fid,V,type)
switch size(V,2)
case 1
for i=1:size(V,1)
fprintf(fid,'%s %5.5f\n', type, V(i,1));
end
case 2
for i=1:size(V,1)
fprintf(fid,'%s %5.5f %5.5f\n', type, V(i,1), V(i,2));
end
case 3
for i=1:size(V,1)
fprintf(fid,'%s %5.5f %5.5f %5.5f\n', type, V(i,1), V(i,2), V(i,3));
end
otherwise
end
switch(type)
case 'v'
fprintf(fid,'# %d vertices \n', size(V,1));
case 'vt'
fprintf(fid,'# %d texture verticies \n', size(V,1));
case 'vn'
fprintf(fid,'# %d normals \n', size(V,1));
otherwise
fprintf(fid,'# %d\n', size(V,1));
end
|
github
|
mubeipeng/focused_slam-master
|
steerLinearSystembyLP.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/steerLinearSystembyLP.m
| 3,471 |
utf_8
|
1386af9e186eab89e654ec5da01f1c1a
|
%%%%%%%%%% Solve an LP to steer a Linear System %%%%%%%
function [x_seq,u_seq] = steerLinearSystembyLP(A,B,lower,upper,x_init,x_final,dt,numberOfSteps)
% Get dimensions
[stateDim,inputDim] = size(B);
solDim = stateDim*numberOfSteps + inputDim*(numberOfSteps-1);
% Initialize solution
x_seq = zeros(stateDim,numberOfSteps);
u_seq = zeros(inputDim,numberOfSteps-1);
% Indexing goes like this
% State vector, x = [x_1;x_2;...;x_stateDim]
% Input Vector u = [u_1;u_2;...;u_inputDim]
% sol_vector = [x_1(1),x_2(1),...,x_stateDim(1),
% x_1(2),...,x_stateDim(numberOfSteps),u_1(1),u_2(1)
% ,...,u_inputDim(1),....,u_inputDim(numberOfSteps-1)]
% Formula for indexing
% i^th state variable at time j, (j-1)*stateDim + i
% k^th input variable at time l, offset + (l-1)*inputDim + k
% offset = stateDim*numberOfSteps
offset = stateDim*numberOfSteps;
%% Set The Cost Function
% Simply minimize x_final
f = zeros(1,solDim);
for i=(numberOfSteps-1)*stateDim+1:(numberOfSteps)*stateDim
f(i) = 1;
end
% -- it turned out that we dont really need that
% also weight the inputs, so that they don't blow up
%
% for i=offset +1:offset + (numberOfSteps-1)*inputDim
%
% f(i) = 1e6;
%
% end
%
%
%% Inequality Constraints
% Just bound the x_final
Aineq = zeros(stateDim,solDim);
bineq = -x_final;
k=1;
for state = 1:stateDim
Aineq(k,(numberOfSteps-1)*stateDim+state) = -1;
k = k+1;
end
%% Equality Constraints (this is the tricky part!!)
Aeq = zeros(numberOfSteps*stateDim,solDim);
beq = zeros(numberOfSteps*stateDim,1);
% Initial conditions
k=1;
for i=1:stateDim
Aeq(k,i) = 1;
beq(i) = x_init(i);
k = k+1;
end
% Now constrain the system to obey the dynamics
constrainIndex= stateDim+1;
for timeIndex=2:numberOfSteps
for stateIndex=1:stateDim
Aeq(constrainIndex,(timeIndex-1)*stateDim + stateIndex) = 1;
for Index=1:stateDim
if(Index==stateIndex)
Aeq(constrainIndex,(timeIndex-2)*stateDim + Index) = -A(stateIndex,Index)*dt-1;
else
Aeq(constrainIndex,(timeIndex-2)*stateDim + Index) = -A(stateIndex,Index)*dt;
end
for inputIndex=1:inputDim
Aeq(constrainIndex,offset+(timeIndex-2)*inputDim + inputIndex) = -B(stateIndex,inputIndex)*dt;
end
end
constrainIndex = constrainIndex+1;
end
end
%% Set the lower and upper bounds (copy-paste over variables)
lb = zeros(solDim,1);
ub = zeros(solDim,1);
% for states
for i=1:numberOfSteps
for j=1:stateDim
lb((i-1)*stateDim + j) = lower(j);
ub((i-1)*stateDim + j) = upper(j);
end
end
% for inputs
for i=1:numberOfSteps-1
for j=1:inputDim
lb(offset + (i-1)*inputDim + j) = lower(stateDim+j);
ub(offset + (i-1)*inputDim + j) = upper(stateDim+j);
end
end
%% Solve The LP and arrange the solution
sol = linprog(f,Aineq,bineq,Aeq,beq,lb,ub);
for i=1:numberOfSteps
for j=1:stateDim
x_seq(j,i) = sol((i-1)*stateDim + j);
end
end
for i=1:numberOfSteps-1
for j=1:inputDim
u_seq(j,i) = sol(offset+ (i-1)*inputDim + j);
end
end
end
|
github
|
mubeipeng/focused_slam-master
|
Aircraft_Kinematic.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/Aircraft_Kinematic.m
| 28,967 |
utf_8
|
5e8129f6bf8fe01b2bf5e822feafe195
|
%% Class Definition
classdef Aircraft_Kinematic < MotionModel_interface
properties (Constant = true)
stDim = 7;%state.dim; % state dimension
ctDim = 4; % control vector dimension
wDim = 4; % Process noise (W) dimension % For the generality we also consider the additive noise on kinematics equation (3 dimension), but it most probably will set to zero. The main noise is a 2 dimensional noise which is added to the controls.
dt = user_data_class.par.motion_model_parameters.dt;
% base_length = user_data_class.par.motion_model_parameters.base_length; % distance between robot's rear wheels.
sigma_b_u = [0.02; deg2rad(0.25);deg2rad(0.25); deg2rad(0.25)];%user_data_class.par.motion_model_parameters.sigma_b_u_aircraft ;
eta_u = [0.005;0.005;0.005;0.005];%user_data_class.par.motion_model_parameters.eta_u_aircraft ;
P_Wg = [0.2 ; 0.2 ; 0.2 ; 0.1 ; 0.1 ; 0.1 ; 0.1];%user_data_class.par.motion_model_parameters.P_Wg;
Max_Roll_Rate = deg2rad(45); % try 45
Max_Pitch_Rate = deg2rad(45);% try 45
Max_Yaw_Rate = deg2rad(45);% try 45
Max_Velocity = 8.0; % m/s
Min_Velocity = 2.5;% m/s
zeroNoise = zeros(Aircraft_Kinematic.wDim,1);
turn_radius_min = Aircraft_Kinematic.Min_Velocity/Aircraft_Kinematic.Max_Yaw_Rate; % indeed we need to define the minimum linear velocity in turnings (on orbits) and then find the minimum radius accordingly. But, we picked the more intuitive way.
end
methods (Static = true)
function x_next = f_discrete(x,u,w)
if u(1)> Aircraft_Kinematic.Max_Velocity
u(1) = Aircraft_Kinematic.Max_Velocity;
end
if u(1) < Aircraft_Kinematic.Min_Velocity
u(1) = Aircraft_Kinematic.Min_Velocity;
end
if u(2)> Aircraft_Kinematic.Max_Roll_Rate
u(2) = Aircraft_Kinematic.Max_Roll_Rate;
end
if u(2) < -Aircraft_Kinematic.Max_Roll_Rate
u(2) = -Aircraft_Kinematic.Max_Roll_Rate;
end
if u(3)> Aircraft_Kinematic.Max_Pitch_Rate
u(3) = Aircraft_Kinematic.Max_Pitch_Rate;
end
if u(3) < -Aircraft_Kinematic.Max_Pitch_Rate
u(3) = -Aircraft_Kinematic.Max_Pitch_Rate;
end
if u(4)> Aircraft_Kinematic.Max_Yaw_Rate
u(4) = Aircraft_Kinematic.Max_Yaw_Rate;
end
if u(4) < -Aircraft_Kinematic.Max_Yaw_Rate
u(4) = -Aircraft_Kinematic.Max_Yaw_Rate;
end
pos = [x(1) ; x(2) ; x(3)];% position state
rot = [x(4) ; x(5) ; x(6) ; x(7)];% rotation state
q_rot = Quaternion(rot);
q_rot = unit(q_rot);% making a normalized quarternion, dont use quatnormalize
p = q_rot.R;
u_linear_ground = p *[u(1); 0; 0] ;
w_linear_ground = p * [w(1); 0 ; 0];
x_next_pos = pos + Aircraft_Kinematic.dt * (u_linear_ground) + ((Aircraft_Kinematic.dt^0.5) * w_linear_ground);
u_angular_ground = [u(2); u(3); u(4)];%p * [u(2); u(3); u(4)];
% u_angular_ground = [u_angular_ground(1); u_angular_ground(2); u_angular_ground(3)];
w_angular_ground = [w(2); w(3); w(4)]; % p * [w(2); w(3); w(4)]
% w_angular_ground = [w_angular_ground(1); w_angular_ground(2); w_angular_ground(3)];
% q0 = x(4);
% q1 = x(5);
% q2 = x(6);
% q3 = x(7);
Amat = [-x(5), -x(6), -x(7);
x(4) , -x(7), x(6);
x(7) , x(4), -x(5);
-x(6), x(5) , x(4)];
dq_dt_u = 0.5*Amat*u_angular_ground;
dq_dt_w = 0.5*Amat*w_angular_ground;
control = dq_dt_u * Aircraft_Kinematic.dt;
noise = dq_dt_w * Aircraft_Kinematic.dt^0.5;
x_next_rot = rot + control + noise;
q_next = unit(x_next_rot); % Make a unit quaternion
q_next = correct_quaternion(q_next);
% %transition_quat = Aircraft_Kinematic.f_transquat(Aircraft_Kinematic.dt , u_angular ,w_angular);
% x_next_q_rot = Quaternion();
% x_next_q_rot = unit(q_rot * transition_quat);% normalizing resultant quaternion)
% x_next_rot = double(x_next_q_rot);% converting to matrix f
x_next = [x_next_pos(1) x_next_pos(2) x_next_pos(3) q_next(1) q_next(2) q_next(3) q_next(4)]'; % augmenting state and rotational part
end
function J = df_dx_func(x,u,w) % state Jacobian
pos = [x(1) , x(2) , x(3)];% position state
rot = [x(4) , x(5) , x(6) , x(7)];% rotation state
q_rot = Quaternion(rot);
q_rot = unit(q_rot);% making a normalized quarternion
p = q_rot.R;
u_angular = [u(2); u(3); u(4)];
t3 = u_angular; % p * u_angular;
u_angular_ground = [0 ;t3(1); t3(2); t3(3)];
w_angular = [w(2); w(3); w(4)];
t4 = w_angular; % p * w_angular;
w_angular_ground = [0 ; t4(1); t4(2); t4(3)];
a_11 = 1 ;
a_12 = - 0.5 * t3(1) * Aircraft_Kinematic.dt - 0.5 * t4(1) * (Aircraft_Kinematic.dt)^0.5;
a_13 = - 0.5 * t3(2) * Aircraft_Kinematic.dt - 0.5 * t4(2) * (Aircraft_Kinematic.dt)^0.5;
a_14 = - 0.5 * t3(3) * Aircraft_Kinematic.dt - 0.5 * t4(3) * (Aircraft_Kinematic.dt)^0.5;
a_21 = 0.5 * t3(1) * Aircraft_Kinematic.dt + 0.5 * t4(1) * (Aircraft_Kinematic.dt)^0.5;
a_22 = 1 ;
a_23 = 0.5 * t3(3) * Aircraft_Kinematic.dt + 0.5 * t4(3) * (Aircraft_Kinematic.dt)^0.5;
a_24 = - 0.5 * t3(2) * Aircraft_Kinematic.dt - 0.5 * t4(2) * (Aircraft_Kinematic.dt)^0.5;
a_31 = 0.5 * t3(2) * Aircraft_Kinematic.dt + 0.5 * t4(2) * (Aircraft_Kinematic.dt)^0.5;
a_32 = - 0.5 * t3(3) * Aircraft_Kinematic.dt - 0.5 * t4(3) * (Aircraft_Kinematic.dt)^0.5;
a_33 = 1 ;
a_34 = 0.5 * t3(1) * Aircraft_Kinematic.dt + 0.5 * t4(1) * (Aircraft_Kinematic.dt)^0.5;
a_41 = 0.5 * t3(3) * Aircraft_Kinematic.dt + 0.5 * t4(3) * (Aircraft_Kinematic.dt)^0.5;
a_42 = 0.5 * t3(2) * Aircraft_Kinematic.dt + 0.5 * t4(2) * (Aircraft_Kinematic.dt)^0.5;
a_43 = -0.5 * t3(1) * Aircraft_Kinematic.dt - 0.5 * t4(1) * (Aircraft_Kinematic.dt)^0.5;
a_44 = 1 ;
A = [a_11 a_12 a_13 a_14; a_21 a_22 a_23 a_24; a_31 a_32 a_33 a_34; a_41 a_42 a_43 a_44];
% Calculating the jacobian of the linear components B
qq = q_rot.double; % put it back in double form
q0 = qq(1);
q1 = qq(2);
q2 = qq(3);
q3 = qq(4);
Vsum = (u(1)*Aircraft_Kinematic.dt + w(1)*Aircraft_Kinematic.dt^0.5);
b_11 = 1;
b_12 = 0;
b_13 = 0;
b_14 = 2*q0 * Vsum;
b_15 = 2*q1 * Vsum;
b_16 = -2*q2 * Vsum;
b_17 = -2*q3 * Vsum;
b_21 = 0;
b_22 = 1;
b_23 = 0;
b_24 = 2*q3*Vsum;
b_25 = 2*q2*Vsum;
b_26 = 2*q1*Vsum;
b_27 = 2*q0*Vsum;
b_31 = 0;
b_32 = 0;
b_33 = 1;
b_34 = -2*q2*Vsum;
b_35 = 2*q3*Vsum;
b_36 = -2*q0*Vsum;
b_37 = 2*q1*Vsum;
B = [b_11 b_12 b_13 b_14 b_15 b_16 b_17;b_21 b_22 b_23 b_24 b_25 b_26 b_27;b_31 b_32 b_33 b_34 b_35 b_36 b_37];
J = zeros(7,7);
J(1:3,1:7) = B;
J(4:7,4:7) = A;
end
function J = df_du_func(x,u,w)
rot = [x(4) , x(5) , x(6) , x(7)];% rotation state
q_rot = Quaternion(rot);
q_rot = unit(q_rot);% making a normalized quarternion
qq = q_rot.double; % put it back in double form
R_gb = q_rot.R;
q0 = qq(1);
q1 = qq(2);
q2 = qq(3);
q3 = qq(4);
b_11 = 0;
b_12 = 0.5 *(-q1)* Aircraft_Kinematic.dt ;
b_13 = 0.5 *(-q2)* Aircraft_Kinematic.dt ;
b_14 = 0.5 *(-q3)* Aircraft_Kinematic.dt ;
b_21 = 0 ;
b_22 = 0.5 *(q0)* Aircraft_Kinematic.dt ;
b_23 = 0.5 *(-q3)* Aircraft_Kinematic.dt ;
b_24 = 0.5 *(q2)* Aircraft_Kinematic.dt ;
b_31 = 0 ;
b_32 = 0.5 *(q3)* Aircraft_Kinematic.dt ;
b_33 = 0.5 *(q0)* Aircraft_Kinematic.dt ;
b_34 = 0.5 *(-q1)* Aircraft_Kinematic.dt ;
b_41 = 0;
b_42 = 0.5 *(-q2)* Aircraft_Kinematic.dt ;
b_43 = 0.5 *(q1) * Aircraft_Kinematic.dt ;
b_44 = 0.5 *(q0) * Aircraft_Kinematic.dt ;
B = [b_11 b_12 b_13 b_14; b_21 b_22 b_23 b_24; b_31 b_32 b_33 b_34; b_41 b_42 b_43 b_44];
% Jacobian calc for linear part
a_11 = (q0^2+q1^2-q2^2-q3^2) * Aircraft_Kinematic.dt ;
a_12 = 0;
a_13 = 0;
a_14 = 0;
a_21 = 2*(q1*q2+q0*q3)* Aircraft_Kinematic.dt;
a_22 = 0;
a_23 = 0;
a_24 = 0;
a_31 = 2*(q1*q3-q0*q2) * Aircraft_Kinematic.dt;
a_32 = 0;
a_33 = 0;
a_34 = 0;
A = [a_11 a_12 a_13 a_14;a_21 a_22 a_23 a_24;a_31 a_32 a_33 a_34];
J = zeros(7,4);
J(1:3,1:4) = A;
J(4:7,1:4) = B;
end
function J = df_dw_func(x,u,w) % noise Jacobian
rot = [x(4) , x(5) , x(6) , x(7)];% rotation state
q_rot = Quaternion(rot);
q_rot = unit(q_rot);% making a normalized quarternion
qq = q_rot.double; % put it back in double form
R_gb = q_rot.R;
q0 = qq(1);
q1 = qq(2);
q2 = qq(3);
q3 = qq(4);
g_11 = 0;
g_12 = 0.5 *(-q1)* sqrt(Aircraft_Kinematic.dt) ;
g_13 = 0.5 *(-q2)* sqrt(Aircraft_Kinematic.dt) ;
g_14 = 0.5 *(-q3)* sqrt(Aircraft_Kinematic.dt) ;
g_21 = 0 ;
g_22 = 0.5 *(q0)* sqrt(Aircraft_Kinematic.dt);
g_23 = 0.5 *(-q3)* sqrt(Aircraft_Kinematic.dt);
g_24 = 0.5 *(q2)* sqrt(Aircraft_Kinematic.dt) ;
g_31 = 0 ;
g_32 = 0.5 *(q3)* sqrt(Aircraft_Kinematic.dt) ;
g_33 = 0.5 *(q0)* sqrt(Aircraft_Kinematic.dt) ;
g_34 = 0.5 *(-q1)* sqrt(Aircraft_Kinematic.dt) ;
g_41 = 0;
g_42 = 0.5 *(-q2)* sqrt(Aircraft_Kinematic.dt) ;
g_43 = 0.5 *(q1)* sqrt(Aircraft_Kinematic.dt) ;
g_44 = 0.5 *(q0)* sqrt(Aircraft_Kinematic.dt) ;
G = [g_11 g_12 g_13 g_14; g_21 g_22 g_23 g_24; g_31 g_32 g_33 g_34; g_41 g_42 g_43 g_44];
% Jacobian for linear part
a_11 = (q0^2+q1^2-q2^2-q3^2) * (Aircraft_Kinematic.dt)^0.5 ;
a_12 = 0;
a_13 = 0;
a_14 = 0;
a_21 = 2*(q1*q2+q0*q3)* (Aircraft_Kinematic.dt)^0.5;
a_22 = 0;
a_23 = 0;
a_24 = 0;
a_31 = 2*(q1*q3-q0*q2) * (Aircraft_Kinematic.dt)^0.5;
a_32 = 0;
a_33 = 0;
a_34 = 0;
A = [a_11 a_12 a_13 a_14;a_21 a_22 a_23 a_24;a_31 a_32 a_33 a_34];
J = zeros(7,4);
J(1:3,1:4) = A;
J(4:7,1:4) = G;
end
function w = generate_process_noise(x,u) % simulate (generate) process noise based on the current poistion and controls
[Un] = Aircraft_Kinematic.generate_control_and_indep_process_noise(u);
w = [Un];
end
function [Un] = generate_control_and_indep_process_noise(U)
% generate Un
indep_part_of_Un = randn(Aircraft_Kinematic.ctDim,1);
P_Un = Aircraft_Kinematic.control_noise_covariance(U);
Un = indep_part_of_Un.*diag(P_Un.^(1/2));
end
function P_Un = control_noise_covariance(U)
u_std=(Aircraft_Kinematic.eta_u).*U +(Aircraft_Kinematic.sigma_b_u);
P_Un=diag(u_std.^2);
end
function Q_process_noise = process_noise_cov(x,u) % compute the covariance of process noise based on the current poistion and controls
Q_process_noise = control_noise_covariance(u);
end
%THERE no validity checking, just implementing for tests sake
function nominal_traj = generate_VALID_open_loop_point2point_traj(start,goal)
nominal_traj = Aircraft_Kinematic.generate_open_loop_point2point_traj(start,goal);
end
function nominal_traj = generate_open_loop_point2point_traj(start,goal) % generates open-loop trajectories between two start and goal states
% The MATLAB RVC ToolBox Must be loaded first
% disp('Using RRT3D to connect points on two orbits');
% disp('Start point is:');start
% disp('Goal point is:');goal
% disp('Solving...');
if is_trajectory_valid(start, goal)
veh = Aircraft_Kinematic();
rrt = RRT3D([], veh, 'start', start, 'range', 5,'npoints',500,'speed',2,'time', Aircraft_Kinematic.dt);
rrt.plan('goal',goal) ; % create navigation tree
nominal_traj.x = [];
nominal_traj.u = [];
nominal_traj = rrt.path(start, goal) ; % animate path from this start location
% Code for plotting
controls = [];
nomXs = [];
for i = 1:length(nominal_traj)
p = nominal_traj(i);
g = rrt.graph;
data = g.data(p);
if ~isempty(data)
if i >= length(nominal_traj) || g.edgedir(p, nominal_traj(i+1)) > 0
controls = [controls,data.steer'];
nomXs = [nomXs,data.path];
else
controls = [controls,(data.steer(:,end:-1:1))'];
nomXs = [nomXs,data.path];
end
end
end
if ~isempty(nomXs)
nominal_traj.x = [start,nomXs];
nominal_traj.u = controls;
end
disp('Done with RRT...');
else
nominal_traj =[];
return;
end
end
%% Generate open-loop Orbit-to-Orbit trajectory
function nominal_traj = generate_VALID_open_loop_orbit2orbit_traj(start_orbit, end_orbit) % generates open-loop trajectories between two start and end orbits
% check if both the orbits are turning in the same
% direction or not.
direction_start_orbit = sign(start_orbit.u(1,1))*sign(start_orbit.u(2,1));
direction_end_orbit = sign(end_orbit.u(1,1))*sign(end_orbit.u(2,1));
% finding the connecting edge between orbits.
if direction_start_orbit == direction_end_orbit % both orbits turn in a same direction
gamma = atan2( end_orbit.center.val(2) - start_orbit.center.val(2) , end_orbit.center.val(1) - start_orbit.center.val(1) );
temp_edge_start = start_orbit.radius * [ cos(gamma-pi/2) ; sin(gamma-pi/2);0 ] + start_orbit.center.val(1:3);
temp_edge_end = end_orbit.radius* [ cos(gamma-pi/2) ; sin(gamma-pi/2);0 ] + end_orbit.center.val(1:3);
else
error('different directions have not been implemented in PNPRM yet.')
end
%temp_traj.x(:,1) = temp_edge_start; temp_traj.x(:,2) = temp_edge_end; % we generate this trajectory (only composed of start and end points) to check the collision probabilities before generating the edges.
%collision = Unicycle_robot.is_constraints_violated(temp_traj); % checking intersection with obstacles
% if collision == 1
% nominal_traj = [];
% return
% else
% % construction edge trajectory
roll_tmp_traj_start = 0;
pitch_tmp_traj_start = 0;
yaw_tmp_traj_start = gamma;
q_tmp_traj_start = angle2quat(yaw_tmp_traj_start,pitch_tmp_traj_start,roll_tmp_traj_start);
tmp_traj_start = [temp_edge_start ; q_tmp_traj_start' ];
tmp_traj_goal = [temp_edge_end; q_tmp_traj_start'];
nominal_traj = MotionModel_class.generate_open_loop_point2point_traj(tmp_traj_start,tmp_traj_goal);
end
%% Sample a valid orbit (periodic trajectory)
function orbit = sample_a_valid_orbit()
orbit_center = state.sample_a_valid_state();
if isempty( orbit_center)
orbit = [];
return
else
orbit = Aircraft_Kinematic.generate_orbit(orbit_center);
orbit = Aircraft_Kinematic.draw_orbit(orbit);
end
disp('fix the orbit drawing above in aircraft_kinematic.m Line 440')
end
%% Construct an orbit
function orbit = generate_orbit(orbit_center)
% minimum orbit radius resutls from dividing the minimum linear
% velocity to maximum angular velocity. However, here we assume
% that the linear velocity is constant.
orbit.radius = Aircraft_Kinematic.turn_radius_min;
orbit_length_meter = 2*pi*orbit.radius;
orbit_length_time_continuous = orbit_length_meter/Aircraft_Kinematic.Min_Velocity;
T_rational = orbit_length_time_continuous/Aircraft_Kinematic.dt;
T = ceil(T_rational);
orbit.period = T;
orbit.center = orbit_center;
% defining controls on the orbit
if T_rational-floor(T_rational)==0
V_p = Aircraft_Kinematic.Min_Velocity * ones(1,T); % we traverse the orbit with minimum linear velocity
omega_p = Aircraft_Kinematic.Max_Yaw_Rate * ones(1,T); % we traverse the orbit with maximum angular velocity
else
V_p = Aircraft_Kinematic.Min_Velocity * [ones(1,T-1) , T_rational-floor(T_rational)]; % we traverse the orbit with minimum linear velocity
omega_p = Aircraft_Kinematic.Max_Yaw_Rate * [ones(1,T-1) , T_rational-floor(T_rational)]; % we traverse the orbit with maximum angular velocity
end
u_p = [V_p;zeros(1,T);zeros(1,T);omega_p];
w_zero = Aircraft_Kinematic.zeroNoise; % no noise
% defining state steps on the orbit
zeroQuaternion = state.zeroQuaternion; % The robot's angle in the start of orbit is zero
x_p(:,1) = [orbit_center.val(1:3) - [0;orbit.radius;0] ; zeroQuaternion]; % initial x
for k=1:T
x_p(:,k+1) = MotionModel_class.f_discrete(x_p(:,k),u_p(:,k),w_zero);
tempState = state(x_p(:,k+1));
if tempState.is_constraint_violated()
error('The selected orbit is violating constraints');
return
end
end
orbit.x = x_p(:,1:T); % "x_p" is of length T+1, but "x_p(:,T+1)" is equal to "x_p(:,1)"
orbit.u = u_p; % "u_p" is of length T.
orbit.plot_handle = [];
end
function point = point_on_orbit(orbit, point_angle)
gamma = point_angle;
point = orbit.radius * [ cos(gamma) ; sin(gamma);0 ] + orbit.center.val(1:3);
yaw = gamma+pi/2;
q = angle2quat(yaw,0,0);
q = correct_quaternion(q);
point = [point;q'];
%start_orbit.radius*[cos(gamma_start_of_orbit_edge);sin(gamma_start_of_orbit_edge);0]+start_orbit.center.val;
end
%% Draw an orbit
function orbit = draw_orbit(orbit,varargin)
% This function draws the orbit.
% default values
orbit_color = 'b'; % Default value for "OrbitTextColor" property. % User-provided value for "OrbitTextColor" property.
orbit_width = 2; % User-provided value for "orbit_width" property. % User-provided value for shifting the text a little bit to the left. % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
robot_shape = 'triangle'; % The shape of robot (to draw trajectories and to show direction of edges and orbits)
robot_size = 1; % Robot size on orbits (to draw trajectories and to show direction of edges and orbits)
orbit_trajectory_flag = 0; % Make it one if you want to see the orbit trajectories. Zero, otherwise.
text_size = 12;
text_color = 'b';
text_shift = 0.8;
orbit_text = [];
% parsing the varargin
if ~isempty(varargin)
for i = 1 : 2 : length(varargin)
switch lower(varargin{i})
case lower('RobotSize')
robot_size = varargin{i+1};
case lower('OrbitWidth')
orbit_width = varargin{i+1};
case lower('OrbitColor')
orbit_color = varargin{i+1};
case lower('OrbitText')
orbit_text = varargin{i+1};
end
end
end
% start drawing
if orbit_trajectory_flag == 1
orbit.plot_handle = [];
for k=1:orbit.period
Xstate = state(orbit.x(:,k));
Xstate = Xstate.draw('RobotShape',robot_shape,'robotsize',robot_size);
orbit.plot_handle = [orbit.plot_handle,Xstate.head_handle,Xstate.text_handle,Xstate.tria_handle];
end
tmp = plot(orbit.x(1,:) , orbit.x(2,:),orbit_color);
orbit.plot_handle = [orbit.plot_handle,tmp];
else
orbit.plot_handle = [];
th_orbit_draw = [0:0.1:2*pi , 2*pi];
x_orbit_draw = orbit.center.val(1) + orbit.radius*cos(th_orbit_draw);
y_orbit_draw = orbit.center.val(2) + orbit.radius*sin(th_orbit_draw);
z_orbit_draw = orbit.center.val(3)*ones(1,size(x_orbit_draw,2));
tmp_h = plot3(x_orbit_draw,y_orbit_draw,z_orbit_draw,'lineWidth',orbit_width);
Xstate = state(orbit.x(:,1));
Xstate = Xstate.draw('RobotShape',robot_shape,'robotsize',robot_size);
orbit.plot_handle = [orbit.plot_handle,tmp_h,Xstate.head_handle,Xstate.text_handle,Xstate.tria_handle];
end
if ~isempty(orbit_text)
text_pos = orbit.center.val;
text_pos(1) = text_pos(1) - text_shift; % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
tmp_handle = text( text_pos(1), text_pos(2), orbit_text, 'fontsize', text_size, 'color', text_color);
orbit.plot_handle = [orbit.plot_handle,tmp_handle];
end
end
function YesNo = is_constraints_violated(open_loop_traj)
error('not yet implemented');
end
function traj_plot_handle = draw_nominal_traj(nominal_traj, traj_flag, varargin)
traj_plot_handle = [];
if traj_flag == 1
for k = 1 : size(nominal_traj.x , 2)
tmp_Xstate = state (nominal_traj.x(:,k) );
tmp_Xstate.draw();
% tmp_Xstate.draw('RobotShape','triangle','robotsize',1);%,'TriaColor',color(cycles));
%traj_plot_handle(k:k+2) =
%[tmp_Xstate.head_handle,tmp_Xstate.text_handle,tmp_Xstate.tria_handle];
end
elseif traj_flag == 2
tmp_handle = plot3(nominal_traj.x(1,:) , nominal_traj.x(2,:) , nominal_traj.x(3,:), 'LineWidth',4, 'color','g');
% traj_plot_handle = [traj_plot_handle , tmp_handle];
len = size( nominal_traj.x , 2);
[yaw,pitch,roll] = quat2angle(nominal_traj.x(4:7,floor(len/2))');
pitch =0;
roll =0;
new_quat = angle2quat(yaw,pitch,roll);
tmp_Xstate = state( [nominal_traj.x(1:3,floor(len/2)) ; new_quat']); % to plot the direction of the line.
tmp_Xstate = tmp_Xstate.draw('RobotShape','triangle','robotsize',2);
traj_plot_handle = [traj_plot_handle , tmp_Xstate.plot_handle , tmp_Xstate.head_handle , tmp_Xstate.tria_handle , tmp_Xstate.text_handle ];
drawnow
elseif traj_flag == 3
tmp_handle = plot3(nominal_traj.x(1,:) , nominal_traj.x(2,:) , nominal_traj.x(3,:), 'LineWidth',4, 'color','r');
% traj_plot_handle = [traj_plot_handle , tmp_handle];
len = size( nominal_traj.x , 2);
[yaw,pitch,roll] = quat2angle(nominal_traj.x(4:7,floor(len/2))');
pitch =0;
roll =0;
new_quat = angle2quat(yaw,pitch,roll);
tmp_Xstate = state( [nominal_traj.x(1:3,floor(len/2)) ; new_quat']); % to plot the direction of the line.
tmp_Xstate = tmp_Xstate.draw('RobotShape','triangle','robotsize',2);
traj_plot_handle = [traj_plot_handle , tmp_Xstate.plot_handle , tmp_Xstate.head_handle , tmp_Xstate.tria_handle , tmp_Xstate.text_handle ];
drawnow
else
tmp_handle = plot3(nominal_traj.x(1,:) , nominal_traj.x(2,:) , nominal_traj.x(3,:), 'LineWidth',2);
% traj_plot_handle = [traj_plot_handle , tmp_handle];
len = size( nominal_traj.x , 2);
[yaw,pitch,roll] = quat2angle(nominal_traj.x(4:7,floor(len/2))');
pitch =0;
roll =0;
new_quat = angle2quat(yaw,pitch,roll);
tmp_Xstate = state( [nominal_traj.x(1:3,floor(len/2)) ; new_quat']); % to plot the direction of the line.
tmp_Xstate = tmp_Xstate.draw('RobotShape','triangle','robotsize',2);
traj_plot_handle = [traj_plot_handle , tmp_Xstate.plot_handle , tmp_Xstate.head_handle , tmp_Xstate.tria_handle , tmp_Xstate.text_handle ];
drawnow
end
end
function plot_handle = draw_orbit_neighborhood(orbit, scale)
% not implemented yet
plot_handle = [];
end
end
end
function qcorrected = correct_quaternion(q)
qcorrected = q;
if q(1) < 0
qcorrected = -q;
end
end
function YesNo = is_trajectory_valid(start, goal)
vel = (Aircraft_Kinematic.Min_Velocity + Aircraft_Kinematic.Max_Velocity)/2;
nPointsOnSegment = ceil(( norm(goal(1:3)-start(1:3)) )/(vel*Aircraft_Kinematic.dt));
guidanceVector = goal(1:3) - start(1:3);
for i=1:nPointsOnSegment+1
point = start(1:3) + (i/(nPointsOnSegment+1))*guidanceVector(1:3);
tmp = state([point;1;0;0;0]);
if tmp.is_constraint_violated
YesNo=0;
return;
end
end
YesNo = 1;
end
%% Generating Control-dependent Noise Covariance
%
% $$ P^{U_n} = \left(
% \begin{array}{cc}
% (\eta_V V + \sigma_{b_V})^2 & 0\\
% 0 & (\eta_{\omega} \omega + \sigma_{b_{\omega}})^2\\
% \end{array}\right) $$,
%
% where, $\eta_u=(\eta_V,\eta_{\omega})^T$ and
% $\sigma_{b_u}=(\sigma_{b_V},\sigma_{b_{\omega}})^T$.
function P_Un = control_noise_covariance(U)
u_std = (Aircraft_Kinematic.eta_u).*U+(Aircraft_Kinematic.sigma_b_u);
P_Un = diag(u_std.^2);
end
|
github
|
mubeipeng/focused_slam-master
|
Quadrotor_MM.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/Quadrotor_MM.m
| 12,667 |
utf_8
|
eec425366f6ece9508fb7c5cb25d21dd
|
classdef Quadrotor_MM < MotionModel_interface
% Note that because the class is defined as a handle class, the
% properties must be defined such that they are do not change from an
% object to another one.
properties (Constant)
stDim = state.dim; % state dimension
ctDim = 4; % control vector dimension
wDim = 16; % Process noise (W) dimension - 4 for control noise and 12 for additive state noise
zeroControl = zeros(Quadrotor_MM.ctDim,1);
zeroNoise = zeros(Quadrotor_MM.wDim,1);
dt = user_data_class.par.motion_model_parameters.dt;
g = 9.81; % (m/s^2) -- gravitational constant
mass = 0.650; % (kg) quadrotor mass
len = 0.23 % (m) length of the quadrotor
EyeX = 0.0075; % (kg*m2) moments of intertia -- x coordinate
EyeY = 0.0075; % (kg*m2) moments of intertia -- y coordinate
EyeZ = 0.013; % (kg*m2) moments of intertia -- z coordinate
sigma_b_u = user_data_class.par.motion_model_parameters.sigma_b_u_quadrotor;
eta_u = user_data_class.par.motion_model_parameters.eta_u_quadrotor;
P_Wg = user_data_class.par.motion_model_parameters.P_Wg;
end
methods (Static)
function x_next = f_discrete(x,u,w)
x_next = Quadrotor_MM.df_dx_func(x,u,w)*x+Quadrotor_MM.df_du_func(x,u,w)*u+Quadrotor_MM.df_dw_func(x,u,w)*w;
end
function A = df_dx_func(x,u,w) %#ok<INUSD>
Acontin = zeros(12,12);
Acontin(1:9,4:12)=diag([1,1,1,Quadrotor_MM.g,-Quadrotor_MM.g,0,1,1,1]);
A = eye(12) + Acontin*Quadrotor_MM.dt;
end
function Bcontin = df_contin_du_func(x,u,w) %#ok<INUSD>
Bcontin = zeros(12,4);
Bcontin(6,1) = 1/Quadrotor_MM.mass;
Bcontin(9:12, 1:4) = diag([0, Quadrotor_MM.len/Quadrotor_MM.EyeX, Quadrotor_MM.len/Quadrotor_MM.EyeY, 1/Quadrotor_MM.EyeZ]);
end
function B = df_du_func(x,u,w)
B = Quadrotor_MM.df_contin_du_func(x,u,w)*Quadrotor_MM.dt;
end
function G = df_dw_func(x,u,w)
Gcontin = [Quadrotor_MM.df_contin_du_func(x,u,w),eye(12)];
G = Gcontin*sqrt(Quadrotor_MM.dt);
end
function w = generate_process_noise(x,u) %#ok<INUSD>
[Un,Wg] = generate_control_and_indep_process_noise(u);
w = [Un;Wg];
end
function Q_process_noise = process_noise_cov(x,u) %#ok<INUSD>
P_Un = control_noise_covariance(u);
Q_process_noise = blkdiag(P_Un,Quadrotor_MM.P_Wg);
end
function nominal_traj = generate_open_loop_point2point_traj(x_init,x_final) % generates open-loop trajectories between two start and goal states
if isa(x_init,'state'), x_init=x_init.val; end % retrieve the value of the state vector
if isa(x_final,'state'), x_final=x_final.val; end % retrieve the value of the state vector
params.g = Quadrotor_MM.g;
params.m = Quadrotor_MM.mass; % quadrotor mass kg
params.Ix = Quadrotor_MM.EyeX; % Moment of Inertia kg*m2
params.Iy = Quadrotor_MM.EyeY; % Moment of Inertia kg*m2
params.Iz = Quadrotor_MM.EyeZ; % Moment of Inertia kg*m2
params.L = Quadrotor_MM.len; % Arm Length m
params.dt = Quadrotor_MM.dt;
%% Initial and Final States
%%%%%%%%%%
% Note that the convention in quadrotor state is:
% P,PDOT,ATT, ATTDOT
% Initial State
p_init = x_init(1:3,1);
pdot_init = x_init(4:6,1);
att_init = x_init(7:9,1);
attdot_init = x_init(10:12,1);
% Final State
p_final = x_final(1:3,1);
pdot_final = x_final(4:6,1);
att_final = x_final(7:9,1);
attdot_final = x_final(10:12,1);
n_steps = 30;
% Reference States (X,Xdot and Y,Ydot)
% Fit a second order polynomial path
delta_x = p_final(1) -p_init(1);
time = 0:params.dt:(n_steps-1)*params.dt;
refs = zeros(10,n_steps);
refs(1,:) = p_final(1); % px command
refs(5,:) = p_final(2); % py command
refs(9,:) = p_final(3); % pz command
%% Propogate with FL Control laws
states = zeros(12,n_steps);
states(:,1) = x_init;
u = zeros(4,n_steps-1);
for time_index=2:n_steps
% Control
u(:,time_index-1) = QuadFeedbackLinearization(states(:,time_index-1),...
refs(:,time_index-1),params);
% Integration
states(:,time_index) =...
quadDyn(states(:,time_index-1),u(:,time_index-1),params)*params.dt +...
states(:,time_index-1);
end
nominal_traj.x = states;
nominal_traj.u = u;
end
function nominal_traj = generate_VALID_open_loop_point2point_traj(x_init,x_final) % generates open-loop trajectories between two start and goal states
if isa(x_init,'state'), x_init=x_init.val; end % retrieve the value of the state vector
if isa(x_final,'state'), x_final=x_final.val; end % retrieve the value of the state vector
params.g = Quadrotor_MM.g;
params.m = Quadrotor_MM.mass; % quadrotor mass kg
params.Ix = Quadrotor_MM.EyeX; % Moment of Inertia kg*m2
params.Iy = Quadrotor_MM.EyeY; % Moment of Inertia kg*m2
params.Iz = Quadrotor_MM.EyeZ; % Moment of Inertia kg*m2
params.L = Quadrotor_MM.len; % Arm Length m
params.dt = Quadrotor_MM.dt;
%% Initial and Final States
%%%%%%%%%%
% Note that the convention in quadrotor state is:
% P,PDOT,ATT, ATTDOT
% Initial State
p_init = x_init(1:3,1);
pdot_init = x_init(4:6,1);
att_init = x_init(7:9,1);
attdot_init = x_init(10:12,1);
% Final State
p_final = x_final(1:3,1);
pdot_final = x_final(4:6,1);
att_final = x_final(7:9,1);
attdot_final = x_final(10:12,1);
n_steps = 30;
% Reference States (X,Xdot and Y,Ydot)
% Fit a second order polynomial path
delta_x = p_final(1) -p_init(1);
time = 0:params.dt:(n_steps-1)*params.dt;
refs = zeros(10,n_steps);
refs(1,:) = p_final(1); % px command
refs(5,:) = p_final(2); % py command
refs(9,:) = p_final(3); % pz command
%% Propogate with FL Control laws
states = zeros(12,n_steps);
states(:,1) = x_init;
u = zeros(4,n_steps-1);
for time_index=2:n_steps
% Control
u(:,time_index-1) = QuadFeedbackLinearization(states(:,time_index-1),...
refs(:,time_index-1),params);
% Integration
states(:,time_index) =...
quadDyn(states(:,time_index-1),u(:,time_index-1),params)*params.dt +...
states(:,time_index-1);
end
nominal_traj.x = states;
nominal_traj.u = u;
end
function YesNo = is_constraints_violated(open_loop_traj) % this function checks if the "open_loop_traj" violates any constraints or not. For example it checks collision with obstacles.
error('not implemented yet')
% In this class the open loop trajectories are indeed straight
% lines. So, we use following simplified procedure to check the
% collisions.
Obst=obstacles_class.obst;
edge_start = open_loop_traj.x(1:2,1);
edge_end = open_loop_traj.x(1:2,end);
N_obst=size(Obst,2);
intersection=0;
for ib=1:N_obst
X_obs=[Obst{ib}(:,1);Obst{ib}(1,1)];
Y_obs=[Obst{ib}(:,2);Obst{ib}(1,2)];
X_edge=[edge_start(1);edge_end(1)];
Y_edge=[edge_start(2);edge_end(2)];
[x_inters,~] = polyxpoly(X_obs,Y_obs,X_edge,Y_edge);
if ~isempty(x_inters)
intersection=intersection+1;
end
end
if intersection>0
YesNo=1;
else
YesNo=0;
end
end
function traj_plot_handle = draw_nominal_traj(nominal_traj, varargin)
for k = 1:length(nominal_traj.x)
xTmp = state(nominal_traj.x(:,k));
xTmp = xTmp.draw('robotshape','triangle');
end
traj_plot_handle = [];
% s_node_2D_loc = nominal_traj.x(1:2,1);
% e_node_2D_loc = nominal_traj.x(1:2,end);
% % retrieve PRM parameters provided by the user
% disp('the varargin need to be parsed here')
% % edge_spec = obj.par.edge_spec;
% % edge_width = obj.par.edge_width;
% edge_spec = '-b';
% edge_width = 2;
%
% % drawing the 2D edge line
% traj_plot_handle = plot([s_node_2D_loc(1),e_node_2D_loc(1)],[s_node_2D_loc(2),e_node_2D_loc(2)],edge_spec,'linewidth',edge_width);
end
end
methods (Static, Access = private)
function nominal_traj = generate_open_loop_point2point_traj_turn_move_turn(obj , start_node_ind, end_node_ind)
error('not implemented yet')
end
function d_yaw_seq = steerHeading(psi_init,psi_final,n_steps)
% Heading Control sub-system (states: psi and r)
A = [0,1;0 0];
B = [0;1/(Quadrotor_MM.EyeZ)];
lower = [-pi/2;-pi;-1];
upper = [pi/2;pi;1];
x_init = [psi_init,0];
x_final = [psi_final,0];
[~,d_yaw_seq] = steerLinearSystembyLP(A,B,lower,upper,x_init,x_final,Quadrotor_MM.dt,n_steps);
end
function d_roll_seq = steerX(px_init,px_final,n_steps)
% X Control sub-system(states x xdot phi p)
A = zeros(4,4);
A(1,2) = 1;
A(2,3) = Quadrotor_MM.g;
A(3,4) = 1;
B = zeros(4,1);
B(4,1) = Quadrotor_MM.len/Quadrotor_MM.EyeX;
lower = [-2;-2;-pi/2;-pi;-1];
upper = [2;2;pi/2;pi;1];
x_init = [px_init,0,0,0];
x_final = [px_final,0,0,0];
[~,d_roll_seq] = steerLinearSystembyLP(A,B,lower,upper,x_init,x_final,Quadrotor_MM.dt,n_steps);
end
function d_pitch_seq = steerY(py_init,py_final,n_steps)
% X Control sub-system(states y ydot theta q)
A = zeros(4,4);
A(1,2) = 1;
A(2,3) = -Quadrotor_MM.g;
A(3,4) = 1;
B = zeros(4,1);
B(4,1) = Quadrotor_MM.len/Quadrotor_MM.EyeY;
lower = [-2;-2;-pi/2;-pi;-1];
upper = [2;2;pi/2;pi;1];
x_init = [py_init,0,0,0];
x_final = [py_final,0,0,0];
[~,d_pitch_seq] = steerLinearSystembyLP(A,B,lower,upper,x_init,x_final,Quadrotor_MM.dt,n_steps);
end
end
end
function [Un,Wg] = generate_control_and_indep_process_noise(U)
% generate Un
indep_part_of_Un = randn(Quadrotor_MM.ctDim,1);
P_Un = control_noise_covariance(U);
Un = indep_part_of_Un.*diag(P_Un.^(1/2));
% generate Wg
Wg = mvnrnd(zeros(Quadrotor_MM.stDim,1),Quadrotor_MM.P_Wg)';
end
function P_Un = control_noise_covariance(U)
u_std=(Quadrotor_MM.eta_u).*U+(Quadrotor_MM.sigma_b_u);
P_Un=diag(u_std.^2);
end
|
github
|
mubeipeng/focused_slam-master
|
Omni_directional_robot.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/Omni_directional_robot.m
| 17,473 |
utf_8
|
98a3c0a20454a1d89bf3e2979909fcc2
|
classdef Omni_directional_robot < MotionModel_interface
% Note that because the class is defined as a handle class, the
% properties must be defined such that they are do not change from an
% object to another one.
properties (Constant)
% numRobots = 1;
% stateClassName = 'planar_robot_XYTheta_state';
stDim = 3; % state dimension
ctDim = 3; % control vector dimension
wDim = 6; % Process noise (W) dimension
zeroControl = zeros(Omni_directional_robot.ctDim,1);
zeroNoise = zeros(Omni_directional_robot.wDim,1);
dt = 0.1000; %user_data_class.par.motion_model_parameters.dt;
robot_link_length = 0.2000; %user_data_class.par.motion_model_parameters.robot_link_length;
sigma_b_u = zeros(3,1); %user_data_class.par.motion_model_parameters.sigma_b_u_omni;
eta_u = zeros(3,1); %user_data_class.par.motion_model_parameters.eta_u_omni;
P_Wg = diag([0.16 0.16 0.0195]); %user_data_class.par.motion_model_parameters.P_Wg;
end
% properties (Constant = true, SetAccess = private)
% UnDim = 3;
% WgDim = 3;
% end
methods (Static)
function x_next = f_discrete(x,u,w)
Un = w(1:Omni_directional_robot.ctDim); % The size of Un may be different from ctDim in some other model.
Wg = w(Omni_directional_robot.ctDim+1 : Omni_directional_robot.wDim); % The size of Wg may be different from stDim in some other model.
Wc = Omni_directional_robot.f_contin(x,Un,Wg);
x_next = x+Omni_directional_robot.f_contin(x,u,0)*Omni_directional_robot.dt+Wc*sqrt(Omni_directional_robot.dt);
end
function x_dot = f_contin(x,u,wg) % Do not call this function from outside of this class!! % The last input in this method should be w, instead of wg. But, since it is a only used in this class, it does not matter so much.
th = x(3);
r = Omni_directional_robot.robot_link_length;
x_dot = (1/3)*[-2*sin(th),-2*sin(pi/3-th),2*sin(pi/3+th);
2*cos(th),-2*cos(pi/3-th),-2*cos(pi/3+th);
1/r,1/r,1/r]*u+wg;
end
function A = df_dx_func(x,u,w)
un = w(1:Omni_directional_robot.ctDim); % The size of Un may be different from ctDim in some other model.
wg = w(Omni_directional_robot.ctDim+1 : Omni_directional_robot.wDim); % The size of Wg may be different from stDim in some other model.
A = eye(Omni_directional_robot.stDim) ...
+ Omni_directional_robot.df_contin_dx(x,u,zeros(Omni_directional_robot.stDim,1))*Omni_directional_robot.dt ...
+ Omni_directional_robot.df_contin_dx(x,un,wg)*sqrt(Omni_directional_robot.dt);
end
function Acontin = df_contin_dx(x,u,w) %#ok<INUSD>
th = x(3);
Acontin = (2/3)*[0 0 -cos(th)*u(1)+cos(pi/3-th)*u(2)+cos(pi/3+th)*u(3);
0 0 -sin(th)*u(1)-sin(pi/3-th)*u(2)+sin(pi/3+th)*u(3);
0 0 0];
end
function B = df_du_func(x,u,w) %#ok<INUSD>
th = x(3);
r = Omni_directional_robot.robot_link_length;
B = (1/3)*[-2*sin(th),-2*sin(pi/3-th),2*sin(pi/3+th);
2*cos(th) ,-2*cos(pi/3-th),-2*cos(pi/3+th);
1/r ,1/r ,1/r ]*Omni_directional_robot.dt;
end
function G = df_dw_func(x,u,w) %#ok<INUSD>
th=x(3);
r=Omni_directional_robot.robot_link_length;
T_theta=(1/3)*[-2*sin(th),-2*sin(pi/3-th),2*sin(pi/3+th);
2*cos(th) ,-2*cos(pi/3-th),-2*cos(pi/3+th);
1/r ,1/r ,1/r ];
G = [T_theta,eye(Omni_directional_robot.stDim)]*sqrt(Omni_directional_robot.dt);
end
function w = generate_process_noise(x,u) %#ok<INUSD>
[Un,Wg] = generate_control_and_indep_process_noise(u);
w = [Un;Wg];
end
function Q_process_noise = process_noise_cov(x,u) %#ok<INUSD>
P_Un = control_noise_covariance(u);
Q_process_noise = blkdiag(P_Un,Omni_directional_robot.P_Wg);
end
function nominal_traj = generate_VALID_open_loop_point2point_traj(X_initial,X_final,obst) % generates open-loop trajectories between two start and goal states
if isa(X_initial,'state'), X_initial=X_initial.val; end % retrieve the value of the state vector
if isa(X_final,'state'), X_final=X_final.val; end % retrieve the value of the state vector
% parameters
omega_path=1.5708; %user_data_class.par.motion_model_parameters.omega_const_path; % constant rotational velocity during turnings
dt=Omni_directional_robot.dt;
V_path=5; %user_data_class.par.motion_model_parameters.V_const_path; % constant translational velocity during straight movements
stDim = Omni_directional_robot.stDim;
ctDim=Omni_directional_robot.ctDim;
r=Omni_directional_robot.robot_link_length;
th_p = atan2( X_final(2)-X_initial(2) , X_final(1)-X_initial(1) ); % the angle of edge % note that "th_p" is already between -pi and pi, since it is the output of "atan2"
%-------------- Rotation number of steps
if abs(X_initial(3))>pi, X_initial(3)=(X_initial(3)-sign(X_initial(3))*2*pi); end % Here, we bound the initial angle "X_initial(3)" between -pi and pi
if abs(X_final(3))>pi, X_final(3)=(X_final(3)-sign(X_final(3)*2*pi)); end % Here, we bound the final angle "X_final(3)" between -pi and pi
delta_th_p = X_final(3) - X_initial(3); % turning angle
if abs(delta_th_p)>pi, delta_th_p=(delta_th_p-sign(delta_th_p)*2*pi); end % Here, we bound "pre_delta_th_p" between -pi and pi
rotation_steps = abs( delta_th_p/(omega_path*dt) );
%--------------Translation number of steps
delta_disp = norm( X_final(1:2) - X_initial(1:2) );
translation_steps = abs(delta_disp/(V_path*dt));
%--------------Total number of steps
kf_rational = max([rotation_steps , translation_steps]);
kf = floor(kf_rational)+1; % note that in all following lines you cannot replace "floor(something)+1" by "ceil(something)", as it may be a whole number.
%=====================Rotation steps of the path
delta_theta_const = omega_path*sign(delta_th_p)*dt;
delta_theta_nominal(: , 1:floor(rotation_steps)) = repmat( delta_theta_const , 1 , floor(rotation_steps));
delta_theta_const_end = omega_path*sign(delta_th_p)*dt*(rotation_steps-floor(rotation_steps));
delta_theta_nominal(:,floor(rotation_steps)+1) = delta_theta_const_end; % note that you cannot replace "floor(pre_rotation_steps)+1" by "ceil(pre_rotation_steps)", as it may be a whole number.
delta_theta_nominal = [delta_theta_nominal , zeros(1 , kf - size(delta_theta_nominal,2))]; % augment zeros to the end of "delta_theta_nominal", to make its length equal to "kf".
% u_const = ones(3,1)*r*omega_path*sign(delta_th_p);
% u_p_rot(: , 1:floor(rotation_steps)) = repmat( u_const,1,floor(rotation_steps) );
% u_const_end = ones(3,1)*r*omega_path*sign(delta_th_p)*(rotation_steps-floor(rotation_steps));
% u_p_rot(:,floor(rotation_steps)+1)=u_const_end; % note that you cannot replace "floor(pre_rotation_steps)+1" by "ceil(pre_rotation_steps)", as it may be a whole number.
%=====================Translations
delta_xy_const = [V_path*cos(th_p);V_path*sin(th_p)]*dt;
delta_xy_nominal( : , 1:floor(translation_steps) ) = repmat( delta_xy_const , 1 , floor(translation_steps));
delta_xy_const_end = [V_path*cos(th_p);V_path*sin(th_p)]*dt*(translation_steps - floor(translation_steps));
delta_xy_nominal( : , floor(translation_steps)+1 ) = delta_xy_const_end;
delta_xy_nominal = [delta_xy_nominal , zeros(2 , kf - size(delta_xy_nominal,2))]; % augment zeros to the end of "delta_xy_nominal", to make its length equal to "kf".
delta_state_nominal = [delta_xy_nominal;delta_theta_nominal];
%=====================Nominal control and state trajectory generation
x_p = zeros(stDim,kf+1);
theta = zeros(1,kf+1);
u_p = zeros(stDim,kf);
x_p(:,1) = X_initial;
theta(1) = X_initial(3);
for k = 1:kf
theta(:,k+1) = theta(:,k) + delta_state_nominal(3,k);
th_k = theta(:,k);
T_inv_k = [-sin(th_k), cos(th_k) ,r;
-sin(pi/3-th_k),-cos(pi/3-th_k) ,r;
sin(pi/3+th_k) ,-cos(pi/3+th_k) ,r];
delta_body_velocities_k = delta_state_nominal(:,k)/dt; % x,y,and theta velocities in body coordinate at time step k
u_p(:,k) = T_inv_k*delta_body_velocities_k; % "T_inv_k" maps the "velocities in body coordinate" to the control signal
x_p(:,k+1) = x_p(:,k) + delta_state_nominal(:,k);
% tmp = state(x_p(:,k+1));
tmp = planar_robot_XYTheta_state(x_p(:,k+1));
if tmp.is_constraint_violated(obst), nominal_traj =[]; return; end
end
% noiselss motion % for debug: if you uncomment the following
% lines you have to get the same "x_p_copy" as the "x_p"
% x_p_copy = zeros(stDim,kf+1);
% x_p_copy(:,1) = X_initial;
% for k = 1:kf
% x_p_copy(:,k+1) = Omni_directional_robot.f_discrete(x_p_copy(:,k),u_p(:,k),zeros(Omni_directional_robot.wDim,1));
% end
nominal_traj.x = x_p;
nominal_traj.u = u_p;
end
function YesNo = is_constraints_violated(open_loop_traj) % this function checks if the "open_loop_traj" violates any constraints or not. For example it checks collision with obstacles.
% In this class the open loop trajectories are indeed straight
% lines. So, we use following simplified procedure to check the
% collisions.
Obst=obstacles_class.obst;
edge_start = open_loop_traj.x(1:2,1);
edge_end = open_loop_traj.x(1:2,end);
N_obst=size(Obst,2);
intersection=0;
for ib=1:N_obst
X_obs=[Obst{ib}(:,1);Obst{ib}(1,1)];
Y_obs=[Obst{ib}(:,2);Obst{ib}(1,2)];
X_edge=[edge_start(1);edge_end(1)];
Y_edge=[edge_start(2);edge_end(2)];
[x_inters,~] = polyxpoly(X_obs,Y_obs,X_edge,Y_edge);
if ~isempty(x_inters)
intersection=intersection+1;
end
end
if intersection>0
YesNo=1;
else
YesNo=0;
end
end
function traj_plot_handle = draw_nominal_traj(nominal_traj, varargin)
s_node_2D_loc = nominal_traj.x(1:2,1);
e_node_2D_loc = nominal_traj.x(1:2,end);
% retrieve PRM parameters provided by the user
disp('the varargin need to be parsed here')
% edge_spec = obj.par.edge_spec;
% edge_width = obj.par.edge_width;
edge_spec = '-b';
edge_width = 2;
% drawing the 2D edge line
traj_plot_handle = plot([s_node_2D_loc(1),e_node_2D_loc(1)],[s_node_2D_loc(2),e_node_2D_loc(2)],edge_spec,'linewidth',edge_width);
end
end
methods (Access = private)
function nominal_traj = generate_open_loop_point2point_traj_turn_move_turn(obj , start_node_ind, end_node_ind)
% I do not use this function anymore. But I kept it for future
% references.
X_initial = obj.nodes(start_node_ind).val;
X_final = obj.nodes(end_node_ind).val;
% parameters
omega_path=user_data_class.par.motion_model_parameters.omega_const_path; % constant rotational velocity during turnings
dt=user_data_class.par.motion_model_parameters.dt;
V_path=user_data_class.par.motion_model_parameters.V_const_path; % constant translational velocity during straight movements
stDim = Omni_directional_robot.stDim;
ctDim=Omni_directional_robot.ctDim;
r=Omni_directional_robot.robot_link_length;
th_p = atan2( X_final(2)-X_initial(2) , X_final(1)-X_initial(1) ); % the angle of edge % note that "th_p" is already between -pi and pi, since it is the output of "atan2"
%--------------Pre-Rotation number of steps
if abs(X_initial(3))>pi, X_initial(3)=(X_initial(3)-sign(X_initial(3))*2*pi); end % Here, we bound the initial angle "X_initial(3)" between -pi and pi
pre_delta_th_p = th_p - X_initial(3); % turning angle at the beginning of the edge (to align robot with edge)
if abs(pre_delta_th_p)>pi, pre_delta_th_p=(pre_delta_th_p-sign(pre_delta_th_p)*2*pi); end % Here, we bound "pre_delta_th_p" between -pi and pi
pre_rotation_steps = abs( pre_delta_th_p/(omega_path*dt) );
%--------------Translation number of steps
delta_disp = norm( X_final(1:2) - X_initial(1:2) );
translation_steps = abs(delta_disp/(V_path*dt));
%--------------Post-Rotation number of steps
if abs(X_final(3))>pi, X_final(3)=(X_final(3)-sign(X_final(3)*2*pi)); end % Here, we bound the initial angle "X_final(3)" between -pi and pi
post_delta_th_p = X_final(3) - th_p; % turning angle at the end of the edge (to align robot with the end node)
if abs(post_delta_th_p)>pi, post_delta_th_p=(post_delta_th_p-sign(post_delta_th_p)*2*pi); end % Here, we bound "post_delta_th_p" between -pi and pi
post_rotation_steps = abs( post_delta_th_p/(omega_path*dt) );
%--------------Total number of steps
kf = floor(pre_rotation_steps)+1+floor(translation_steps)+1+floor(post_rotation_steps)+1;
u_p=nan(ctDim,kf+1);
%=====================Pre-Rotation
u_const = ones(3,1)*r*omega_path*sign(pre_delta_th_p);
u_p(: , 1:floor(pre_rotation_steps)) = repmat( u_const,1,floor(pre_rotation_steps) );
u_const_end = ones(3,1)*r*omega_path*sign(pre_delta_th_p)*(pre_rotation_steps-floor(pre_rotation_steps));
u_p(:,floor(pre_rotation_steps)+1)=u_const_end; % note that you cannot replace "floor(pre_rotation_steps)+1" by "ceil(pre_rotation_steps)", as it may be a whole number.
last_k = floor(pre_rotation_steps)+1;
%=====================Translations
T_inv = [-sin(th_p), cos(th_p) ,r;
-sin(pi/3-th_p),-cos(pi/3-th_p) ,r;
sin(pi/3+th_p) ,-cos(pi/3+th_p) ,r];
u_const=T_inv*[V_path*cos(th_p);V_path*sin(th_p);0];
u_p( : , last_k+1:last_k + floor(translation_steps) ) = repmat(u_const,1,floor(translation_steps));
%Note that in below line we are using "u_const", in which the "Inv_Dyn"
%has been already accounted for. So, we do not need to multiply it with
%"Inv_Dyn" again.
u_const_end = u_const*(translation_steps - floor(translation_steps));
u_p( : , last_k + floor(translation_steps)+1 ) = u_const_end;
%=====================Post-Rotation
last_k = last_k + floor(translation_steps)+1;
u_const = ones(3,1)*r*omega_path*sign(post_delta_th_p);
u_p(: , last_k+1:last_k+floor(post_rotation_steps)) = repmat( u_const,1,floor(post_rotation_steps) );
u_const_end = ones(3,1)*r*omega_path*sign(post_delta_th_p)*(post_rotation_steps-floor(post_rotation_steps));
u_p(:,last_k+floor(post_rotation_steps)+1)=u_const_end; % note that you cannot replace "floor(pre_rotation_steps)+1" by "ceil(pre_rotation_steps)", as it may be a whole number.
% noiselss motion
x_p = zeros(stDim,kf+1);
x_p(:,1) = X_initial;
for k = 1:kf
x_p(:,k+1) = Omni_directional_robot.f_discrete(x_p(:,k),u_p(:,k),zeros(Omni_directional_robot.wDim,1));
end
nominal_traj.x = x_p;
nominal_traj.u = u_p;
end
end
end
function [Un,Wg] = generate_control_and_indep_process_noise(U)
% generate Un
indep_part_of_Un = randn(Omni_directional_robot.ctDim,1);
P_Un = control_noise_covariance(U);
Un = indep_part_of_Un.*diag(P_Un.^(1/2));
% generate Wg
Wg = mvnrnd(zeros(Omni_directional_robot.stDim,1),Omni_directional_robot.P_Wg)';
end
function P_Un = control_noise_covariance(U)
u_std=(Omni_directional_robot.eta_u).*U+(Omni_directional_robot.sigma_b_u);
P_Un=diag(u_std.^2);
end
|
github
|
mubeipeng/focused_slam-master
|
Unicycle_robot.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/Unicycle_robot.m
| 38,881 |
utf_8
|
364ab552f2479dc26544c3b1eaa1dbf9
|
%% Class Definition
classdef Unicycle_robot < MotionModel_interface
%============================== UNICYCLE MOTION MODEL =========================================
% Note that because the class is defined as a handle class, the
% properties must be defined such that they do not change from an
% object to another one.
%% Properties
properties (Constant = true)
stDim = state.dim; % state dimension
ctDim = 2; % control vector dimension
wDim = 5; % Process noise (W) dimension % For the generality we also consider the additive noise on kinematics equation (3 dimension), but it most probably will set to zero. The main noise is a 2 dimensional noise which is added to the controls.
dt = user_data_class.par.motion_model_parameters.dt;
base_length = user_data_class.par.motion_model_parameters.base_length; % distance between robot's rear wheels.
sigma_b_u = user_data_class.par.motion_model_parameters.sigma_b_u_unicycle;
eta_u = user_data_class.par.motion_model_parameters.eta_u_unicycle;
P_Wg = user_data_class.par.motion_model_parameters.P_Wg;
zeroNoise = zeros(Unicycle_robot.wDim,1);
end
properties (Constant = true) % orbit-related properties
turn_radius_min = 1.5*0.1; % indeed we need to define the minimum linear velocity in turnings (on orbits) and then find the minimum radius accordingly. But, we picked the more intuitive way.
angular_velocity_max = 90*pi/180; % degree per second (converted to radian per second)
linear_velocity_min_on_orbit = Unicycle_robot.turn_radius_min*Unicycle_robot.angular_velocity_max; % note that on the straight line the minimum velocity can go to zero. But, in turnings (on orbit) the linear velocity cannot fall below this value.
linear_velocity_max = 0.5*10;
end
%% Methods
methods (Static = true)
%% Continuous dynamics
function x_dot = f_contin(x,u,w) %#ok<STOUT,INUSD>
% This is not needed yet in unicycle model.
end
%% Discrete dynamics
% $$ x_k = x_{k-1}+ [V_k\cos\theta_k, V_k\sin\theta_k,
% \omega_k]^T\delta t + [V^n_k\cos\theta_k, V^n_k\sin\theta_k,
% \omega^n_k]^T\sqrt{\delta t} + W^g\sqrt{\delta t}$$
function x_next = f_discrete(x,u,w)
if length(u) ~= 2, error('SFMP: In this unicycle model, the dimension of control has to be 2'), end
Un = w(1:Unicycle_robot.ctDim); % The size of Un may be different from ctDim in some other model.
Wg = w(Unicycle_robot.ctDim+1 : Unicycle_robot.wDim); % The size of Wg may be different from stDim in some other model.
c = cos(x(3));
s = sin(x(3));
d_t = Unicycle_robot.dt;
x_next = x + [u(1)*c ; u(1)*s ; u(2)]*d_t + [Un(1)*c ; Un(1)*s ; Un(2)]*sqrt(d_t) + Wg*sqrt(d_t);
end
%% Matrix A: State Jacobian in Discrete dynamics
%
% $$ \mathbf{A} = \frac{\partial x_k}{\partial x_{k-1}} = I
% + \left(
% \begin{array}{ccc}
% 0 & 0 & -V_k^p\sin\theta^p\\
% 0 & 0 & V_k^p\cos\theta^p\\
% 0 & 0 & 0
% \end{array}\right) \delta t
% + \left(
% \begin{array}{ccc}
% 0 & 0 & -V_k^n\sin\theta^p\\
% 0 & 0 & V_k^n\cos\theta^p\\
% 0 & 0 & 0
% \end{array}\right)\sqrt{\delta t} $$
%
% Note that in most cases, we assume that we do not have access to
% the exact value of noises. Thus, we input $\mathbf{E}(V^n)$, which is zero to
% compute the linearization matrices.
function A = df_dx_func(x,u,w)
if (length(u) ~= 2 || length(w) ~= 5), error('SFMP: In this unicycle model, the dimension of control has to be 2 and noise has to be 5'), end
Un = w(1:Unicycle_robot.ctDim); % The size of Un may be different from ctDim in some other model.
% Wg = w(Unicycle_robot.ctDim+1 : Unicycle_robot.wDim);
% % The size of Wg may be different from stDim in some other
% model. In this Jacobian "Wg" does not appear.
c = cos(x(3));
s = sin(x(3));
d_t = Unicycle_robot.dt;
A = eye(Unicycle_robot.stDim) + [0 0 -u(1)*s; 0 0 u(1)*c; 0 0 0] * d_t + [0 0 -Un(1)*s; 0 0 Un(1)*c; 0 0 0] * sqrt(d_t);
end
%% Matrix A: State Jacobian in Continuous dynamics
function Acontin = df_contin_dx(x,u,w) %#ok<STOUT,INUSD>
% Not yet implemented.
end
%% Matrix B: State to Control Jacobian in Discrete dynamics
%
% $$ \mathbf{B} = \frac{\partial x_k}{\partial u_{k-1}} =
% \left(
% \begin{array}{cc}
% \cos\theta^p & 0\\
% \sin\theta^p & 0\\
% 0 & 1
% \end{array}\right) \delta t $$
%
function B = df_du_func(x,u,w) %#ok<INUSD>
th = x(3);
B = [cos(th) , 0 ; sin(th) , 0 ; 0 , 1] * Unicycle_robot.dt;
end
%% Matrix G: State to noise Jacobian in Discrete dynamics
%
% $$ \mathbf{G} = \frac{\partial x_k}{\partial w_{k-1}} =
% \left(
% \begin{array}{ccccc}
% \cos\theta^p & 0 & 1 & 0 & 0\\
% \sin\theta^p & 0 & 0 & 1 & 0\\
% 0 & 1 & 0 & 0 & 1
% \end{array}\right) \sqrt{\delta t} $$
%
function G = df_dw_func(x,u,w) %#ok<INUSD>
th=x(3);
G = [cos(th) , 0 , 1 , 0 , 0 ; sin(th) , 0 , 0 ,1,0 ; 0 , 1 , 0 ,0,1] * sqrt(Unicycle_robot.dt);
end
%% Generating process noise
% The whole process noise $w$ consists of control-dependent noise $U_n$ and
% control-independent noise $W^g$.
function w = generate_process_noise(x,u) %#ok<INUSD>
[Un,Wg] = generate_control_and_indep_process_noise(u);
w = [Un;Wg];
end
%% Computing process noise covarinace
function Q_process_noise = process_noise_cov(x,u) %#ok<INUSD>
P_Un = control_noise_covariance(u);
Q_process_noise = blkdiag(P_Un,Unicycle_robot.P_Wg);
end
%% Computing planned open-loop deterministic controls (or nominal controls) for unicycle model.
function nominal_traj = generate_open_loop_point2point_traj(x_initial,x_final)
% "x_initial" and "x_final" are vectors that indicate the start
% and final position of the state trajectory, we are planning
% the control "up" for.
if isa(x_initial , 'state'), x_initial = x_initial.val; end
if isa(x_final , 'state'), x_final = x_final.val; end
% minimum turn radius resutls from dividing the minimum linear
% velocity to maximum angular velocity. However, here we assume
% that the linear velocity is constant.
radius = Unicycle_robot.turn_radius_min;
initial_circle_center = [radius*cos(x_initial(3)-pi/2) ; radius*sin(x_initial(3)-pi/2)] + x_initial(1:2);
final_circle_center = [radius*cos(x_final(3)-pi/2) ; radius*sin(x_final(3)-pi/2)] + x_final(1:2);
% tth = 0:0.1:2*pi+.1;plot(initial_circle_center(1)+radius*cos(tth), initial_circle_center(2)+radius*sin(tth)); %TO DEBUG - DONT DELETE
% tth = 0:0.1:2*pi+.1;plot(final_circle_center(1)+radius*cos(tth), final_circle_center(2)+radius*sin(tth)); %TO DEBUG - DONT DELETE
gamma_tangent = atan2( final_circle_center(2) - initial_circle_center(2) , final_circle_center(1) - initial_circle_center(1) ); % The angle of the tangent line
gamma_start_of_tangent_line = gamma_tangent + pi/2; % the angle on which the starting point of the tangent line lies on orbit i.
gamma_end_of_tangent_line = gamma_tangent + pi/2; % the angle on which the ending point of the tangent line lies on orbit i.
initial_robot_gamma = x_initial(3) + pi/2; % Note that this is not robot's heading angle. This says that at which angle robot lies on the circle.
final_robot_gamma = x_final(3) + pi/2; % Note that this is not robot's heading angle. This says that at which angle robot lies on the circle.
% Turn part on the first circle
entire_th_on_initial_circle = delta_theta_turn(initial_robot_gamma, gamma_start_of_tangent_line, 'cw'); % NOTE: this must be a negative number as we turn CLOCKWISE.
delta_theta_on_turns = - Unicycle_robot.angular_velocity_max * Unicycle_robot.dt ; %VERY IMPORTANT: since we want to traverse the circles clockwise, the angular velocity has to be NEGATIVE.
kf_pre_rational = entire_th_on_initial_circle/delta_theta_on_turns;
kf_pre = ceil(kf_pre_rational);
V_pre = Unicycle_robot.linear_velocity_min_on_orbit * [ones(1,kf_pre-1) , kf_pre_rational-floor(kf_pre_rational)];
omega_pre = -Unicycle_robot.angular_velocity_max * [ones(1,kf_pre-1) , kf_pre_rational-floor(kf_pre_rational)]; %VERY IMPORTANT: since we want to traverse the circles clockwise, the angular velocity has to be NEGATIVE.
u_pre = [V_pre ; omega_pre];
w_zero = zeros(Unicycle_robot.wDim,1); % no noise
x_pre(:,1) = x_initial;
for k=1:kf_pre
x_pre(:,k+1) = Unicycle_robot.f_discrete(x_pre(:,k),u_pre(:,k),w_zero);
% tmp = state(x_pre(:,k+1));tmp.draw(); % FOR DEBUGGING
end
% Line part
tanget_line_length = norm ( final_circle_center - initial_circle_center ) ;
step_length = Unicycle_robot.linear_velocity_max * Unicycle_robot.dt;
kf_line_rational = tanget_line_length/step_length;
kf_line = ceil(kf_line_rational);
V_line = Unicycle_robot.linear_velocity_max * [ones(1,kf_line-1) , kf_line_rational-floor(kf_line_rational)];
omega_line = zeros(1,kf_line);
u_line = [V_line;omega_line];
x_line(:,1) = x_pre(:,kf_pre+1);
for k=1:kf_line
x_line(:,k+1) = Unicycle_robot.f_discrete(x_line(:,k),u_line(:,k),w_zero);
% tmp = state(x_line(:,k+1));tmp.draw(); % FOR DEBUGGING
end
% Turn part on the final circle
th_on_final_circle = delta_theta_turn(gamma_end_of_tangent_line, final_robot_gamma, 'cw'); % NOTE: this must be a negative number as we turn CLOCKWISE.
kf_post_rational = th_on_final_circle/delta_theta_on_turns;
kf_post = ceil(kf_post_rational);
V_post = Unicycle_robot.linear_velocity_min_on_orbit * [ones(1,kf_post-1) , kf_post_rational-floor(kf_post_rational)];
omega_post = -Unicycle_robot.angular_velocity_max * [ones(1,kf_post-1) , kf_post_rational-floor(kf_post_rational)]; %VERY IMPORTANT: since we want to traverse the circles clockwise, the angular velocity has to be NEGATIVE.
u_post = [V_post ; omega_post];
x_post(:,1) = x_line(:,kf_line+1);
for k=1:kf_post
x_post(:,k+1) = Unicycle_robot.f_discrete(x_post(:,k),u_post(:,k),w_zero);
% tmp = state(x_post(:,k+1));tmp.draw(); % FOR DEBUGGING
end
nominal_traj.x = [x_pre(:,1:kf_pre) , x_line(:,1:kf_line) , x_post(:,1:kf_post+1)]; % This line is written very carefully. So, dont worry about its correctness!
nominal_traj.u = [u_pre(:,1:kf_pre) , u_line(:,1:kf_line) , u_post(:,1:kf_post)]; % This line is written very carefully. So, dont worry about its correctness!
end
%% Computing planned open-loop deterministic controls (or nominal controls) for unicycle model.
function nominal_traj = generate_VALID_open_loop_point2point_traj(x_initial,x_final)
% "x_initial" and "x_final" are vectors that indicate the start
% and final position of the state trajectory, we are planning
% the control "up" for.
if isa(x_initial , 'state'), x_initial = x_initial.val; end
if isa(x_final , 'state'), x_final = x_final.val; end
% minimum turn radius resutls from dividing the minimum linear
% velocity to maximum angular velocity. However, here we assume
% that the linear velocity is constant.
radius = Unicycle_robot.turn_radius_min;
initial_circle_center = [radius*cos(x_initial(3)-pi/2) ; radius*sin(x_initial(3)-pi/2)] + x_initial(1:2);
final_circle_center = [radius*cos(x_final(3)-pi/2) ; radius*sin(x_final(3)-pi/2)] + x_final(1:2);
% tth = 0:0.1:2*pi+.1;plot(initial_circle_center(1)+radius*cos(tth), initial_circle_center(2)+radius*sin(tth)); %TO DEBUG - DONT DELETE
% tth = 0:0.1:2*pi+.1;plot(final_circle_center(1)+radius*cos(tth), final_circle_center(2)+radius*sin(tth)); %TO DEBUG - DONT DELETE
gamma_tangent = atan2( final_circle_center(2) - initial_circle_center(2) , final_circle_center(1) - initial_circle_center(1) ); % The angle of the tangent line
gamma_start_of_tangent_line = gamma_tangent + pi/2; % the angle on which the starting point of the tangent line lies on orbit i.
gamma_end_of_tangent_line = gamma_tangent + pi/2; % the angle on which the ending point of the tangent line lies on orbit i.
initial_robot_gamma = x_initial(3) + pi/2; % Note that this is not robot's heading angle. This says that at which angle robot lies on the circle.
final_robot_gamma = x_final(3) + pi/2; % Note that this is not robot's heading angle. This says that at which angle robot lies on the circle.
only_forward_motion = 0;
% Turn part on the first circle
entire_th_on_initial_circle = delta_theta_turn(initial_robot_gamma, gamma_start_of_tangent_line, 'cw'); % NOTE: this must be a negative number as we turn CLOCKWISE.
if only_forward_motion || entire_th_on_initial_circle >= -pi % keep going forward, where heading direction points to the "clockwise" direction.
delta_theta_on_turns = - Unicycle_robot.angular_velocity_max * Unicycle_robot.dt ; %VERY IMPORTANT: since we want to traverse the circles clockwise, the angular velocity has to be NEGATIVE.
kf_pre_rational = entire_th_on_initial_circle/delta_theta_on_turns;
kf_pre = ceil(kf_pre_rational);
V_pre = Unicycle_robot.linear_velocity_min_on_orbit * [ones(1,kf_pre-1) , kf_pre_rational-floor(kf_pre_rational)]; % In the forward motion, the linear velocity has to be positive
omega_pre = -Unicycle_robot.angular_velocity_max * [ones(1,kf_pre-1) , kf_pre_rational-floor(kf_pre_rational)]; %VERY IMPORTANT: since we want to traverse the circles clockwise, the angular velocity has to be NEGATIVE.
else % going backwards, where the heading direction still points to the "clockwise" direction.
entire_th_on_initial_circle = 2*pi + entire_th_on_initial_circle; % Note that the "entire_th_on_final_circle" before summation is negative, and after summation gets positive.
delta_theta_on_turns = Unicycle_robot.angular_velocity_max * Unicycle_robot.dt ; %VERY IMPORTANT: since we want to traverse the circles clockwise BUT BACKWARDS, the angular velocity has to be POSITIVE.
kf_pre_rational = entire_th_on_initial_circle/delta_theta_on_turns;
kf_pre = ceil(kf_pre_rational);
V_pre = - Unicycle_robot.linear_velocity_min_on_orbit * [ones(1,kf_pre-1) , kf_pre_rational-floor(kf_pre_rational)]; % In backwards motion, the linear velocity has to be negative
omega_pre = Unicycle_robot.angular_velocity_max * [ones(1,kf_pre-1) , kf_pre_rational-floor(kf_pre_rational)]; %VERY IMPORTANT: since we want to traverse the circles clockwise BUT BACKWARDS, the angular velocity has to be POSITIVE.
end
u_pre = [V_pre ; omega_pre];
w_zero = zeros(Unicycle_robot.wDim,1); % no noise
x_pre(:,1) = x_initial;
for k=1:kf_pre
x_pre(:,k+1) = Unicycle_robot.f_discrete(x_pre(:,k),u_pre(:,k),w_zero);
tmp = state(x_pre(:,k+1)); if tmp.is_constraint_violated, nominal_traj =[]; return; end
% tmp.draw(); % FOR DEBUGGING
end
% Line part
tanget_line_length = norm ( final_circle_center - initial_circle_center ) ;
step_length = Unicycle_robot.linear_velocity_max * Unicycle_robot.dt;
kf_line_rational = tanget_line_length/step_length;
kf_line = ceil(kf_line_rational);
V_line = Unicycle_robot.linear_velocity_max * [ones(1,kf_line-1) , kf_line_rational-floor(kf_line_rational)];
omega_line = zeros(1,kf_line);
u_line = [V_line;omega_line];
x_line(:,1) = x_pre(:,kf_pre+1);
for k=1:kf_line
x_line(:,k+1) = Unicycle_robot.f_discrete(x_line(:,k),u_line(:,k),w_zero);
tmp = state(x_line(:,k+1));%% if tmp.is_constraint_violated, nominal_traj =[]; return; end
% tmp.draw(); % FOR DEBUGGING
end
% Turn part on the final circle
entire_th_on_final_circle = delta_theta_turn(gamma_end_of_tangent_line, final_robot_gamma, 'cw'); % NOTE: this must be a negative number as we turn CLOCKWISE.
if only_forward_motion || entire_th_on_final_circle >= -pi
delta_theta_on_turns = - Unicycle_robot.angular_velocity_max * Unicycle_robot.dt ; %VERY IMPORTANT: since we want to traverse the circles clockwise, the angular velocity has to be NEGATIVE.
kf_post_rational = entire_th_on_final_circle/delta_theta_on_turns;
kf_post = ceil(kf_post_rational);
V_post = Unicycle_robot.linear_velocity_min_on_orbit * [ones(1,kf_post-1) , kf_post_rational-floor(kf_post_rational)]; % In the forward motion, the linear velocity has to be positive
omega_post = - Unicycle_robot.angular_velocity_max * [ones(1,kf_post-1) , kf_post_rational-floor(kf_post_rational)]; %VERY IMPORTANT: since we want to traverse the circles clockwise, the angular velocity has to be NEGATIVE.
else
entire_th_on_final_circle = 2*pi + entire_th_on_final_circle; % Note that the "entire_th_on_final_circle" before summation is negative, and after summation gets positive.
delta_theta_on_turns = Unicycle_robot.angular_velocity_max * Unicycle_robot.dt ; %VERY IMPORTANT: since we want to traverse the circles clockwise BUT BACKWARDS, the angular velocity has to be POSITIVE.
kf_post_rational = entire_th_on_final_circle/delta_theta_on_turns;
kf_post = ceil(kf_post_rational);
V_post = - Unicycle_robot.linear_velocity_min_on_orbit * [ones(1,kf_post-1) , kf_post_rational-floor(kf_post_rational)]; % In backwards motion, the linear velocity has to be negative
omega_post = Unicycle_robot.angular_velocity_max * [ones(1,kf_post-1) , kf_post_rational-floor(kf_post_rational)]; %VERY IMPORTANT: since we want to traverse the circles clockwise BUT BACKWARDS, the angular velocity has to be POSITIVE.
end
u_post = [V_post ; omega_post];
x_post(:,1) = x_line(:,kf_line+1);
for k=1:kf_post
x_post(:,k+1) = Unicycle_robot.f_discrete(x_post(:,k),u_post(:,k),w_zero);
tmp = state(x_post(:,k+1)); if tmp.is_constraint_violated, nominal_traj =[]; return; end
% tmp.draw(); % FOR DEBUGGING
end
nominal_traj.x = [x_pre(:,1:kf_pre) , x_line(:,1:kf_line) , x_post(:,1:kf_post+1)]; % This line is written very carefully. So, dont worry about its correctness!
nominal_traj.u = [u_pre(:,1:kf_pre) , u_line(:,1:kf_line) , u_post(:,1:kf_post)]; % This line is written very carefully. So, dont worry about its correctness!
end
%% Computing planned open-loop deterministic state trajectory (or nominal trajectory) for unicycle model.
% In computing the planned trajectory, system is assumed to be deterministic, so the noise is zero.
%
% $$ x^p_{K+1} = f (x^p_{K}, u^p_k, 0 ) $$
%
function x_p = compute_planned_traj(x_initial,u_p,kf)
% noiselss motion
x_p = zeros(state.dim,kf+1);
x_p(:,1) = x_initial;
for k = 1:kf
x_p(:,k+1) = Unicycle_robot.f_discrete(x_p(:,k),u_p(:,k),zeros(Unicycle_robot.wDim,1));
end
end
%% Sample a valid orbit (periodic trajectory)
function orbit = sample_a_valid_orbit()
orbit_center = state.sample_a_valid_state();
if isempty( orbit_center)
orbit = [];
return
else
orbit = Unicycle_robot.generate_orbit(orbit_center);
orbit = Unicycle_robot.draw_orbit(orbit);
end
end
%% Construct an orbit
function orbit = generate_orbit(orbit_center)
% minimum orbit radius resutls from dividing the minimum linear
% velocity to maximum angular velocity. However, here we assume
% that the linear velocity is constant.
orbit.radius = Unicycle_robot.turn_radius_min;
orbit_length_meter = 2*pi*orbit.radius;
orbit_length_time_continuous = orbit_length_meter/Unicycle_robot.linear_velocity_min_on_orbit;
T_rational = orbit_length_time_continuous/Unicycle_robot.dt;
T = ceil(T_rational);
orbit.period = T;
orbit.center = orbit_center;
% defining controls on the orbit
V_p = Unicycle_robot.linear_velocity_min_on_orbit * [ones(1,T-1) , T_rational-floor(T_rational)]; % we traverse the orbit with minimum linear velocity
omega_p = Unicycle_robot.angular_velocity_max * [ones(1,T-1) , T_rational-floor(T_rational)]; % we traverse the orbit with maximum angular velocity
u_p = [V_p;omega_p];
w_zero = zeros(Unicycle_robot.wDim,1); % no noise
% defining state steps on the orbit
x_p(:,1) = [orbit_center.val(1:2) - [0;orbit.radius] ; 0*pi/180]; % initial x
for k=1:T
x_p(:,k+1) = Unicycle_robot.f_discrete(x_p(:,k),u_p(:,k),w_zero);
end
orbit.x = x_p(:,1:T); % "x_p" is of length T+1, but "x_p(:,T+1)" is equal to "x_p(:,1)"
orbit.u = u_p; % "u_p" is of length T.
orbit.plot_handle = [];
end
%% Draw an orbit
function orbit = draw_orbit(orbit,varargin)
% This function draws the orbit.
% default values
orbit_color = 'b'; % Default value for "OrbitTextColor" property. % User-provided value for "OrbitTextColor" property.
orbit_width = 2; % User-provided value for "orbit_width" property. % User-provided value for shifting the text a little bit to the left. % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
robot_shape = 'triangle'; % The shape of robot (to draw trajectories and to show direction of edges and orbits)
robot_size = 1; % Robot size on orbits (to draw trajectories and to show direction of edges and orbits)
orbit_trajectory_flag = 0; % Make it one if you want to see the orbit trajectories. Zero, otherwise.
text_size = 12;
text_color = 'b';
text_shift = 0.8;
orbit_text = [];
% parsing the varargin
if ~isempty(varargin)
for i = 1 : 2 : length(varargin)
switch lower(varargin{i})
case lower('RobotSize')
robot_size = varargin{i+1};
case lower('OrbitWidth')
orbit_width = varargin{i+1};
case lower('OrbitColor')
orbit_color = varargin{i+1};
case lower('OrbitText')
orbit_text = varargin{i+1};
end
end
end
% start drawing
if orbit_trajectory_flag == 1
orbit.plot_handle = [];
for k=1:orbit.period
Xstate = state(orbit.x(:,k));
Xstate = Xstate.draw('RobotShape',robot_shape,'robotsize',robot_size);
orbit.plot_handle = [orbit.plot_handle,Xstate.head_handle,Xstate.text_handle,Xstate.tria_handle];
end
tmp = plot(orbit.x(1,:) , orbit.x(2,:),orbit_color);
orbit.plot_handle = [orbit.plot_handle,tmp];
else
orbit.plot_handle = [];
th_orbit_draw = [0:0.1:2*pi , 2*pi];
x_orbit_draw = orbit.center.val(1) + orbit.radius*cos(th_orbit_draw);
y_orbit_draw = orbit.center.val(2) + orbit.radius*sin(th_orbit_draw);
tmp_h = plot(x_orbit_draw,y_orbit_draw,'lineWidth',orbit_width);
Xstate = state(orbit.x(:,1));
Xstate = Xstate.draw('RobotShape',robot_shape,'robotsize',robot_size);
orbit.plot_handle = [orbit.plot_handle,tmp_h,Xstate.head_handle,Xstate.text_handle,Xstate.tria_handle];
end
if ~isempty(orbit_text)
text_pos = orbit.center.val;
text_pos(1) = text_pos(1) - text_shift; % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
tmp_handle = text( text_pos(1), text_pos(2), orbit_text, 'fontsize', text_size, 'color', text_color);
orbit.plot_handle = [orbit.plot_handle,tmp_handle];
end
end
%% Generate open-loop Orbit-to-Orbit trajectory
function nominal_traj = generate_VALID_open_loop_orbit2orbit_traj(start_orbit, end_orbit) % generates open-loop trajectories between two start and end orbits
% check if the both orbits are turning in the same
% direction or not.
direction_start_orbit = sign(start_orbit.u(1,1))*sign(start_orbit.u(2,1));
direction_end_orbit = sign(end_orbit.u(1,1))*sign(end_orbit.u(2,1));
% finding the connecting edge between orbits.
if direction_start_orbit == direction_end_orbit % both orbits turn in a same direction
gamma = atan2( end_orbit.center.val(2) - start_orbit.center.val(2) , end_orbit.center.val(1) - start_orbit.center.val(1) );
temp_edge_start = start_orbit.radius * [ cos(gamma-pi/2) ; sin(gamma-pi/2) ] + start_orbit.center.val(1:2);
temp_edge_end = end_orbit.radius* [ cos(gamma-pi/2) ; sin(gamma-pi/2) ] + end_orbit.center.val(1:2);
else
error('different directions have not been implemented in PNPRM yet.')
end
%temp_traj.x(:,1) = temp_edge_start; temp_traj.x(:,2) = temp_edge_end; % we generate this trajectory (only composed of start and end points) to check the collision probabilities before generating the edges.
%collision = Unicycle_robot.is_constraints_violated(temp_traj); % checking intersection with obstacles
% if collision == 1
% nominal_traj = [];
% return
% else
% % construction edge trajectory
tmp_traj_start = [temp_edge_start ; gamma ];
V_p = start_orbit.u(1,1);
step_length = V_p * Unicycle_robot.dt;
edge_length = norm ( end_orbit.center.val - start_orbit.center.val ) ;
edge_steps = floor(edge_length/step_length);
omega_p = 0;
u_p_single = [V_p;omega_p];
u_p = repmat(u_p_single ,1,edge_steps);
w_zero = zeros(Unicycle_robot.wDim , 1); % no noise
x_p(:,1) = tmp_traj_start;
for k =1:edge_steps
x_p(:,k+1) = Unicycle_robot.f_discrete(x_p(:,k),u_p(:,k),w_zero);
tmp = state(x_p(:,k+1)); if tmp.is_constraint_violated, nominal_traj =[]; return; end
% tmp.draw(); % FOR DEBUGGING
end
nominal_traj.x = x_p;
nominal_traj.u = u_p;
end
%% check if the trajectory is collision-free or not
function YesNo = is_constraints_violated(open_loop_traj) % this function checks if the "open_loop_traj" violates any constraints or not. For example it checks collision with obstacles.
% In this class the open loop trajectories are indeed straight
% lines. So, we use following simplified procedure to check the
% collisions.
error('This function is obsolete. Instead, we have the "generate_VALID_open_loop_point2point_traj" function')
YesNo = 0;
Obst = obstacles_class.obst;
edge_start = open_loop_traj.x(1:2 , 1);
edge_end = open_loop_traj.x(1:2 , end);
N_obst = size(Obst,2);
for ib=1:N_obst
X_obs=[Obst{ib}(:,1);Obst{ib}(1,1)];
Y_obs=[Obst{ib}(:,2);Obst{ib}(1,2)];
X_edge=[edge_start(1);edge_end(1)];
Y_edge=[edge_start(2);edge_end(2)];
[x_inters,~] = polyxpoly(X_obs,Y_obs,X_edge,Y_edge);
if ~isempty(x_inters)
YesNo=1;
return
end
end
end
%% Draw nominal trajectories
function traj_plot_handle = draw_nominal_traj(nominal_traj, traj_flag)
traj_plot_handle = [];
if traj_flag == 1
for k = 1 : size(nominal_traj.x , 2)
tmp_Xstate = state (nominal_traj.x(:,k) );
tmp_Xstate.draw('RobotShape','triangle','robotsize',1);%,'TriaColor',color(cycles));
%traj_plot_handle(k:k+2) =
%[tmp_Xstate.head_handle,tmp_Xstate.text_handle,tmp_Xstate.tria_handle];
end
else
tmp_handle = plot(nominal_traj.x(1,:) , nominal_traj.x(2,:));
traj_plot_handle = [traj_plot_handle , tmp_handle];
len = size( nominal_traj.x , 2);
tmp_Xstate = state( nominal_traj.x(:,floor(len/2)) ); % to plot the direction of the line.
% tmp_Xstate = tmp_Xstate.draw('RobotShape','triangle','robotsize',2);
% traj_plot_handle = [traj_plot_handle , tmp_Xstate.plot_handle , tmp_Xstate.head_handle , tmp_Xstate.tria_handle , tmp_Xstate.text_handle ];
drawnow
end
end
%% Draw orbit neighborhood
function plot_handle = draw_orbit_neighborhood(orbit, scale)
tmp_th = 0:0.1:2*pi;
x = orbit.center.val(1);
y = orbit.center.val(2);
plot_handle = plot(scale*cos(tmp_th) + x , scale*sin(tmp_th) + y, '--');
end
end
end
%% Generating Control-dependent and independent noises
%
% $$ U'_n \sim \mathcal{N}(0_{2\times 1} , I_{2\times 2}), ~~~ U_n =
% (P^{U_n})^{1/2}U'_n\sim\mathcal{N}(0_{2\times 1} , P^{Un}),~~~W^g \sim \mathcal{N}(0_{3\times 1} , P^{W^g})$$
%
% The reason we do not use "mvnrnd" to generate $U_n$ is the speed. The way
% we do here is much faster than using "mvnrnd".
function [Un,Wg] = generate_control_and_indep_process_noise(U)
% generate Un
indep_part_of_Un = randn(Unicycle_robot.ctDim,1);
P_Un = control_noise_covariance(U);
Un = indep_part_of_Un.*diag(P_Un.^(1/2));
% generate Wg
Wg = mvnrnd(zeros(Unicycle_robot.stDim,1),Unicycle_robot.P_Wg)';
end
%% Generating Control-dependent Noise Covariance
%
% $$ P^{U_n} = \left(
% \begin{array}{cc}
% (\eta_V V + \sigma_{b_V})^2 & 0\\
% 0 & (\eta_{\omega} \omega + \sigma_{b_{\omega}})^2\\
% \end{array}\right) $$,
%
% where, $\eta_u=(\eta_V,\eta_{\omega})^T$ and
% $\sigma_{b_u}=(\sigma_{b_V},\sigma_{b_{\omega}})^T$.
function P_Un = control_noise_covariance(U)
u_std=(Unicycle_robot.eta_u).*U+(Unicycle_robot.sigma_b_u);
P_Un=diag(u_std.^2);
end
%% Generating deterministic open loop controls (nominal controls)
% I think this function should go out of this class maybe.
function [u_p,kf] = compute_planned_control_unicycle(X_initial,X_final)
% inputs
x_c=[X_initial(1),X_final(1)];
y_c=[X_initial(2),X_final(2)];
dt=user_data_class.par.motion_model_parameters.dt;
omega_path=user_data_class.par.motion_model_parameters.omega_const_path; % constant rotational velocity during turnings
V_path=user_data_class.par.motion_model_parameters.V_const_path; % constant translational velocity during straight movements
%stDim=Unicycle_robot.stDim;
ctDim=Unicycle_robot.ctDim;
% preallocation
th_p=zeros(1,length(x_c));
delta_th_p=zeros(1,length(x_c));
rotation_steps=zeros(length(x_c)-1,1);
delta_disp=zeros(length(x_c)-1,1);
translation_steps=zeros(length(x_c)-1,1);
total_num_steps=0;
% Dividing the motion to pure translations and rotations
th_initial=X_initial(3);
for i=1:length(x_c)-1
% rotations
th_p(i)=atan2((y_c(i+1)-y_c(i)),(x_c(i+1)-x_c(i)));
if i>1, delta_th_p(i)=th_p(i)-th_p(i-1); else delta_th_p(i)=th_p(i)-th_initial; end;
rotation_steps(i)=abs(delta_th_p(i)/(omega_path*dt));
%translations
delta_disp(i)=sqrt( (y_c(i+1)-y_c(i))^2+(x_c(i+1)-x_c(i))^2 );
translation_steps(i)=abs(delta_disp(i)/(V_path*dt));
total_num_steps=total_num_steps+ceil(rotation_steps(i))+ceil(translation_steps(i));
end
kf=total_num_steps;
% Computing Velocities along the path
% omega_path=zeros(1,kf);
% v_path=zeros(1,kf);
u_p=nan(ctDim,kf+1);
start_ind_w=1;
% end_ind_w=start_ind_w+ceil(rotation_steps(1))-1;
end_ind_w=start_ind_w+floor(rotation_steps(1));
for i=1:length(x_c)-1
%Rotation
if end_ind_w~=0
u_const = [ 0 ; omega_path*sign(delta_th_p(i)) ];
u_p(:,start_ind_w:end_ind_w-1)=repmat(u_const,1,floor(rotation_steps(i)));
u_const_end=u_const * (rotation_steps(i)-floor(rotation_steps(i)));
u_p(:,end_ind_w)=u_const_end;
end
%Translations
u_const = [ V_path ; 0 ];
u_p(:,end_ind_w+1:end_ind_w+ceil(translation_steps(i))-1)=repmat(u_const,1,floor(translation_steps(i)));
u_const_end=u_const*(translation_steps(i)-floor(translation_steps(i)));
u_p(:,end_ind_w+ceil(translation_steps(i)))=u_const_end;
%Preparing for the next path segment
if i~=length(x_c)-1 %% This "if" is just for avoiding the error massege that appears due to non-existence of rotation_steps(length(x_c))
start_ind_w=start_ind_w+ceil(rotation_steps(i))+ceil(translation_steps(i));
end_ind_w=start_ind_w+ceil(rotation_steps(i+1))-1;
end
end
% u_p=[x_dot;theta_dot];
% u_p=[u_p,[nan;nan]];
end
%% Generating deterministic open loop controls with bounded curvature (nominal controls)
% I think this function should go out of this class maybe.
function [u_p,kf] = compute_planned_control_unicycle_bounded_curvature(X_initial,X_final)
% inputs
x_c=[X_initial(1),X_final(1)];
y_c=[X_initial(2),X_final(2)];
dt=user_data_class.par.motion_model_parameters.dt;
omega_path=user_data_class.par.motion_model_parameters.omega_const_path; % constant rotational velocity during turnings
V_path=user_data_class.par.motion_model_parameters.V_const_path; % constant translational velocity during straight movements
%stDim=Unicycle_robot.stDim;
ctDim=Unicycle_robot.ctDim;
% preallocation
th_p=zeros(1,length(x_c));
delta_th_p=zeros(1,length(x_c));
rotation_steps=zeros(length(x_c)-1,1);
delta_disp=zeros(length(x_c)-1,1);
translation_steps=zeros(length(x_c)-1,1);
total_num_steps=0;
% Dividing the motion to pure translations and rotations
th_initial=X_initial(3);
for i=1:length(x_c)-1
% rotations
th_p(i)=atan2((y_c(i+1)-y_c(i)),(x_c(i+1)-x_c(i)));
if i>1, delta_th_p(i)=th_p(i)-th_p(i-1); else delta_th_p(i)=th_p(i)-th_initial; end;
rotation_steps(i)=abs(delta_th_p(i)/(omega_path*dt));
%translations
delta_disp(i)=sqrt( (y_c(i+1)-y_c(i))^2+(x_c(i+1)-x_c(i))^2 );
translation_steps(i)=abs(delta_disp(i)/(V_path*dt));
total_num_steps=total_num_steps+ceil(rotation_steps(i))+ceil(translation_steps(i));
end
kf=total_num_steps;
% Computing Velocities along the path
% omega_path=zeros(1,kf);
% v_path=zeros(1,kf);
u_p=nan(ctDim,kf+1);
start_ind_w=1;
% end_ind_w=start_ind_w+ceil(rotation_steps(1))-1;
end_ind_w=start_ind_w+floor(rotation_steps(1));
for i=1:length(x_c)-1
%Rotation
if end_ind_w~=0
u_const = [ 0 ; omega_path*sign(delta_th_p(i)) ];
u_p(:,start_ind_w:end_ind_w-1)=repmat(u_const,1,floor(rotation_steps(i)));
u_const_end=u_const * (rotation_steps(i)-floor(rotation_steps(i)));
u_p(:,end_ind_w)=u_const_end;
end
%Translations
u_const = [ V_path ; 0 ];
u_p(:,end_ind_w+1:end_ind_w+ceil(translation_steps(i))-1)=repmat(u_const,1,floor(translation_steps(i)));
u_const_end=u_const*(translation_steps(i)-floor(translation_steps(i)));
u_p(:,end_ind_w+ceil(translation_steps(i)))=u_const_end;
%Preparing for the next path segment
if i~=length(x_c)-1 %% This "if" is just for avoiding the error massege that appears due to non-existence of rotation_steps(length(x_c))
start_ind_w=start_ind_w+ceil(rotation_steps(i))+ceil(translation_steps(i));
end_ind_w=start_ind_w+ceil(rotation_steps(i+1))-1;
end
end
% u_p=[x_dot;theta_dot];
% u_p=[u_p,[nan;nan]];
end
|
github
|
mubeipeng/focused_slam-master
|
youbot_base.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/youbot_base.m
| 14,789 |
utf_8
|
8cb1348f049e23cf2bdb6ade776415b1
|
classdef youbot_base < MotionModel_interface
% Note that because the class is defined as a handle class, the
% properties must be defined such that they are do not change from an
% object to another one.
properties (Constant)
stDim = state.dim; % state dimension
ctDim = 4; % control vector dimension
wDim = 7; % Process noise (W) dimension
zeroControl = zeros(youbot_base.ctDim,1);
zeroNoise = zeros(youbot_base.wDim,1);
dt = user_data_class.par.motion_model_parameters.dt;
l1 = 0.1585*2; % (meter) distance between right and left wheel
l2 = 0.228*2; % (meter) distance between front and rear wheel
vMax = 0.8 % m/s maximum speed for individual wheels and max base velocity
sigma_b_u = user_data_class.par.motion_model_parameters.sigma_b_u_KukaBase;
eta_u = user_data_class.par.motion_model_parameters.eta_u_KukaBase;
P_Wg = user_data_class.par.motion_model_parameters.P_Wg;
end
% properties (Constant = true, SetAccess = private)
% UnDim = 3;
% WgDim = 3;
% end
methods (Static)
function x_next = f_discrete(x,u,w)
Un = w(1:youbot_base.ctDim); % The size of Un may be different from ctDim in some other model.
Wg = w(youbot_base.ctDim+1 : youbot_base.wDim); % The size of Wg may be different from stDim in some other model.
Wc = youbot_base.f_contin(x,Un,Wg);
x_next = x+youbot_base.f_contin(x,u,0)*youbot_base.dt+Wc*sqrt(youbot_base.dt);
end
function x_dot = f_contin(x,u,wg) % Do not call this function from outside of this class!! % The last input in this method should be w, instead of wg. But, since it is a only used in this class, it does not matter so much.
B = youbot_base.df_du_func(x,u,wg)/youbot_base.dt; % df_du_func is for the discrete model therefore it should be divided by dt to get the continuous B
x_dot = B*u+wg;
end
function A = df_dx_func(x,u,w)
un = w(1:youbot_base.ctDim); % The size of Un may be different from ctDim in some other model.
wg = w(youbot_base.ctDim+1 : youbot_base.wDim); % The size of Wg may be different from stDim in some other model.
A = eye(youbot_base.stDim) ...
+ youbot_base.df_contin_dx(x,u,zeros(youbot_base.stDim,1))*youbot_base.dt ...
+ youbot_base.df_contin_dx(x,un,wg)*sqrt(youbot_base.dt);
end
function Acontin = df_contin_dx(x,u,w) %#ok<INUSD>
Acontin = zeros(3,3);
end
function B = df_du_func(x,u,w) %#ok<INUSD>
gama1= 2/(youbot_base.l2-youbot_base.l1);
B = (1/4)*[-1 1 1 -1;...
1 1 1 1;...
gama1 -gama1 gama1 -gama1]*youbot_base.dt; %% this is the B for the continous system
end
function G = df_dw_func(x,u,w) %#ok<INUSD>
B = youbot_base.df_du_func(x,u,w);
G = [B,eye(youbot_base.stDim)]*sqrt(youbot_base.dt); % this calculation is for the discrete system
end
function w = generate_process_noise(x,u) %#ok<INUSD>
[Un,Wg] = generate_control_and_indep_process_noise(u);
w = [Un;Wg];
end
function Q_process_noise = process_noise_cov(x,u) %#ok<INUSD>
P_Un = control_noise_covariance(u);
Q_process_noise = blkdiag(P_Un,youbot_base.P_Wg);
end
function nominal_traj = generate_open_loop_point2point_traj(X_initial,X_final) % generates open-loop trajectories between two start and goal states
if isa(X_initial,'state'), X_initial=X_initial.val; end % retrieve the value of the state vector
if isa(X_final,'state'), X_final=X_final.val; end % retrieve the value of the state vector
B = youbot_base.df_du_func(0,0,0)/youbot_base.dt;; %% B matrix in the youbot robot does not depend on current state or input
deltaX = abs(X_final - X_initial);
t_interval = 0.8*max(deltaX)/youbot_base.vMax; % we move by 80 percent of the maxmimum velocity
kf = ceil(t_interval/ youbot_base.dt); % number of steps needed to follow the trajectory
uStar = (1/t_interval)*B'*inv(B*B')*deltaX; %
%=====================Nominal control and state trajectory generation
x_p = zeros(youbot_base.stDim,kf+1);
u_p = zeros(youbot_base.ctDim,kf);
x_p(:,1) = X_initial;
for k = 1:kf
u_p(:,k) = uStar; % "T_inv_k" maps the "velocities in body coordinate" to the control signal
x_p(:,k+1) = youbot_base.f_discrete(x_p(:,k),u_p(:,k) ,zeros(youbot_base.wDim,1)); % generaating the trajectory
end
% noiselss motion % for debug: if you uncomment the following
% lines you have to get the same "x_p_copy" as the "x_p"
% x_p_copy = zeros(stDim,kf+1);
% x_p_copy(:,1) = X_initial;
% for k = 1:kf
% x_p_copy(:,k+1) = youbot_base.f_discrete(x_p_copy(:,k),u_p(:,k),zeros(youbot_base.wDim,1));
% end
nominal_traj.x = x_p;
nominal_traj.u = u_p;
end
function nominal_traj = generate_VALID_open_loop_point2point_traj(X_initial,X_final) % generates open-loop trajectories between two start and goal states
if isa(X_initial,'state'), X_initial=X_initial.val; end % retrieve the value of the state vector
if isa(X_final,'state'), X_final=X_final.val; end % retrieve the value of the state vector
B = youbot_base.df_du_func(0,0,0)/ youbot_base.dt;; %% B matrix in the youbot robot does not depend on current state or input
deltaX = abs(X_final - X_initial);
t_interval = 0.8*max(deltaX)/youbot_base.vMax; % we move by 80 percent of the maxmimum velocity
kf = ceil(t_interval/ youbot_base.dt); % number of steps needed to follow the trajectory
uStar = (1/t_interval)*B'*inv(B*B')*deltaX; %
%=====================Nominal control and state trajectory generation
x_p = zeros(youbot_base.stDim,kf+1);
u_p = zeros(youbot_base.ctDim,kf);
x_p(:,1) = X_initial;
for k = 1:kf
u_p(:,k) = uStar; % "T_inv_k" maps the "velocities in body coordinate" to the control signal
x_p(:,k+1) = youbot_base.f_discrete(x_p(:,k),u_p(:,k) ,zeros(youbot_base.wDim,1)); % generaating the trajectory
% tmp = state(x_p(:,k+1)); if tmp.is_constraint_violated(), nominal_traj =[]; return; end
end
% noiselss motion % for debug: if you uncomment the following
% lines you have to get the same "x_p_copy" as the "x_p"
% x_p_copy = zeros(stDim,kf+1);
% x_p_copy(:,1) = X_initial;
% for k = 1:kf
% x_p_copy(:,k+1) = youbot_base.f_discrete(x_p_copy(:,k),u_p(:,k),zeros(youbot_base.wDim,1));
% end
nominal_traj.x = x_p;
nominal_traj.u = u_p;
end
function YesNo = is_constraints_violated(open_loop_traj) % this function checks if the "open_loop_traj" violates any constraints or not. For example it checks collision with obstacles.
% In this class the open loop trajectories are indeed straight
% lines. So, we use following simplified procedure to check the
% collisions.
Obst=obstacles_class.obst;
edge_start = open_loop_traj.x(1:2,1);
edge_end = open_loop_traj.x(1:2,end);
N_obst=size(Obst,2);
intersection=0;
for ib=1:N_obst
X_obs=[Obst{ib}(:,1);Obst{ib}(1,1)];
Y_obs=[Obst{ib}(:,2);Obst{ib}(1,2)];
X_edge=[edge_start(1);edge_end(1)];
Y_edge=[edge_start(2);edge_end(2)];
[x_inters,~] = polyxpoly(X_obs,Y_obs,X_edge,Y_edge);
if ~isempty(x_inters)
intersection=intersection+1;
end
end
if intersection>0
YesNo=1;
else
YesNo=0;
end
end
function traj_plot_handle = draw_nominal_traj(nominal_traj, varargin)
s_node_2D_loc = nominal_traj.x(1:2,1);
e_node_2D_loc = nominal_traj.x(1:2,end);
% retrieve PRM parameters provided by the user
disp('the varargin need to be parsed here')
% edge_spec = obj.par.edge_spec;
% edge_width = obj.par.edge_width;
edge_spec = '-b';
edge_width = 2;
% drawing the 2D edge line
traj_plot_handle = plot([s_node_2D_loc(1),e_node_2D_loc(1)],[s_node_2D_loc(2),e_node_2D_loc(2)],edge_spec,'linewidth',edge_width);
end
end
methods (Access = private)
function nominal_traj = generate_open_loop_point2point_traj_turn_move_turn(obj , start_node_ind, end_node_ind)
% I do not use this function anymore. But I kept it for future
% references.
X_initial = obj.nodes(start_node_ind).val;
X_final = obj.nodes(end_node_ind).val;
% parameters
omega_path=user_data_class.par.motion_model_parameters.omega_const_path; % constant rotational velocity during turnings
dt=user_data_class.par.motion_model_parameters.dt;
V_path=user_data_class.par.motion_model_parameters.V_const_path; % constant translational velocity during straight movements
stDim = youbot_base.stDim;
ctDim=youbot_base.ctDim;
r=youbot_base.robot_link_length;
th_p = atan2( X_final(2)-X_initial(2) , X_final(1)-X_initial(1) ); % the angle of edge % note that "th_p" is already between -pi and pi, since it is the output of "atan2"
%--------------Pre-Rotation number of steps
if abs(X_initial(3))>pi, X_initial(3)=(X_initial(3)-sign(X_initial(3))*2*pi); end % Here, we bound the initial angle "X_initial(3)" between -pi and pi
pre_delta_th_p = th_p - X_initial(3); % turning angle at the beginning of the edge (to align robot with edge)
if abs(pre_delta_th_p)>pi, pre_delta_th_p=(pre_delta_th_p-sign(pre_delta_th_p)*2*pi); end % Here, we bound "pre_delta_th_p" between -pi and pi
pre_rotation_steps = abs( pre_delta_th_p/(omega_path*dt) );
%--------------Translation number of steps
delta_disp = norm( X_final(1:2) - X_initial(1:2) );
translation_steps = abs(delta_disp/(V_path*dt));
%--------------Post-Rotation number of steps
if abs(X_final(3))>pi, X_final(3)=(X_final(3)-sign(X_final(3)*2*pi)); end % Here, we bound the initial angle "X_final(3)" between -pi and pi
post_delta_th_p = X_final(3) - th_p; % turning angle at the end of the edge (to align robot with the end node)
if abs(post_delta_th_p)>pi, post_delta_th_p=(post_delta_th_p-sign(post_delta_th_p)*2*pi); end % Here, we bound "post_delta_th_p" between -pi and pi
post_rotation_steps = abs( post_delta_th_p/(omega_path*dt) );
%--------------Total number of steps
kf = floor(pre_rotation_steps)+1+floor(translation_steps)+1+floor(post_rotation_steps)+1;
u_p=nan(ctDim,kf+1);
%=====================Pre-Rotation
u_const = ones(3,1)*r*omega_path*sign(pre_delta_th_p);
u_p(: , 1:floor(pre_rotation_steps)) = repmat( u_const,1,floor(pre_rotation_steps) );
u_const_end = ones(3,1)*r*omega_path*sign(pre_delta_th_p)*(pre_rotation_steps-floor(pre_rotation_steps));
u_p(:,floor(pre_rotation_steps)+1)=u_const_end; % note that you cannot replace "floor(pre_rotation_steps)+1" by "ceil(pre_rotation_steps)", as it may be a whole number.
last_k = floor(pre_rotation_steps)+1;
%=====================Translations
T_inv = [-sin(th_p), cos(th_p) ,r;
-sin(pi/3-th_p),-cos(pi/3-th_p) ,r;
sin(pi/3+th_p) ,-cos(pi/3+th_p) ,r];
u_const=T_inv*[V_path*cos(th_p);V_path*sin(th_p);0];
u_p( : , last_k+1:last_k + floor(translation_steps) ) = repmat(u_const,1,floor(translation_steps));
%Note that in below line we are using "u_const", in which the "Inv_Dyn"
%has been already accounted for. So, we do not need to multiply it with
%"Inv_Dyn" again.
u_const_end = u_const*(translation_steps - floor(translation_steps));
u_p( : , last_k + floor(translation_steps)+1 ) = u_const_end;
%=====================Post-Rotation
last_k = last_k + floor(translation_steps)+1;
u_const = ones(3,1)*r*omega_path*sign(post_delta_th_p);
u_p(: , last_k+1:last_k+floor(post_rotation_steps)) = repmat( u_const,1,floor(post_rotation_steps) );
u_const_end = ones(3,1)*r*omega_path*sign(post_delta_th_p)*(post_rotation_steps-floor(post_rotation_steps));
u_p(:,last_k+floor(post_rotation_steps)+1)=u_const_end; % note that you cannot replace "floor(pre_rotation_steps)+1" by "ceil(pre_rotation_steps)", as it may be a whole number.
% noiselss motion
x_p = zeros(stDim,kf+1);
x_p(:,1) = X_initial;
for k = 1:kf
x_p(:,k+1) = youbot_base.f_discrete(x_p(:,k),u_p(:,k),zeros(youbot_base.wDim,1));
end
nominal_traj.x = x_p;
nominal_traj.u = u_p;
end
end
end
function [Un,Wg] = generate_control_and_indep_process_noise(U)
% generate Un
indep_part_of_Un = randn(youbot_base.ctDim,1);
P_Un = control_noise_covariance(U);
Un = indep_part_of_Un.*diag(P_Un.^(1/2));
% generate Wg
Wg = mvnrnd(zeros(youbot_base.stDim,1),youbot_base.P_Wg)';
end
function P_Un = control_noise_covariance(U)
u_std=(youbot_base.eta_u).*U+(youbot_base.sigma_b_u);
P_Un=diag(u_std.^2);
end
|
github
|
mubeipeng/focused_slam-master
|
MotionModel_class_NotImplementedYet.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/Multi_Omni_directional_robots/MotionModel_class_NotImplementedYet.m
| 14,853 |
utf_8
|
ad172bb4f2ce9155039355759020a5ea
|
classdef MotionModel_class < MotionModel_interface
% Note that because the class is defined as a handle class, the
% properties must be defined such that they are do not change from an
% object to another one.
properties (Constant)
num_robots = user_data_class.par.state_parameters.num_robots;
stDim = state.dim; % state dimension
ctDim = state.dim; % control vector dimension
wDim = 2*state.dim; % Process noise (W) dimension
dt = user_data_class.par.motion_model_parameters.dt;
robot_link_length = user_data_class.par.motion_model_parameters.robot_link_length;
sigma_b_u = user_data_class.par.motion_model_parameters.sigma_b_u_omni_team;
eta_u = user_data_class.par.motion_model_parameters.eta_u_omni_team;
P_Wg = user_data_class.par.motion_model_parameters.P_Wg_team;
end
methods (Static)
function x_next_team = f_discrete(x_team,u_team,w_team)
for i = 1:MotionModel_class.num_robots
x = x_team(3*i-2:3*i);
u = u_team(3*i-2:3*i);
Un = w_team(6*i-5:6*i-3);
Wg = w_team(6*i-2:6*i);
Wc = MotionModel_class.f_contin(x,Un,Wg);
x_next = x+MotionModel_class.f_contin(x,u,0)*MotionModel_class.dt+Wc*sqrt(MotionModel_class.dt);
x_next_team(3*i-2:3*i , 1) = x_next; % Note that the "x_next_team" must be a column vector
end
end
function x_dot = f_contin(x,u,wg) % Do not call this function from outside of this class!! % The last input in this method should be w, instead of wg. But, since it is a only used in this class, it does not matter so much.
% Note that this function should only work for a single robot,
% Not for entire team.
th = x(3);
r = MotionModel_class.robot_link_length;
x_dot = (1/3)*[-2*sin(th),-2*sin(pi/3-th),2*sin(pi/3+th);
2*cos(th),-2*cos(pi/3-th),-2*cos(pi/3+th);
1/r,1/r,1/r]*u+wg;
end
function A_team = df_dx_func(x_team,u_team,w_team)
A_team = [];
for i = 1:MotionModel_class.num_robots
x = x_team(3*i-2:3*i);
u = u_team(3*i-2:3*i);
un = w_team(6*i-5:6*i-3);
wg = w_team(6*i-2:6*i);
A = eye(3) ...
+ MotionModel_class.df_contin_dx(x,u,zeros(3,1))*MotionModel_class.dt ...
+ MotionModel_class.df_contin_dx(x,un,wg)*sqrt(MotionModel_class.dt);
A_team = blkdiag(A_team,A);
end
end
function Acontin = df_contin_dx(x,u,w) %#ok<INUSD>
% Note that this function should only work for a single robot,
% Not for entire team.
th = x(3);
Acontin = (2/3)*[0 0 -cos(th)*u(1)+cos(pi/3-th)*u(2)+cos(pi/3+th)*u(3);
0 0 -sin(th)*u(1)-sin(pi/3-th)*u(2)+sin(pi/3+th)*u(3);
0 0 0];
end
function B_team = df_du_func(x_team,u_team,w_team) %#ok<INUSD>
B_team = [];
for i = 1:MotionModel_class.num_robots
th = x_team(3*i);
r = MotionModel_class.robot_link_length;
B = (1/3)*[-2*sin(th),-2*sin(pi/3-th),2*sin(pi/3+th);
2*cos(th) ,-2*cos(pi/3-th),-2*cos(pi/3+th);
1/r ,1/r ,1/r ]*MotionModel_class.dt;
B_team = blkdiag(B_team,B);
end
end
function G_team = df_dw_func(x_team,u_team,w_team) %#ok<INUSD>
G_team = [];
for i = 1:MotionModel_class.num_robots
th=x_team(3*i);
r=MotionModel_class.robot_link_length;
T_theta=(1/3)*[-2*sin(th),-2*sin(pi/3-th),2*sin(pi/3+th);
2*cos(th) ,-2*cos(pi/3-th),-2*cos(pi/3+th);
1/r ,1/r ,1/r ];
G = [T_theta,eye(3)]*sqrt(MotionModel_class.dt);
G_team = blkdiag(G_team,G);
end
end
function w_team = generate_process_noise(x_team,u_team) %#ok<INUSD>
[Un_team,Wg_team] = generate_control_and_indep_process_noise(u_team);
w_team = [];
for i = 1:MotionModel_class.num_robots
w_team = [w_team ; Un_team(3*i-2:3*i);Wg_team(3*i-2:3*i)]; %#ok<AGROW> % in the full noise vector, for each robot we first store the Un and then Wg.
end
end
function Q_process_noise_team = process_noise_cov(x_team,u_team) %#ok<INUSD>
P_Un_team = control_noise_covariance(u_team);
Q_process_noise_team = [];
for i = 1:MotionModel_class.num_robots
Q_process_noise_team = blkdiag(Q_process_noise_team , P_Un_team(3*i-2:3*i , 3*i-2:3*i),MotionModel_class.P_Wg(3*i-2:3*i , 3*i-2:3*i)); % in the full noise matrix, for each robot we first store the Un cov and then Wg cov.
end
end
function nominal_traj_team = generate_open_loop_point2point_traj(X_initial_team,X_final_team) % generates open-loop trajectories between two start and goal states
if isa(X_initial_team,'state'), X_initial_team=X_initial_team.val; end % retrieve the value of the state vector
if isa(X_final_team,'state'), X_final_team=X_final_team.val; end % retrieve the value of the state vector
% parameters (same for all team)
dt=MotionModel_class.dt;
stDim_team = MotionModel_class.stDim;
ctDim_team = MotionModel_class.ctDim;
r=MotionModel_class.robot_link_length;
for i = 1:MotionModel_class.num_robots
% parameters (possibly different for each robot)
stDim = stDim_team/MotionModel_class.num_robots;
ctDim = ctDim_team/MotionModel_class.num_robots;
omega_path=user_data_class.par.motion_model_parameters.omega_const_path_team(i); % constant rotational velocity during turnings
V_path=user_data_class.par.motion_model_parameters.V_const_path_team(i); % constant translational velocity during straight movements
X_initial = X_initial_team(3*i-2:3*i);
X_final = X_final_team(3*i-2:3*i);
th_p = atan2( X_final(2)-X_initial(2) , X_final(1)-X_initial(1) ); % the angle of edge % note that "th_p" is already between -pi and pi, since it is the output of "atan2"
%-------------- Rotation number of steps
if abs(X_initial(3))>pi, X_initial(3)=(X_initial(3)-sign(X_initial(3))*2*pi); end % Here, we bound the initial angle "X_initial(3)" between -pi and pi
if abs(X_final(3))>pi, X_final(3)=(X_final(3)-sign(X_final(3)*2*pi)); end % Here, we bound the final angle "X_final(3)" between -pi and pi
delta_th_p = X_final(3) - X_initial(3); % turning angle
if abs(delta_th_p)>pi, delta_th_p=(delta_th_p-sign(delta_th_p)*2*pi); end % Here, we bound "pre_delta_th_p" between -pi and pi
rotation_steps = abs( delta_th_p/(omega_path*dt) );
%--------------Translation number of steps
delta_disp = norm( X_final(1:2) - X_initial(1:2) );
translation_steps = abs(delta_disp/(V_path*dt));
%--------------Total number of steps
kf_rational = max([rotation_steps , translation_steps]);
kf = floor(kf_rational)+1; % note that in all following lines you cannot replace "floor(something)+1" by "ceil(something)", as it may be a whole number.
%=====================Rotation steps of the path
delta_theta_const = omega_path*sign(delta_th_p)*dt;
delta_theta_nominal(: , 1:floor(rotation_steps)) = repmat( delta_theta_const , 1 , floor(rotation_steps));
delta_theta_const_end = omega_path*sign(delta_th_p)*dt*(rotation_steps-floor(rotation_steps));
delta_theta_nominal(:,floor(rotation_steps)+1) = delta_theta_const_end; % note that you cannot replace "floor(pre_rotation_steps)+1" by "ceil(pre_rotation_steps)", as it may be a whole number.
delta_theta_nominal = [delta_theta_nominal , zeros(1 , kf - size(delta_theta_nominal,2))]; % augment zeros to the end of "delta_theta_nominal", to make its length equal to "kf".
% u_const = ones(3,1)*r*omega_path*sign(delta_th_p);
% u_p_rot(: , 1:floor(rotation_steps)) = repmat( u_const,1,floor(rotation_steps) );
% u_const_end = ones(3,1)*r*omega_path*sign(delta_th_p)*(rotation_steps-floor(rotation_steps));
% u_p_rot(:,floor(rotation_steps)+1)=u_const_end; % note that you cannot replace "floor(pre_rotation_steps)+1" by "ceil(pre_rotation_steps)", as it may be a whole number.
%=====================Translations
delta_xy_const = [V_path*cos(th_p);V_path*sin(th_p)]*dt;
delta_xy_nominal( : , 1:floor(translation_steps) ) = repmat( delta_xy_const , 1 , floor(translation_steps));
delta_xy_const_end = [V_path*cos(th_p);V_path*sin(th_p)]*dt*(translation_steps - floor(translation_steps));
delta_xy_nominal( : , floor(translation_steps)+1 ) = delta_xy_const_end;
delta_xy_nominal = [delta_xy_nominal , zeros(2 , kf - size(delta_xy_nominal,2))]; % augment zeros to the end of "delta_xy_nominal", to make its length equal to "kf".
delta_state_nominal = [delta_xy_nominal;delta_theta_nominal];
%=====================Nominal control and state trajectory generation
x_p = zeros(stDim,kf+1);
theta = zeros(1,kf+1);
u_p = zeros(stDim,kf);
x_p(:,1) = X_initial;
theta(1) = X_initial(3);
for k = 1:kf
theta(:,k+1) = theta(:,k) + delta_state_nominal(3,k);
th_k = theta(:,k);
T_inv_k = [-sin(th_k), cos(th_k) ,r;
-sin(pi/3-th_k),-cos(pi/3-th_k) ,r;
sin(pi/3+th_k) ,-cos(pi/3+th_k) ,r];
delta_body_velocities_k = delta_state_nominal(:,k)/dt; % x,y,and theta velocities in body coordinate at time step k
u_p(:,k) = T_inv_k*delta_body_velocities_k; % "T_inv_k" maps the "velocities in body coordinate" to the control signal
x_p(:,k+1) = x_p(:,k) + delta_state_nominal(:,k);
end
% noiselss motion % for debug: if you uncomment the following
% lines you have to get the same "x_p_copy" as the "x_p"
% x_p_copy = zeros(stDim,kf+1);
% x_p_copy(:,1) = X_initial;
% for k = 1:kf
% x_p_copy(:,k+1) = MotionModel_class.f_discrete(x_p_copy(:,k),u_p(:,k),zeros(MotionModel_class.wDim,1));
% end
x_p_team{i} = x_p; %#ok<AGROW>
u_p_team{i} = u_p; %#ok<AGROW>
kf_team(i) = kf; %#ok<AGROW>
end
max_kf = max(kf_team);
nominal_traj_team.x = [];nominal_traj_team.u = [];
for i = 1:MotionModel_class.num_robots
nominal_traj_team.x = [nominal_traj_team.x ; [x_p_team{i} , repmat( x_p_team{i}(:,end) , 1 , max_kf+1-size(x_p_team{i},2))] ];
nominal_traj_team.u = [nominal_traj_team.u ; [u_p_team{i} , zeros(3,max_kf-size(u_p_team{i},2))] ];
end
end
function YesNo = is_constraints_violated(open_loop_traj) % this function checks if the "open_loop_traj" violates any constraints or not. For example it checks collision with obstacles.
% In this class the open loop trajectories are indeed straight
% lines. So, we use following simplified procedure to check the
% collisions.
YesNo=0; % initialization
Obst=obstacles_class.obst;
for j = 1:MotionModel_class.num_robots
edge_start = open_loop_traj.x(3*j-2:3*j-1 , 1);
edge_end = open_loop_traj.x(3*j-2:3*j-1 , end);
N_obst=size(Obst,2);
for ib=1:N_obst
X_obs=[Obst{ib}(:,1);Obst{ib}(1,1)];
Y_obs=[Obst{ib}(:,2);Obst{ib}(1,2)];
X_edge=[edge_start(1);edge_end(1)];
Y_edge=[edge_start(2);edge_end(2)];
[x_inters,~] = polyxpoly(X_obs,Y_obs,X_edge,Y_edge);
if ~isempty(x_inters)
YesNo=1;
return
end
end
end
end
function traj_plot_handle = draw_nominal_traj(nominal_traj)
traj_plot_handle = [];
for i = 1:MotionModel_class.num_robots
s_node_2D_loc = nominal_traj.x( 3*i-2:3*i-1 , 1);
e_node_2D_loc = nominal_traj.x( 3*i-2:3*i-1 , end);
% retrieve PRM parameters provided by the user
disp('the varargin need to be parsed here')
% edge_spec = obj.par.edge_spec;
% edge_width = obj.par.edge_width;
edge_spec = '-b';
edge_width = 2;
% drawing the 2D edge line
tmp_h = plot([s_node_2D_loc(1),e_node_2D_loc(1)],[s_node_2D_loc(2),e_node_2D_loc(2)],edge_spec,'linewidth',edge_width);
traj_plot_handle = [traj_plot_handle , tmp_h]; %#ok<AGROW>
end
end
end
end
function [Un_team,Wg_team] = generate_control_and_indep_process_noise(U_team)
% generate Un
indep_part_of_Un_team = randn(MotionModel_class.ctDim,1);
P_Un_team = control_noise_covariance(U_team);
Un_team = indep_part_of_Un_team.*diag(P_Un_team.^(1/2));
% generate Wg
Wg_team = mvnrnd(zeros(MotionModel_class.stDim,1),MotionModel_class.P_Wg)';
end
function P_Un_team = control_noise_covariance(U_team)
u_std_team=(MotionModel_class.eta_u).*U_team+(MotionModel_class.sigma_b_u); % note that "MotionModel_class.eta_u" has to be the same size as the "U_team"
P_Un_team=diag(u_std_team.^2);
end
|
github
|
mubeipeng/focused_slam-master
|
quadDyn.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/QuadRelated/quadDyn.m
| 818 |
utf_8
|
40737a280d40e345ede7fda2ceafd5eb
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Continous quadrotor dynamics,
% gives xdot for a given x and u
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xdot = quadDyn(x,u,params)
% The state vector alphabet
px = x(1);
py = x(2);
pz = x(3);
pxdot = x(4);
pydot = x(5);
pzdot = x(6);
phi = x(7);
theta = x(8);
psi = x(9);
p = x(10);
q = x(11);
r = x(12);
% The input vector alphabet
d_collective = u(1);
d_roll = u(2);
d_pitch = u(3);
d_yaw = u(4);
% parameters
g = params.g;
Ix = params.Ix;
Iy = params.Iy;
Iz = params.Iz;
L = params.L;
m = params.m;
% Dynamics
xdot = zeros(12,1);
xdot(1) = pxdot;
xdot(2) = pydot;
xdot(3) = pzdot;
xdot(4) = g*phi;
xdot(5) = -g*theta;
xdot(6) = d_collective/m;
xdot(7) = p;
xdot(8) = q;
xdot(9) = r;
xdot(10) = L*d_roll/Ix;
xdot(11) = L*d_pitch/Iy;
xdot(12) = 1*d_yaw/Iz;
end
|
github
|
mubeipeng/focused_slam-master
|
steerHeading.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/QuadRelated/steerHeading.m
| 468 |
utf_8
|
7bc4050a782d8cd40a99cf93903976ac
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Steer heading
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d_yaw_seq = steerHeading(psi_init,psi_final,n_steps,params)
% Heading Control sub-system (states: psi and r)
A = [0,1;0 0];
B = [0;1/(params.Iz)];
lower = [-pi/2;-pi;-1];
upper = [pi/2;pi;1];
x_init = [psi_init,0];
x_final = [psi_final,0];
[~,d_yaw_seq] = steerLinearSystembyLP(A,B,lower,upper,x_init,x_final,params.dt,n_steps);
end
|
github
|
mubeipeng/focused_slam-master
|
steerLinearSystembyLP.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/QuadRelated/steerLinearSystembyLP.m
| 3,471 |
utf_8
|
1386af9e186eab89e654ec5da01f1c1a
|
%%%%%%%%%% Solve an LP to steer a Linear System %%%%%%%
function [x_seq,u_seq] = steerLinearSystembyLP(A,B,lower,upper,x_init,x_final,dt,numberOfSteps)
% Get dimensions
[stateDim,inputDim] = size(B);
solDim = stateDim*numberOfSteps + inputDim*(numberOfSteps-1);
% Initialize solution
x_seq = zeros(stateDim,numberOfSteps);
u_seq = zeros(inputDim,numberOfSteps-1);
% Indexing goes like this
% State vector, x = [x_1;x_2;...;x_stateDim]
% Input Vector u = [u_1;u_2;...;u_inputDim]
% sol_vector = [x_1(1),x_2(1),...,x_stateDim(1),
% x_1(2),...,x_stateDim(numberOfSteps),u_1(1),u_2(1)
% ,...,u_inputDim(1),....,u_inputDim(numberOfSteps-1)]
% Formula for indexing
% i^th state variable at time j, (j-1)*stateDim + i
% k^th input variable at time l, offset + (l-1)*inputDim + k
% offset = stateDim*numberOfSteps
offset = stateDim*numberOfSteps;
%% Set The Cost Function
% Simply minimize x_final
f = zeros(1,solDim);
for i=(numberOfSteps-1)*stateDim+1:(numberOfSteps)*stateDim
f(i) = 1;
end
% -- it turned out that we dont really need that
% also weight the inputs, so that they don't blow up
%
% for i=offset +1:offset + (numberOfSteps-1)*inputDim
%
% f(i) = 1e6;
%
% end
%
%
%% Inequality Constraints
% Just bound the x_final
Aineq = zeros(stateDim,solDim);
bineq = -x_final;
k=1;
for state = 1:stateDim
Aineq(k,(numberOfSteps-1)*stateDim+state) = -1;
k = k+1;
end
%% Equality Constraints (this is the tricky part!!)
Aeq = zeros(numberOfSteps*stateDim,solDim);
beq = zeros(numberOfSteps*stateDim,1);
% Initial conditions
k=1;
for i=1:stateDim
Aeq(k,i) = 1;
beq(i) = x_init(i);
k = k+1;
end
% Now constrain the system to obey the dynamics
constrainIndex= stateDim+1;
for timeIndex=2:numberOfSteps
for stateIndex=1:stateDim
Aeq(constrainIndex,(timeIndex-1)*stateDim + stateIndex) = 1;
for Index=1:stateDim
if(Index==stateIndex)
Aeq(constrainIndex,(timeIndex-2)*stateDim + Index) = -A(stateIndex,Index)*dt-1;
else
Aeq(constrainIndex,(timeIndex-2)*stateDim + Index) = -A(stateIndex,Index)*dt;
end
for inputIndex=1:inputDim
Aeq(constrainIndex,offset+(timeIndex-2)*inputDim + inputIndex) = -B(stateIndex,inputIndex)*dt;
end
end
constrainIndex = constrainIndex+1;
end
end
%% Set the lower and upper bounds (copy-paste over variables)
lb = zeros(solDim,1);
ub = zeros(solDim,1);
% for states
for i=1:numberOfSteps
for j=1:stateDim
lb((i-1)*stateDim + j) = lower(j);
ub((i-1)*stateDim + j) = upper(j);
end
end
% for inputs
for i=1:numberOfSteps-1
for j=1:inputDim
lb(offset + (i-1)*inputDim + j) = lower(stateDim+j);
ub(offset + (i-1)*inputDim + j) = upper(stateDim+j);
end
end
%% Solve The LP and arrange the solution
sol = linprog(f,Aineq,bineq,Aeq,beq,lb,ub);
for i=1:numberOfSteps
for j=1:stateDim
x_seq(j,i) = sol((i-1)*stateDim + j);
end
end
for i=1:numberOfSteps-1
for j=1:inputDim
u_seq(j,i) = sol(offset+ (i-1)*inputDim + j);
end
end
end
|
github
|
mubeipeng/focused_slam-master
|
steerY.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/QuadRelated/steerY.m
| 543 |
utf_8
|
4dabac2f1131428e5d6cfd0753472897
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Steer heading
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d_pitch_seq = steerY(py_init,py_final,n_steps,params)
% X Control sub-system(states y ydot theta q)
A = zeros(4,4);
A(1,2) = 1;
A(2,3) = -params.g;
A(3,4) = 1;
B = zeros(4,1);
B(4,1) = params.L/params.Iy;
lower = [-2;-2;-pi/2;-pi;-1];
upper = [2;2;pi/2;pi;1];
x_init = [py_init,0,0,0];
x_final = [py_final,0,0,0];
[~,d_pitch_seq] = steerLinearSystembyLP(A,B,lower,upper,x_init,x_final,params.dt,n_steps);
end
|
github
|
mubeipeng/focused_slam-master
|
steerX.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/QuadRelated/steerX.m
| 538 |
utf_8
|
bf981478069c31a7ffc15ebc80e00d8a
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Steer heading
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function d_roll_seq = steerX(px_init,px_final,n_steps,params)
% X Control sub-system(states x xdot phi p)
A = zeros(4,4);
A(1,2) = 1;
A(2,3) = params.g;
A(3,4) = 1;
B = zeros(4,1);
B(4,1) = params.L/params.Ix;
lower = [-2;-2;-pi/2;-pi;-1];
upper = [2;2;pi/2;pi;1];
x_init = [px_init,0,0,0];
x_final = [px_final,0,0,0];
[~,d_roll_seq] = steerLinearSystembyLP(A,B,lower,upper,x_init,x_final,params.dt,n_steps);
end
|
github
|
mubeipeng/focused_slam-master
|
trajectory2.m
|
.m
|
focused_slam-master/FIRM/All_motion_models/QuadRelated/trajectory2.m
| 11,511 |
utf_8
|
5b16be0eceaefd2ffbc39da0e1ccd002
|
function trajectory2(x,y,z,pitch,roll,yaw,scale_factor,step,varargin)
% function trajectory2(x,y,z,pitch,roll,yaw,scale_factor,step,selector)
%
%
% x,y,z center trajectory (vector) [m]
%
% pitch,roll,yaw euler's angles [rad]
%
% scale_factor normalization factor [scalar]
% (related to body aircraft dimension)
%
% step attitude sampling factor [scalar]
% (the points number between two body models)
% OPTIONAL INPUT:
%
% selector select the body model [string]
% A-10 A-10 Body Model
% cessna Cessna Body Model
% mig Mig Body Model
% tomcat Tomcat Body Model
% jet Generic jet body model
% shuttle Space Shuttle body model
% helicopter Helicopter Body Model
% 747 Boeing 747 Body Model
% biplane Generic Biplane body model
% md90 Md90 body model
% dc10 Dc10 Body Model
% ah64 Ah64 helicopter body model
%
% NOTICE: if the selector is omitted, the version 2 use the same stylized
% body model of versin 1
%
% *******************************
% Function Version 2.0
% 2/04/2004 (dd/mm/yyyy)
% Valerio Scordamaglia
% [email protected]
% *******************************
if nargin<8
disp(' Error:');
disp(' Error: Invalid Number Inputs!');
return;
end
if (length(x)~=length(y))|(length(x)~=length(z))|(length(y)~=length(z))
disp(' Error:');
disp(' Uncorrect Dimension of the center trajectory Vectors. Please Check the size');
return;
end
if ((length(pitch)~=length(roll))||(length(pitch)~=length(yaw))||(length(roll)~=length(yaw)))
disp(' Error:');
disp(' Uncorrect Dimension of the euler''s angle Vectors. Please Check the size');
return;
end
if length(pitch)~=length(x)
disp(' Error:');
disp(' Size mismatch between euler''s angle vectors and center trajectory vectors');
return
end
if step>=length(x)
disp(' Error:');
disp(' Attitude samplig factor out of range. Reduce step');
return
end
if step<1
step=1;
end
if nargin>9
disp(' Error:');
disp(' too much input arguments!');
return
end
if nargin==8
trajectory_old(x,y,z,pitch,roll,yaw,scale_factor,step);
return;
else
tmp=cell2mat(varargin(1));
selector=num2str(tmp);
clear tmp;
end;
cur_dir=pwd;
if strcmp(selector,'shuttle')
load shuttle;
V=[-V(:,2) V(:,1) V(:,3)];
V(:,1)=V(:,1)-round(sum(V(:,1))/size(V,1));
V(:,2)=V(:,2)-round(sum(V(:,2))/size(V,1));
V(:,3)=V(:,3)-round(sum(V(:,3))/size(V,1));
elseif strcmp(selector,'helicopter')
load helicopter;
V=[-V(:,2) V(:,1) V(:,3)];
V(:,1)=V(:,1)-round(sum(V(:,1))/size(V,1));
V(:,2)=V(:,2)-round(sum(V(:,2))/size(V,1));
V(:,3)=V(:,3)-round(sum(V(:,3))/size(V,1));
elseif strcmp(selector,'747')
load boeing_747;
V=[V(:,2) V(:,1) V(:,3)];
V(:,1)=V(:,1)-round(sum(V(:,1))/size(V,1));
V(:,2)=V(:,2)-round(sum(V(:,2))/size(V,1));
V(:,3)=V(:,3)-round(sum(V(:,3))/size(V,1));
elseif strcmp(selector,'biplane')
load biplane;
V=[-V(:,2) V(:,1) V(:,3)];
V(:,1)=V(:,1)-round(sum(V(:,1))/size(V,1));
V(:,2)=V(:,2)-round(sum(V(:,2))/size(V,1));
V(:,3)=V(:,3)-round(sum(V(:,3))/size(V,1));
elseif strcmp(selector,'md90')
load md90;
V=[-V(:,1) V(:,2) V(:,3)];
V(:,1)=V(:,1)-round(sum(V(:,1))/size(V,1));
V(:,2)=V(:,2)-round(sum(V(:,2))/size(V,1));
V(:,3)=V(:,3)-round(sum(V(:,3))/size(V,1));
elseif strcmp(selector,'dc10')
load dc10;
V=[V(:,2) V(:,1) V(:,3)];
V(:,1)=V(:,1)-round(sum(V(:,1))/size(V,1));
V(:,2)=V(:,2)-round(sum(V(:,2))/size(V,1));
V(:,3)=V(:,3)-round(sum(V(:,3))/size(V,1));
elseif strcmp(selector,'ah64')
load ah64;
V=[V(:,2) V(:,1) V(:,3)];
V(:,1)=V(:,1)-round(sum(V(:,1))/size(V,1));
V(:,2)=V(:,2)-round(sum(V(:,2))/size(V,1));
V(:,3)=V(:,3)-round(sum(V(:,3))/size(V,1));
elseif strcmp(selector,'mig')
load mig;
V=[V(:,2) V(:,1) V(:,3)];
elseif strcmp(selector,'tomcat')
load tomcat;
V=[-V(:,2) V(:,1) V(:,3)];
V(:,1)=V(:,1)-round(sum(V(:,1))/size(V,1));
V(:,2)=V(:,2)-round(sum(V(:,2))/size(V,1));
V(:,3)=V(:,3)-round(sum(V(:,3))/size(V,1));
elseif strcmp(selector,'jet')
load 80jet;
V=[-V(:,2) V(:,1) V(:,3)];
elseif strcmp(selector,'cessna')
load 83plane;
V=[-V(:,2) V(:,1) V(:,3)];
elseif strcmp(selector,'A-10')
load A-10;
V=[V(:,3) V(:,1) V(:,2)];
else
try
eval(['load ' selector ';']);
V(:,1)=V(:,1)-round(sum(V(:,1))/size(V,1));
V(:,2)=V(:,2)-round(sum(V(:,2))/size(V,1));
V(:,3)=V(:,3)-round(sum(V(:,3))/size(V,1));
catch
str=strcat('Warning: ',selector,' not found. Default=A-10');
disp(str);
load A-10;
V=[V(:,3) V(:,1) V(:,2)];
end
end
correction=max(abs(V(:,1)));
V=V./(scale_factor*correction);
ii=length(x);
resto=mod(ii,step);
for i=1:step:(ii-resto)
theta=pitch(i);
phi=roll(i);
psi=yaw(i);
Tbe=[cos(psi)*cos(theta) sin(psi)*cos(theta) -sin(theta);((cos(psi)*sin(theta)*sin(phi))-(sin(psi)*cos(phi))) ((sin(psi)*sin(theta)*sin(phi))+(cos(psi)*cos(phi))) cos(theta)*sin(phi);((cos(psi)*sin(theta)*cos(phi))+(sin(psi)*sin(phi))) ((sin(psi)*sin(theta)*cos(phi))-(cos(psi)*sin(phi))) cos(theta)*cos(phi)];
%Tbe=Tbe';
Vnew=V*Tbe;
rif=[x(i) y(i) z(i)];
X0=repmat(rif,size(Vnew,1),1);
Vnew=Vnew+X0;
p=patch('faces', F, 'vertices' ,Vnew);
set(p, 'facec', [1 0 0]);
set(p, 'FaceVertexCData', C);
set(p, 'EdgeColor','none');
hold on;
end
hold on;
plot3(x,y,z);
light;
grid on;
view(82.50,2);
daspect([1 1 1]) ;
xlabel('X (m)');
ylabel('Y (m)');
zlabel('Z (m)');
cd (cur_dir);
function trajectory_old(x,y,z,pitch,roll,yaw,scale_factor,step)
if (length(x)~=length(y))||(length(x)~=length(z))||(length(y)~=length(z))
disp(' Error:');
disp(' Uncorrect Dimension of the center trajectory Vectors. Please Check the size');
return;
end
if ((length(pitch)~=length(roll))||(length(pitch)~=length(yaw))||(length(roll)~=length(yaw)))
disp(' Error:');
disp(' Uncorrect Dimension of the euler''s angle Vectors. Please Check the size');
return;
end
if length(pitch)~=length(x)
disp(' Error:');
disp(' Size mismatch between euler''s angle vectors and center trajectory vectors');
return
end
if step>=length(x)
disp(' Error:');
disp(' Attitude samplig factor out of range. Reduce step');
return
end
if step<1
step=1;
end
[xxx,yyy,zzz]=miss_shape;
correction=10;
xxx = -xxx/(scale_factor*correction);
yyy = yyy/(scale_factor*correction);
zzz = zzz/(scale_factor*correction);
ii=length(x);
resto=mod(ii,step);
for i=1:step:(ii-resto)
theta=pitch(i);
phi=roll(i);
psi=yaw(i);
Tbe=[cos(psi)*cos(theta) sin(psi)*cos(theta) -sin(theta);((cos(psi)*sin(theta)*sin(phi))-(sin(psi)*cos(phi))) ((sin(psi)*sin(theta)*sin(phi))+(cos(psi)*cos(phi))) cos(theta)*sin(phi);((cos(psi)*sin(theta)*cos(phi))+(sin(psi)*sin(phi))) ((sin(psi)*sin(theta)*cos(phi))-(cos(psi)*sin(phi))) cos(theta)*cos(phi)];
x_hat=0.*xxx;
y_hat=0.*yyy;
z_hat=0.*zzz;
for iii=1:size(xxx,1)
for jjj=1:size(xxx,2)
tmp_b=[xxx(iii,jjj);yyy(iii,jjj);zzz(iii,jjj)];
tmp_e=Tbe*tmp_b;
x_hat(iii,jjj)=x(i)+tmp_e(1,1);
y_hat(iii,jjj)=y(i)+tmp_e(2,1);
z_hat(iii,jjj)=z(i)+tmp_e(3,1);
end
end
plot3(x_hat,y_hat,z_hat);
hold on;
patch(x_hat,y_hat,z_hat,[1 0 0]);
end
axis equal;
%grid off
hold on;
plot3(x,y,z);
light;
grid on;
view(82.50,2);
xlabel('X (m)');
ylabel('Y (m)');
zlabel('Z (m)');
%the following function is a remake of the matlab function
function [x,y,z]=miss_shape
num=30; % Number of z-y segments to make the circle
count=1; % Counter for number of individual patches
theta=[360/2/num:360/num:(360+360/2/num)]*pi/180;
len = 25.7; % Total Length (no units)
radius = 1.5/2; % Radius of body
s_fore = 5; % Start of main body (w.r.t. nose)
thr_len = 1.4; % Length of Motor exit
rad_throt = 1.3/2; % radius of motor exit
l_fore=len-s_fore-thr_len; % Length of main body
c_g = 14; % Position of c.g. w.r.t nose
%
% Fore Body Shape
%
yc_range = radius*sin(theta);
zc_range = -radius*cos(theta);
for i = 1:num
xcraft{i}=[s_fore s_fore s_fore+l_fore s_fore+l_fore ]-c_g;
ycraft{i}=[yc_range(i) yc_range(i+1) yc_range(i+1) yc_range(i)];
zcraft{i}=[zc_range(i) zc_range(i+1) zc_range(i+1) zc_range(i)];
end
count=num+1;
%
% Throttle Shape
%
yc_range2 = rad_throt*sin(theta);axis
zc_range2 = -rad_throt*cos(theta);
for i = 1:num
xcraft{count}=[len-thr_len len-thr_len len len]-c_g;
ycraft{count}=[yc_range(i) yc_range(i+1) yc_range2(i+1) yc_range2(i)];
zcraft{count}=[zc_range(i) zc_range(i+1) zc_range2(i+1) zc_range2(i)];
count=count+1;
end
%
% Nose Shape
%
for i = 1:num
xcraft{count}=[s_fore s_fore 0 s_fore]-c_g;
ycraft{count}=[yc_range(i) yc_range(i+1) 0 yc_range(i)];
zcraft{count}=[zc_range(i) zc_range(i+1) 0 zc_range(i)];
count=count+1;
end
%
% Wing shapes
%
xcraft{count}=[10.2 13.6 14.6 15]-c_g;
ycraft{count}=[-zc_range(1) -zc_range(1)+1.5 -zc_range(1)+1.5 -zc_range(1)];
zcraft{count}=[0 0 0 0 ];
xcraft{count+1}=xcraft{count};
ycraft{count+1}=-ycraft{count};
zcraft{count+1}=zcraft{count};
% xcraft{count+2}=xcraft{count};
% ycraft{count+2}=zcraft{count};
% zcraft{count+2}=ycraft{count};
% xcraft{count+3}=xcraft{count};
% ycraft{count+3}=zcraft{count};
% zcraft{count+3}=-ycraft{count};
%
% Tail shapes
%
count=count+2;
xcraft{count}=[22.1 22.9 23.3 23.3]-c_g;
ycraft{count}=[-zc_range(1) -zc_range(1)+1.1 -zc_range(1)+1.1 -zc_range(1)];
zcraft{count}=[0 0 0 0];
xcraft{count+1}=xcraft{count};
ycraft{count+1}=-ycraft{count};
zcraft{count+1}=zcraft{count};
xcraft{count+2}=xcraft{count};
ycraft{count+2}=zcraft{count};
zcraft{count+2}=ycraft{count};
% xcraft{count+3}=xcraft{count};
% ycraft{count+3}=zcraft{count};
% zcraft{count+3}=-ycraft{count};
count=count+2;
%
% Combine individual objects into a single set of co-ordinates and roll through 45 degrees
%
x=[];y=[];z=[];
roll = [1 0 0;0 cos(0/180*pi) sin(0/180*pi);0 -sin(0/180*pi) cos(0/180*pi)];
for i = 1:count
x = [x xcraft{i}'];
y = [y ycraft{i}'];
z = [z zcraft{i}'];
end
for i =1:4
dum = [x(i,:);y(i,:);z(i,:)];
dum = roll*dum;
x(i,:)=dum(1,:);
y(i,:)=dum(2,:);
z(i,:)=dum(3,:);
end
%
% Rescale vertices
%
% x = -x/len;
% y = y/len;
% z = z/len;
% End miss_shape
|
github
|
mubeipeng/focused_slam-master
|
Six_DOF_robot_state.m
|
.m
|
focused_slam-master/FIRM/All_state/Six_DOF_robot_state.m
| 12,804 |
utf_8
|
d28bb6f56a79a2d7837de7d06cf94932
|
classdef Six_DOF_robot_state < state_interface
% This class encapsulates the state of a 6DOF robot, described by its 3D location and orientation quaternion.
properties (Constant)
dim = 7; % state dimension [X,Y,Z,q0,q1,q2,q3]
zeroQuaternion = [1 ; 0 ; 0 ; 0];
end
properties
val; % value of the state
plot_handle; % handle for the "drawings" associated with the state
head_handle;
tria_handle;
text_handle; % handle for the "displayed text" associated with the state
end
methods
function obj = Six_DOF_robot_state(varargin)
obj = obj@state_interface(varargin{:});
end
function signed_dist_vector = signed_element_wise_dist(obj,x2) % this function returns the "Signed element-wise distance" between two states x1 and x2
x1 = obj.val; % retrieve the value of the state vector
if isa(x2,'state'), x2=x2.val; end % retrieve the value of the state vector
signed_dist_vector = x1-x2;
% signed_dist_position = x1(1:3) - x2(1:3); % [X1-X2, Y1-Y2, Z1-Z2]'
% signed_dist_quat = x1(4:7) - x2(4:7);
%
% if any(abs(signed_dist_quat) > 1)
% signed_dist_quat = x1(4:7) + x2(4:7);
% end
% signed_dist_vector = [signed_dist_position;signed_dist_quat];
end
function distance_for_control = compute_distance_for_control(obj,x2)
% EST OF ERROR WITH QUAT PRODUCT %
x1 = obj.val; % retrieve the value of the state vector
if isa(x2,'state'), x2=x2.val; end % retrieve the value of the state vector
signed_dist_position = x1(1:3) - x2(1:3); % [X1-X2, Y1-Y2, Z1-Z2]'
q_1 = x1(4:7)';
q_2 = x2(4:7)';
q21 = quatmultiply(q_1,quatinv(q_2)); % relative rotation quaternion from nominal to current
signed_dist_vector = [signed_dist_position;q21'];
distance_for_control = signed_dist_vector;
distance_for_control(4)=0; % For quaternion control, we only need to control q1,q2,q3 because q1 is constrained by the normalization relation
end
function obj = draw(obj, varargin)
% The full list of properties for this function is:
% 'RobotShape', 'RobotSize', 'TriaColor', 'color', 'HeadShape',
% 'HeadSize'.
% default values
robot_shape = 'point';
robot_size = 1;
tria_color = 'b';
head_color = 'b';
head_shape = '*';
head_size = 6;
robot_text = [];
font_size = 15;
text_color = 'b';
for i = 1 : 2 : length(varargin)
switch lower(varargin{i})
case lower('RobotShape')
robot_shape = varargin{i+1};
case lower('RobotSize')
robot_size = varargin{i+1};
case lower('TriaColor')
tria_color = varargin{i+1};
case lower('color')
head_color = varargin{i+1};
case lower('HeadShape')
head_shape = varargin{i+1};
case lower('HeadSize')
head_size = varargin{i+1};
case lower('text')
robot_text = varargin{i+1};
case lower('fontsize')
font_size = varargin{i+1};
case lower('textcolor')
text_color = varargin{i+1};
otherwise
error('This property does not exist.')
end
end
x=obj.val;
obj.head_handle = plot3(x(1),x(2),x(3),'Marker',head_shape,'MarkerSize',head_size,'MarkerEdgeColor',head_color,'MarkerFaceColor',head_color);
robot_size = 4;
vertices_x=[0,-robot_size,-robot_size,-robot_size,-robot_size/2,-robot_size,-robot_size,0];
vertices_y=[0,-robot_size/5,0,0,0,0,robot_size/5,0];
vertices_z=[0,0,0,robot_size/10,0,0,0,0];
q_rot = Quaternion(x(4:7)); % rotation quaternion
q_rot = unit(q_rot);% making a normalized quarternion, dont use quatnormalize
R = q_rot.R;
vert=R*[vertices_x;vertices_y;vertices_z];
% plot the triangle body
if strcmpi(robot_shape,'triangle') % strcmpi is not sensitive to letter scase.
tmp=get(gca,'NextPlot');
hold on
obj.tria_handle = plot3(vert(1,:)+x(1),vert(2,:)+x(2),vert(3,:)+x(3),'color',tria_color);
set(gca,'NextPlot',tmp);
end
% write the text next to the robot
% if ~isempty(robot_text)
% robot_size_for_text=robot_size*1.5; % we need a slightly bigger robot so that the text does not interfere with actual robot.
% vertices_x=[0,-robot_size_for_text,-robot_size_for_text,0];
% vertices_y=[0,-robot_size_for_text/5,robot_size_for_text/5,0];
% R=[cos(th),-sin(th);sin(th),cos(th)];
% vert=R*[vertices_x;vertices_y];
%
% text_pos=(vert(:,2)+vert(:,3))/2 + x(1:2); % we add the mid-point of the base of this bigger robot to its heading position to find the text position, right behind the robot.
% text_pos(1) = text_pos(1) - 0.45; % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
% obj.text_handle = text(text_pos(1),text_pos(2),robot_text,'fontsize',font_size,'color',text_color);
% end
% obj.tria_handle = [obj.tria_handle,plot_3D_cone_in_2D(x,tria_color)];
end
function obj = delete_plot(obj,varargin)
% The list of properties for this function is:
% 'triangle', 'head'.
if isempty(varargin)
try % Avoid errors if the graphic object has already been deleted
delete(obj.head_handle);
obj.head_handle = [];
end
try % Avoid errors if the graphic object has already been deleted
delete(obj.tria_handle);
obj.tria_handle = [];
end
try % Avoid errors if the graphic object has already been deleted
delete(obj.text_handle);
obj.text_handle = [];
end
else
for i = 1 : length(varargin)
switch varargin{i}
case 'triangle'
try % Avoid errors if the graphic object has already been deleted
delete(obj.tria_handle);
obj.tria_handle = [];
end
case 'head'
try % Avoid errors if the graphic object has already been deleted
delete(obj.head_handle)
obj.head_handle = [];
end
case 'text'
try % Avoid errors if the graphic object has already been deleted
delete(obj.text_handle);
obj.text_handle = [];
end
otherwise
error('There is no such a handle to delete')
end
end
end
end
function neighb_plot_handle = draw_neighborhood(obj, scale)
tmp_th = 0:0.1:2*pi;
x = obj.val(1);
y = obj.val(2);
neighb_plot_handle = plot3(scale*cos(tmp_th) + x , scale*sin(tmp_th) + y, obj.val(3));
end
function YesNo = is_constraint_violated(obj)
x = obj.val;
YesNo = 0; % initialization
obst = obstacles_class.obst; % for abbreviation
for i_ob = 1:length(obst)
if any(inpolygon(x(1,:),x(2,:),obst{i_ob}(:,1),obst{i_ob}(:,2)))
YesNo =1;
return
end
end
end
function old_limits = zoom_in(obj,zoom_ratio)
old_limits = axis;
% old_xlim = xlim;
% old_ylim = ylim;
% old_limits = [old_xlim,old_ylim];
% new_center = obj.val;
% new_x_length = (old_xlim(2)-old_xlim(1))/zoom_ratio;
% new_y_length = (old_ylim(2)-old_ylim(1))/zoom_ratio;
% new_xlim = new_center(1) + [-new_x_length,new_x_length]/2;
% new_ylim = new_center(2) + [-new_y_length,new_y_length]/2;
% axis([new_xlim,new_ylim])
end
function obj = apply_differentiable_constraints(obj)
qnorm = norm(obj.val(4:7));
if qnorm ~=0
obj.val(4:7) = obj.val(4:7)/qnorm;
end
end
function J = get_differentiable_constraints_jacobian(obj)
q = obj.val(4:7);
nq = norm(q);
Jq = -nq^(-3)*(q*q')+nq^(-1)*eye(4);
J = blkdiag(eye(3),Jq);
end
end
methods (Static)
function origin = SpaceOrigin()
origin = [zeros(3,1);Six_DOF_robot_state.zeroQuaternion]; % note that the "state" class will be generated on the fly (using TypeDef) function.
end
function sampled_state = sample_a_valid_state()
user_or_random = 'user';
xrange = [0.5 4];
yrange = [0.5 4];
zrange = user_data_class.par.sim.env_z_limits;
if strcmp(user_or_random , 'user')
[x,y]=ginput(1);
if isempty(x)
sampled_state = [];
return
else
xyz = rand(1,3) .* [xrange(2)-xrange(1) yrange(2)-yrange(1) zrange(2)-zrange(1)] + ...
[xrange(1) yrange(1) zrange(1)];
yaw = rand*2*pi;
pitch = -pi/2 + rand*pi;
roll = -pi/2 + rand*pi;
quat = angle2quat(yaw,pitch,roll);
sampled_state = state([x , y , xyz(3), quat]');
end
if sampled_state.is_constraint_violated()
sampled_state = user_samples_a_state();
end
elseif strcmp(user_or_random , 'random')
xyz = rand(1,3) .* [xrange(2)-xrange(1) yrange(2)-yrange(1) zrange(2)-zrange(1)] + ...
[xrange(1) yrange(1) zrange(1)];
yaw = rand*2*pi;
pitch = rand*2*pi;
roll = rand*2*pi;
quat = angle2quat(yaw,pitch,roll);
sampled_state = [xyz, quat]';
else
error('not correct!');
end
end
end
end
function plot_handle = plot_3D_cone_in_2D(x,color)
size_ratio = 0.75;
r = 1*size_ratio;
h = 2*size_ratio;
m = h/r;
[R,A] = meshgrid(linspace(0,r,2),linspace(0,2*pi,20));
X = R .* cos(A);
Y = R .* sin(A);
Z = m*R;
X_base = X;
Y_base = Y;
Z_base = h*ones(size(X_base));
% Cone around the z-axis, point at the origin
% mesh(X,Y,Z)
X = [X,X_base];
Y = [Y,Y_base];
Z = [Z,Z_base];
% mesh(X,Y,Z)
% axis equal
% axis([-3 3 -3 3 0 3])
phi = pi/2;
X1 = X*cos(phi) - Z*sin(phi);
Y1 = Y;
Z1 = X*sin(phi) + Z*cos(phi);
% Previous cone, rotated by angle phi about the y-axis
%mesh(X1,Y1,Z1)
% h_cone = surf(X1,Y1,Z1);
% set(h_cone,'edgecolor','none','facecolor',color,'facelighting','gouraud');
rot = [x(4) ; x(5) ; x(6) ; x(7)];% rotation state
q_rot = Quaternion(rot);
q_rot = unit(q_rot);% making a normalized quarternion, dont use quatnormalize
Pos = q_rot.R*[X1;Y1;Z1] + repmat(x(1:3),1,size(X1));
X2 = Pos(1,:);
Y2 = Pos(2,:);
Z2 = Pos(3,:);
% Second cone rotated by angle theta about the z-axis
plot_handle = mesh(X2,Y2,Z2);
% axis equal
% set(gca,'PlotBoxAspectRatio',[1 1 1]);
% camlight(135,180);
% view([30,25]);
set(plot_handle,'edgecolor','none','facecolor',color,'facelighting','phong');
% xlabel('x')
% ylabel('y')
% zlabel('z')
end
|
github
|
mubeipeng/focused_slam-master
|
revolute_joint_manipulator_state.m
|
.m
|
focused_slam-master/FIRM/All_state/revolute_joint_manipulator_state.m
| 9,225 |
utf_8
|
ff960810a44dc0b18ff184eae6a8abca
|
classdef revolute_joint_manipulator_state < state_interface
% This class encapsulates the state of the system.
properties (Constant)
num_revolute_joints = user_data_class.par.state_parameters.num_revolute_joints;
dim = revolute_joint_manipulator_state.num_revolute_joints; % state dimension
link_length = 0.5;
end
properties
val; % value of the state
joint_2D_locations; % 2D locations of joints in the plane
plot_handle; % handle for the "drawings" associated with the state
text_handle; % handle for the "displayed text" associated with the state
end
methods
function obj = revolute_joint_manipulator_state(varargin) % constructor function
obj = obj@state_interface(varargin{:});
th = obj.val;
sum_theta = 0; % initialization % since teh manipulator works in a plane, the rotation has to be a 2by2 matrix
end_link = [0;0]; % this is the location in the plane that the beginning of the manipulator is attached to
for i = 1:revolute_joint_manipulator_state.num_revolute_joints
sum_theta = sum_theta + th(i); % at i-th iteration R_prod is the product of R1*R2*...*Ri
start_link = end_link(:,max(i-1,1)); % 2D position of the start of i-th link in plane
end_link(:,i) = obj.Rot_2D(sum_theta)*[obj.link_length;0] + start_link; % 2D position of the end of i-th link in plane % [obj.link_length;0] means that the length of the i-th joint is 1.
end
obj.joint_2D_locations = end_link; % Note that the i-th column of this matrix is the 2D location of the end of i-th link in the manipulator.
end
end
methods
function signed_dist_vector = signed_element_wise_dist(obj,x2) % this function returns the "Signed element-wise distnace" between two states x1 and x2
x1 = obj.val; % retrieve the value of the state vector
if isa(x2,'revolute_joint_manipulator_state'), x2=x2.val; end % retrieve the value of the state vector
signed_dist_vector = x1 - x2;
% Following part takes care of periodicity in heading angle representation.
for i = 1:obj.num_revolute_joints
th_dist = signed_dist_vector(i);
if th_dist >= 0
th_dist_bounded = mod( th_dist , 2*pi );
if th_dist_bounded > pi, th_dist_bounded = th_dist_bounded - 2*pi; end
else
th_dist_bounded = - mod( -th_dist , 2*pi );
if th_dist_bounded < -pi, th_dist_bounded = th_dist_bounded + 2*pi; end
end
signed_dist_vector(i) = th_dist_bounded; % updating the angle distance
end
end
function obj = draw(obj, varargin) % draw state
manip_color = 'b'; %default color
robot_text = [];
font_size = 15;
text_color = 'b';
for i = 1 : 2 : length(varargin)
switch lower(varargin{i})
case lower('color')
manip_color = varargin{i+1};
case lower('text')
robot_text = varargin{i+1};
case lower('fontsize')
font_size = varargin{i+1};
case lower('textcolor')
text_color = varargin{i+1};
end
end
all_joints = [ [0;0] , obj.joint_2D_locations ];
obj.plot_handle = plot( all_joints(1,:) , all_joints(2,:) , 'color', manip_color);
if ~isempty(robot_text)
text_pos = obj.joint_2D_locations(:,end);
text_pos(1) = text_pos(1) - 0.45; % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
obj.text_handle = text(text_pos(1),text_pos(2),robot_text,'fontsize',font_size,'color',text_color);
end
end
function obj = delete_plot(obj,varargin) % delete state drawings
try
delete(obj.plot_handle);
end
obj.plot_handle =[];
end
function neighb_plot_handle = draw_neighborhood(obj, scale)
disp('Not yet implemented');
neighb_plot_handle = 'something';
end
function YesNo = is_constraint_violated(obj) % this function checks if the "state" is a collilsion-free one or not.
YesNo = 0; % initialization
all_joints = [ [0;0] , obj.joint_2D_locations ]; % Actually, this is a polyline
% first we check the self-intersections
% [x_inters,~] = polyxpoly(all_joints(1,:),all_joints(2,:),all_joints(1,:),all_joints(2,:)); % the intersection points must be the vertices of the manipulator polygon
% if length(x_inters)>size(all_joints,2) % if there is any more intersection points than the number of manipulator joints, that means that we have a self-intersection
% YesNo=1;
% return
% end
% now, we check the intersection with obstacls
Obst = obstacles_class.obst;
N_obst=size(Obst,2);
for ib=1:N_obst
X_obs=[Obst{ib}(:,1);Obst{ib}(1,1)];
Y_obs=[Obst{ib}(:,2);Obst{ib}(1,2)];
[x_inters,~] = polyxpoly(X_obs,Y_obs,all_joints(1,:),all_joints(2,:));
if ~isempty(x_inters)
YesNo=1;
return
end
end
end
function old_limits = zoom_in(obj,zoom_ratio)
old_xlim = xlim;
old_ylim = ylim;
old_limits = [old_xlim,old_ylim];
new_center = obj.joint_2D_locations(:,end);
new_x_length = (old_xlim(2)-old_xlim(1))/zoom_ratio;
new_y_length = (old_ylim(2)-old_ylim(1))/zoom_ratio;
new_xlim = new_center(1) + [-new_x_length,new_x_length]/2;
new_ylim = new_center(2) + [-new_y_length,new_y_length]/2;
axis([new_xlim,new_ylim])
end
end
methods (Static)
function sampled_state = sample_a_valid_state()
user_or_random = 'random';
if strcmp(user_or_random , 'user')
sampled_state = user_samples_a_state();
elseif strcmp(user_or_random , 'random')
sampled_state = randomly_sample_a_state();
else
error('not correct!');
end
end
end
methods (Access = private)
function draw_link()
end
function R = Rot_2D(obj,th)
R = [cos(th) -sin(th);sin(th) cos(th)];
end
end
end
function sampled_state = user_samples_a_state()
x_circle = cos(0:0.1:2*pi)*revolute_joint_manipulator_state.link_length; y_circle = sin(0:0.1:2*pi)*revolute_joint_manipulator_state.link_length; % to plot indicator (helper) circles
end_link = [0;0]; % this is the location in the plane that the beginning of the manipulator is attached to
for i = 1:revolute_joint_manipulator_state.num_revolute_joints
circle_handle = plot(x_circle + end_link(1), y_circle + end_link(2));
circle_handle = [circle_handle , plot(end_link(1),end_link(2),'*')];
[x,y]=ginput(1);
if isempty(x)
delete(circle_handle);
sampled_state = [];
return
else
start_link = end_link; % 2D position of the start of i-th link in plane
rel_vector = [x;y] - start_link; % relative vector
rel_vector = rel_vector/norm(rel_vector)*revolute_joint_manipulator_state.link_length; % making the length of link equal to "state.link_length"
end_link = rel_vector + start_link;
tmp_h = plot( [start_link(1) , end_link(1)] , [start_link(2) , end_link(2)] ,'r');
delete(circle_handle);
th_absolute(i) = atan2(end_link(2) - start_link(2) , end_link(1) - start_link(1)) ;
end
end
th_joints = [th_absolute(1) , diff(th_absolute)];
for i = 1:revolute_joint_manipulator_state.num_revolute_joints
th_dist = th_joints(i);
if th_dist >= 0
th_dist_bounded = mod( th_dist , 2*pi );
if th_dist_bounded > pi, th_dist_bounded = th_dist_bounded - 2*pi; end
else
th_dist_bounded = - mod( -th_dist , 2*pi );
if th_dist_bounded < -pi, th_dist_bounded = th_dist_bounded + 2*pi; end
end
th_joints(i) = th_dist_bounded; % updating the angle distance
end
sampled_state = revolute_joint_manipulator_state(th_joints);
if sampled_state.is_constraint_violated()
sampled_state = user_samples_a_state();
end
end
function sampled_state = randomly_sample_a_state()
sampled_state_val = rand(revolute_joint_manipulator_state.dim,1)*2*pi-pi;
sampled_state = revolute_joint_manipulator_state(sampled_state_val);
if sampled_state.is_constraint_violated()
sampled_state = randomly_sample_a_state();
end
end
|
github
|
mubeipeng/focused_slam-master
|
multi_robot_positional_state.m
|
.m
|
focused_slam-master/FIRM/All_state/multi_robot_positional_state.m
| 10,155 |
utf_8
|
141d95173c43240a01ca1125454acd98
|
classdef multi_robot_positional_state < state_interface
% This class encapsulates the state of a planar robot, described by its 2D location and heading angle.
properties
num_robots;
dim; % state dimension
val; % value of the state
plot_handle=[]; % handle for the "drawings" associated with the state
head_handle=[];
tria_handle=[];
text_handle=[]; % handle for the "displayed text" associated with the state
end
methods
function obj = multi_robot_positional_state(varargin) % Note that the format (spacing and words) of this function must remain the same (as it is used in the typeDef function)
obj = obj@state_interface(varargin{:});
num_robots_user = user_data_class.par.state_parameters.num_robots;
obj.num_robots = num_robots_user;
obj.dim = 2*num_robots_user;
end
function signed_dist_vector = signed_element_wise_dist(obj,x2) % this function returns the "Signed element-wise distnace" between two states x1 and x2
x1 = obj.val; % retrieve the value of the state vector
if isa(x2,'multi_robot_positional_state'), x2=x2.val; end % retrieve the value of the state vector % Note that the format (spacing and words) of this function must remain the same (as it is used in the typeDef function)
signed_dist_vector = x1 - x2;
end
function setNumRobots (num_robots_inp)
obj.num_robots = num_robots_inp;
end
function obj = draw(obj, varargin)
% The full list of properties for this function is:
% 'RobotShape', 'RobotSize', 'TriaColor', 'color', 'HeadShape',
% 'HeadSize'.
% default values
robot_shape = 'triangle';
robot_size = 0.5;
robot_color = {'r','g','b'};
head_shape = {'s','o','d'};
head_size = 6;
robot_text = {};
font_size = 15;
text_color = 'b';
for i = 1 : 2 : length(varargin)
switch lower(varargin{i})
case lower('RobotShape')
robot_shape = varargin{i+1};
case lower('RobotSize')
robot_size = varargin{i+1};
case lower('TriaColor')
% robot_color = varargin{i+1};
case lower('color')
% robot_color = varargin{i+1};
case lower('HeadShape')
% head_shape = varargin{i+1};
case lower('HeadSize')
head_size = varargin{i+1};
case lower('text')
robot_text = varargin{i+1};
case lower('fontsize')
font_size = varargin{i+1};
case lower('textcolor')
text_color = varargin{i+1};
otherwise
error('This property does not exist.')
end
end
tmp=get(gca,'NextPlot');
hold on
for i = 1:obj.num_robots
x = obj.val(2*i-1:2*i);
obj.head_handle = [obj.head_handle,plot(x(1),x(2),'Marker',head_shape{i},'MarkerSize',head_size,'MarkerEdgeColor',robot_color{i},'MarkerFaceColor',robot_color{i})];
% write the text next to the robot
if ~isempty(robot_text)
text_pos= x(1:2)+2; % we shift the text a little bit away from the node. % we add the mid-point of the base of this bigger robot to its heading position to find the text position, right behind the robot.
text_pos(1) = text_pos(1) - 0.45; % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
obj.text_handle = [obj.text_handle,text(text_pos(1),text_pos(2),robot_text,'fontsize',font_size,'color',text_color)];
end
end
set(gca,'NextPlot',tmp);
end
function obj = delete_plot(obj,varargin)
% The list of properties for this function is:
% 'triangle', 'head'.
if isempty(varargin)
try % Avoid errors if the graphic object has already been deleted
delete(obj.head_handle);
obj.head_handle = [];
end
try % Avoid errors if the graphic object has already been deleted
delete(obj.tria_handle);
obj.tria_handle = [];
end
try % Avoid errors if the graphic object has already been deleted
delete(obj.text_handle);
obj.text_handle = [];
end
else
for i = 1 : length(varargin)
switch varargin{i}
case 'triangle'
try % Avoid errors if the graphic object has already been deleted
delete(obj.tria_handle);
obj.tria_handle = [];
end
case 'head'
try % Avoid errors if the graphic object has already been deleted
delete(obj.head_handle)
obj.head_handle = [];
end
case 'text'
try % Avoid errors if the graphic object has already been deleted
delete(obj.text_handle);
obj.text_handle = [];
end
otherwise
error('There is no such a handle to delete')
end
end
end
end
function neighb_plot_handle = draw_neighborhood(obj, scale)
tmp_th = 0:0.1:2*pi;
neighb_plot_handle = [];
for i = 1:obj.num_robots
x = obj.val(2*i-1);
y = obj.val(2*i);
tmp_h = plot(scale*cos(tmp_th) + x , scale*sin(tmp_th) + y);
neighb_plot_handle = [neighb_plot_handle , tmp_h]; %#ok<AGROW>
end
end
function YesNo = is_constraint_violated(obj)
YesNo = 0; % initialization
obst = obstacles_class.obst; % for abbreviation
for j = 1:obj.num_robots
x = obj.val(2*j-1:2*j);
for i_ob = 1:length(obst)
if any(inpolygon(x(1,:),x(2,:),obst{i_ob}(:,1),obst{i_ob}(:,2)))
YesNo =1;
return
end
end
end
end
function old_limits = zoom_in(obj,zoom_ratio) %#ok<INUSD>
old_xlim = xlim;
old_ylim = ylim;
old_limits = [old_xlim,old_ylim];
% new_center = obj.joint_2D_locations(:,end);
% new_x_length = (old_xlim(2)-old_xlim(1))/zoom_ratio;
% new_y_length = (old_ylim(2)-old_ylim(1))/zoom_ratio;
% new_xlim = new_center(1) + [-new_x_length,new_x_length]/2;
% new_ylim = new_center(2) + [-new_y_length,new_y_length]/2;
% axis([new_xlim,new_ylim])
end
end
methods
function sampled_state = sample_a_valid_state(obj)
product_space_sampling_flag = 0;
if product_space_sampling_flag == 1
sampled_state = product_space_sampling();
return
end
disp('we have to check the validity also')
robots_val = [];
for i = 1:obj.num_robots
[x,y]=ginput(1);
if isempty(x)
sampled_state = [];
return
else
robots_val = [robots_val ; [x ; y ] ]; %#ok<AGROW>
end
end
sampled_state = feval(class(obj),robots_val, obj.num_robots);
end
end
end
function sampled_state_product_space = product_space_sampling()
if state.dim ~= 6, error('this function only works for 3 planar (2D) robots'); end
sampled_state = state.empty;
finish_flag = 0;
max_samples = 20;
for i_samp = 1:max_samples
%---------we select a VALID single joint sample
while 1
[x1,y1]=ginput(1);
if isempty(x1)
finish_flag = 1;
break
end
window_size = 5;
x2 = x1+rand*window_size - window_size/2;
x3 = x1+rand*window_size - window_size/2;
y2 = y1+rand*window_size - window_size/2;
y3 = y1+rand*window_size - window_size/2;
tmp_state = state([x1;y1;x2;y2;x3;y3]);
if ~tmp_state.is_constraint_violated()
break
end
end
%----------
if finish_flag == 1
break
else
tmp_state.draw();
sampled_state = [sampled_state , tmp_state];
end
end
%for i_rob = 1:state.num_robots
n_s = length(sampled_state);
sampled_state_product_space = state.empty(0,n_s^3);
for i_samp = 1:n_s
for j_samp = 1:n_s
for k_samp = 1:n_s
product_sample = state ( [sampled_state(i_samp).val(1:2) ; sampled_state(j_samp).val(3:4) ; sampled_state(k_samp).val(5:6)] );
sampled_state_product_space = [sampled_state_product_space , product_sample];
end
end
end
end
|
github
|
mubeipeng/focused_slam-master
|
planar_robot_XYTheta_state.m
|
.m
|
focused_slam-master/FIRM/All_state/planar_robot_XYTheta_state.m
| 10,745 |
utf_8
|
4c5314bb8c6748c04648327554223ff7
|
classdef planar_robot_XYTheta_state < state_interface
% This class encapsulates the state of a planar robot, described by its 2D location and heading angle.
properties (Constant)
label = 'planar_robot_XYTheta_state';
dim = 3; % state dimension
sup_norm_weights_nonNormalized = 1./[1 ; 1 ; inf];
sup_norm_weights = planar_robot_XYTheta_state.sup_norm_weights_nonNormalized / norm(planar_robot_XYTheta_state.sup_norm_weights_nonNormalized); % we normalize the weights here.
FIRM_node_mean_neighborhood_weights = [0.08 ; 0.08 ; 3 *pi/180 ] ; % this only works for 3D state spaces % note that the last entry, ie theta's neighborhood, has to be in radian.
end
properties
val; % value of the state
plot_handle; % handle for the "drawings" associated with the state
head_handle;
tria_handle;
text_handle; % handle for the "displayed text" associated with the state
end
methods
function obj = planar_robot_XYTheta_state(varargin)
obj = obj@state_interface(varargin{:});
end
function signed_dist_vector = signed_element_wise_dist(obj,x2) % this function returns the "Signed element-wise distnace" between two states x1 and x2
x1 = obj.val; % retrieve the value of the state vector
if isa(x2,'state'), x2=x2.val; end % retrieve the value of the state vector
signed_dist_vector = x1 - x2;
% Following part takes care of periodicity in heading angle representation.
th_dist = signed_dist_vector(3);
if th_dist >= 0
th_dist_bounded = mod( th_dist , 2*pi );
if th_dist_bounded > pi, th_dist_bounded = th_dist_bounded - 2*pi; end
else
th_dist_bounded = - mod( -th_dist , 2*pi );
if th_dist_bounded < -pi, th_dist_bounded = th_dist_bounded + 2*pi; end
end
signed_dist_vector(3) = th_dist_bounded; % updating the angle distance
end
function obj = draw(obj, varargin)
% The full list of properties for this function is:
% 'RobotShape', 'RobotSize', 'TriaColor', 'color', 'HeadShape',
% 'HeadSize'.
% default values
robot_shape = 'point';
robot_size = 0.5;
tria_color = 'b';
head_color = 'b';
head_shape = '*';
head_size = 6;
robot_text = [];
font_size = 15;
text_color = 'b';
for i = 1 : 2 : length(varargin)
switch lower(varargin{i})
case lower('RobotShape')
robot_shape = varargin{i+1};
case lower('RobotSize')
robot_size = varargin{i+1};
case lower('TriaColor')
tria_color = varargin{i+1};
case lower('color')
head_color = varargin{i+1};
case lower('HeadShape')
head_shape = varargin{i+1};
case lower('HeadSize')
head_size = varargin{i+1};
case lower('text')
robot_text = varargin{i+1};
case lower('fontsize')
font_size = varargin{i+1};
case lower('textcolor')
text_color = varargin{i+1};
otherwise
error('This property does not exist.')
end
end
x=obj.val;
obj.head_handle = plot(x(1),x(2),'Marker',head_shape,'MarkerSize',head_size,'MarkerEdgeColor',head_color,'MarkerFaceColor',head_color);
th=x(3);
vertices_x=[0,-robot_size,-robot_size,0];
vertices_y=[0,-robot_size/5,robot_size/5,0];
R=[cos(th),-sin(th);sin(th),cos(th)];
vert=R*[vertices_x;vertices_y];
% plot the triangle body
if strcmpi(robot_shape,'triangle') % strcmpi is not sensitive to letter scase.
tmp=get(gca,'NextPlot');
hold on
obj.tria_handle = plot(vert(1,:)+x(1),vert(2,:)+x(2),'color',tria_color);
set(gca,'NextPlot',tmp);
end
% write the text next to the robot
if ~isempty(robot_text)
robot_size_for_text=robot_size*1.5; % we need a slightly bigger robot so that the text does not interfere with actual robot.
vertices_x=[0,-robot_size_for_text,-robot_size_for_text,0];
vertices_y=[0,-robot_size_for_text/5,robot_size_for_text/5,0];
R=[cos(th),-sin(th);sin(th),cos(th)];
vert=R*[vertices_x;vertices_y];
text_pos=(vert(:,2)+vert(:,3))/2 + x(1:2); % we add the mid-point of the base of this bigger robot to its heading position to find the text position, right behind the robot.
text_pos(1) = text_pos(1) - 0.45; % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
obj.text_handle = text(text_pos(1),text_pos(2),robot_text,'fontsize',font_size,'color',text_color);
end
obj.tria_handle = [obj.tria_handle,plot_3D_cone_in_2D(x(1),x(2),th,tria_color)];
end
function obj = delete_plot(obj,varargin)
% The list of properties for this function is:
% 'triangle', 'head'.
if isempty(varargin)
try % Avoid errors if the graphic object has already been deleted
delete(obj.head_handle);
obj.head_handle = [];
end
try % Avoid errors if the graphic object has already been deleted
delete(obj.tria_handle);
obj.tria_handle = [];
end
try % Avoid errors if the graphic object has already been deleted
delete(obj.text_handle);
obj.text_handle = [];
end
else
for i = 1 : length(varargin)
switch varargin{i}
case 'triangle'
try % Avoid errors if the graphic object has already been deleted
delete(obj.tria_handle);
obj.tria_handle = [];
end
case 'head'
try % Avoid errors if the graphic object has already been deleted
delete(obj.head_handle)
obj.head_handle = [];
end
case 'text'
try % Avoid errors if the graphic object has already been deleted
delete(obj.text_handle);
obj.text_handle = [];
end
otherwise
error('There is no such a handle to delete')
end
end
end
end
function neighb_plot_handle = draw_neighborhood(obj, scale)
tmp_th = 0:0.1:2*pi;
x = obj.val(1);
y = obj.val(2);
neighb_plot_handle = plot(scale*cos(tmp_th) + x , scale*sin(tmp_th) + y);
end
function YesNo = is_constraint_violated(obj,sim)
x = obj.val;
YesNo = 0; % initialization
obst = sim.obstacle.obst; % for abbreviation
for i_ob = 1:length(obst)
if any(inpolygon(x(1,:),x(2,:),obst{i_ob}(:,1),obst{i_ob}(:,2)))
YesNo =1;
return
end
end
end
function old_limits = zoom_in(obj,zoom_ratio)
old_xlim = xlim;
old_ylim = ylim;
old_limits = [old_xlim,old_ylim];
new_center = obj.val;
new_x_length = (old_xlim(2)-old_xlim(1))/zoom_ratio;
new_y_length = (old_ylim(2)-old_ylim(1))/zoom_ratio;
new_xlim = new_center(1) + [-new_x_length,new_x_length]/2;
new_ylim = new_center(2) + [-new_y_length,new_y_length]/2;
axis([new_xlim,new_ylim])
end
end
methods (Static)
function sampled_state = sample_a_valid_state()
user_or_random = 'user';
if strcmp(user_or_random , 'user')
[x,y]=ginput(1);
if isempty(x)
sampled_state = [];
return
else
random_theta = rand*2*pi - pi; % generates a random orientation between -pi and pi
sampled_state = state([x ; y ; random_theta]);
end
if sampled_state.is_constraint_violated()
sampled_state = user_samples_a_state();
end
elseif strcmp(user_or_random , 'random')
error('not yet implemented')
else
error('not correct!');
end
end
end
end
function plot_handle = plot_3D_cone_in_2D(x_robot,y_robot,theta_robot,color)
size_ratio = 0.75;
r = 1*size_ratio;
h = 2*size_ratio;
m = h/r;
[R,A] = meshgrid(linspace(0,r,2),linspace(0,2*pi,20));
X = R .* cos(A);
Y = R .* sin(A);
Z = m*R;
X_base = X;
Y_base = Y;
Z_base = h*ones(size(X_base));
% Cone around the z-axis, point at the origin
% mesh(X,Y,Z)
X = [X,X_base];
Y = [Y,Y_base];
Z = [Z,Z_base];
% mesh(X,Y,Z)
% axis equal
% axis([-3 3 -3 3 0 3])
phi = pi/2;
X1 = X*cos(phi) - Z*sin(phi);
Y1 = Y;
Z1 = X*sin(phi) + Z*cos(phi);
% Previous cone, rotated by angle phi about the y-axis
%mesh(X1,Y1,Z1)
% h_cone = surf(X1,Y1,Z1);
% set(h_cone,'edgecolor','none','facecolor',color,'facelighting','gouraud');
X2 = X1*cos(theta_robot) - Y1*sin(theta_robot) + x_robot;
Y2 = X1*sin(theta_robot) + Y1*cos(theta_robot) + y_robot;
Z2 = Z1;
% Second cone rotated by angle theta about the z-axis
plot_handle = mesh(X2,Y2,Z2);
% axis equal
% set(gca,'PlotBoxAspectRatio',[1 1 1]);
% camlight(135,180);
% view([30,25]);
set(plot_handle,'edgecolor','none','facecolor',color,'facelighting','phong');
% xlabel('x')
% ylabel('y')
% zlabel('z')
end
|
github
|
mubeipeng/focused_slam-master
|
Multi_planar_robots_XYTheta_state.m
|
.m
|
focused_slam-master/FIRM/All_state/Multi_planar_robots_XYTheta_state.m
| 11,131 |
utf_8
|
536f5a239512b610e02ff2fee58a0af1
|
classdef Multi_planar_robots_XYTheta_state < state_interface
% This class encapsulates the state of a planar robot, described by its 2D location and heading angle.
properties (Constant)
num_robots = user_data_class.par.state_parameters.num_robots;
dim = 3*state.num_robots; % state dimension
end
properties
val; % value of the state
plot_handle=[]; % handle for the "drawings" associated with the state
head_handle=[];
tria_handle=[];
text_handle=[]; % handle for the "displayed text" associated with the state
end
methods
function obj = Multi_planar_robots_XYTheta_state(varargin)
obj = obj@state_interface(varargin{:});
end
function signed_dist_vector = signed_element_wise_dist(obj,x2) % this function returns the "Signed element-wise distnace" between two states x1 and x2
x1 = obj.val; % retrieve the value of the state vector
if isa(x2,'state'), x2=x2.val; end % retrieve the value of the state vector
signed_dist_vector = x1 - x2;
% Following part takes care of periodicity in heading angle representation.
for i = 1:obj.num_robots
th_dist = signed_dist_vector(3*i);
if th_dist >= 0
th_dist_bounded = mod( th_dist , 2*pi );
if th_dist_bounded > pi, th_dist_bounded = th_dist_bounded - 2*pi; end
else
th_dist_bounded = - mod( -th_dist , 2*pi );
if th_dist_bounded < -pi, th_dist_bounded = th_dist_bounded + 2*pi; end
end
signed_dist_vector(3*i) = th_dist_bounded; % updating the angle distance
end
end
function obj = draw(obj, varargin)
% The full list of properties for this function is:
% 'RobotShape', 'RobotSize', 'TriaColor', 'color', 'HeadShape',
% 'HeadSize'.
% default values
robot_shape = 'triangle';
robot_size = 0.5;
robot_color = 'b';
head_shape = '*';
head_size = 6;
robot_text = {};
font_size = 15;
text_color = 'b';
for i = 1 : 2 : length(varargin)
switch lower(varargin{i})
case lower('RobotShape')
robot_shape = varargin{i+1};
case lower('RobotSize')
robot_size = varargin{i+1};
case lower('TriaColor')
robot_color = varargin{i+1};
case lower('color')
robot_color = varargin{i+1};
case lower('HeadShape')
head_shape = varargin{i+1};
case lower('HeadSize')
head_size = varargin{i+1};
case lower('text')
robot_text = varargin{i+1};
case lower('fontsize')
font_size = varargin{i+1};
case lower('textcolor')
text_color = varargin{i+1};
otherwise
error('This property does not exist.')
end
end
if user_data_class.par.Lighting_and_3D_plots == 1
robot_shape = 'cone'; % we overwrite user's choice if the simulation has to be done in 3D and under camera light
end
tmp=get(gca,'NextPlot');
hold on
for i = 1:obj.num_robots
x = obj.val(3*i-2:3*i);
obj.head_handle = [obj.head_handle,plot(x(1),x(2),'Marker',head_shape,'MarkerSize',head_size,'MarkerEdgeColor',robot_color,'MarkerFaceColor',robot_color)];
th = x(3);
if strcmpi(robot_shape,'triangle') % strcmpi is not sensitive to letter scase.
vertices_x = [0,-robot_size,-robot_size,0];
vertices_y = [0,-robot_size/5,robot_size/5,0];
R = [cos(th),-sin(th);sin(th),cos(th)];
vert = R*[vertices_x;vertices_y];
obj.tria_handle = [obj.tria_handle,plot(vert(1,:)+x(1),vert(2,:)+x(2),'color',robot_color)]; % plot the triangle body
elseif strcmpi(robot_shape,'cone') % strcmpi is not sensitive to letter scase.
obj.tria_handle = [obj.tria_handle,plot_3D_cone_in_2D(x(1),x(2),th,robot_color)]; % plot the 3D conde body
end
% write the text next to the robot
if ~isempty(robot_text)
robot_size_for_text=robot_size*1.5; % we need a slightly bigger robot so that the text does not interfere with actual robot.
vertices_x=[0,-robot_size_for_text,-robot_size_for_text,0];
vertices_y=[0,-robot_size_for_text/5,robot_size_for_text/5,0];
R=[cos(th),-sin(th);sin(th),cos(th)];
vert=R*[vertices_x;vertices_y];
text_pos=(vert(:,2)+vert(:,3))/2 + x(1:2); % we add the mid-point of the base of this bigger robot to its heading position to find the text position, right behind the robot.
text_pos(1) = text_pos(1) - 0.45; % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
obj.text_handle = [obj.text_handle,text(text_pos(1),text_pos(2),robot_text,'fontsize',font_size,'color',text_color)];
end
end
set(gca,'NextPlot',tmp);
end
function obj = delete_plot(obj,varargin)
% The list of properties for this function is:
% 'triangle', 'head'.
if isempty(varargin)
try % Avoid errors if the graphic object has already been deleted
delete(obj.head_handle);
obj.head_handle = [];
end
try % Avoid errors if the graphic object has already been deleted
delete(obj.tria_handle);
obj.tria_handle = [];
end
try % Avoid errors if the graphic object has already been deleted
delete(obj.text_handle);
obj.text_handle = [];
end
else
for i = 1 : length(varargin)
switch varargin{i}
case 'triangle'
try % Avoid errors if the graphic object has already been deleted
delete(obj.tria_handle);
obj.tria_handle = [];
end
case 'head'
try % Avoid errors if the graphic object has already been deleted
delete(obj.head_handle)
obj.head_handle = [];
end
case 'text'
try % Avoid errors if the graphic object has already been deleted
delete(obj.text_handle);
obj.text_handle = [];
end
otherwise
error('There is no such a handle to delete')
end
end
end
end
function neighb_plot_handle = draw_neighborhood(obj, scale)
tmp_th = 0:0.1:2*pi;
neighb_plot_handle = [];
for i = 1:obj.num_robots
x = obj.val(3*i-2);
y = obj.val(3*i-1);
tmp_h = plot(scale*cos(tmp_th) + x , scale*sin(tmp_th) + y);
neighb_plot_handle = [neighb_plot_handle , tmp_h]; %#ok<AGROW>
end
end
function YesNo = is_constraint_violated(obj)
YesNo = 0; % initialization
obst = obstacles_class.obst; % for abbreviation
for j = 1:obj.num_robots
x = obj.val(3*j-2:3*j-1);
for i_ob = 1:length(obst)
if any(inpolygon(x(1,:),x(2,:),obst{i_ob}(:,1),obst{i_ob}(:,2)))
YesNo =1;
return
end
end
end
end
function old_limits = zoom_in(obj,zoom_ratio)
old_xlim = xlim;
old_ylim = ylim;
old_limits = [old_xlim,old_ylim];
% new_center = obj.joint_2D_locations(:,end);
% new_x_length = (old_xlim(2)-old_xlim(1))/zoom_ratio;
% new_y_length = (old_ylim(2)-old_ylim(1))/zoom_ratio;
% new_xlim = new_center(1) + [-new_x_length,new_x_length]/2;
% new_ylim = new_center(2) + [-new_y_length,new_y_length]/2;
% axis([new_xlim,new_ylim])
end
end
methods (Static)
function sampled_state = sample_a_valid_state()
disp('we have to check the validity also')
robots_val = [];
for i = 1:state.num_robots
[x,y]=ginput(1);
if isempty(x)
sampled_state = [];
return
else
random_theta = rand*2*pi - pi; % generates a random orientation between -pi and pi
robots_val = [robots_val ; [x ; y ; random_theta] ]; %#ok<AGROW>
end
end
sampled_state = state(robots_val);
end
end
end
function plot_handle = plot_3D_cone_in_2D(x_robot,y_robot,theta_robot,color)
size_ratio = 0.75;
r = 1*size_ratio;
h = 2*size_ratio;
m = h/r;
[R,A] = meshgrid(linspace(0,r,2),linspace(0,2*pi,20));
X = R .* cos(A);
Y = R .* sin(A);
Z = m*R;
X_base = X;
Y_base = Y;
Z_base = h*ones(size(X_base));
% Cone around the z-axis, point at the origin
% mesh(X,Y,Z)
X = [X,X_base];
Y = [Y,Y_base];
Z = [Z,Z_base];
% mesh(X,Y,Z)
% axis equal
% axis([-3 3 -3 3 0 3])
phi = pi/2;
X1 = X*cos(phi) - Z*sin(phi);
Y1 = Y;
Z1 = X*sin(phi) + Z*cos(phi);
% Previous cone, rotated by angle phi about the y-axis
%mesh(X1,Y1,Z1)
% h_cone = surf(X1,Y1,Z1);
% set(h_cone,'edgecolor','none','facecolor',color,'facelighting','gouraud');
X2 = X1*cos(theta_robot) - Y1*sin(theta_robot) + x_robot;
Y2 = X1*sin(theta_robot) + Y1*cos(theta_robot) + y_robot;
Z2 = Z1;
% Second cone rotated by angle theta about the z-axis
plot_handle = mesh(X2,Y2,Z2);
% axis equal
% set(gca,'PlotBoxAspectRatio',[1 1 1]);
% camlight(135,180);
% view([30,25]);
set(plot_handle,'edgecolor','none','facecolor',color,'facelighting','phong');
% xlabel('x')
% ylabel('y')
% zlabel('z')
end
|
github
|
mubeipeng/focused_slam-master
|
Planar_dyn_manipulator_state.m
|
.m
|
focused_slam-master/FIRM/All_state/Planar_dyn_manipulator_state.m
| 9,738 |
utf_8
|
e63d596a57b2945029a1a83c631b976e
|
classdef Planar_dyn_manipulator_state < state_interface
% This class encapsulates the state of the system.
properties (Constant)
num_revolute_joints = user_data_class.par.state_parameters.num_revolute_joints;
dim = 2*Planar_dyn_manipulator_state.num_revolute_joints; % state dimension
link_length = 0.5;
end
properties
val; % value of the state
joint_2D_locations; % 2D locations of joints in the plane
plot_handle; % handle for the "drawings" associated with the state
text_handle; % handle for the "displayed text" associated with the state
end
methods
function obj = Planar_dyn_manipulator_state(varargin) % constructor function
obj = obj@state_interface(varargin{:});
th = obj.val(1:Planar_dyn_manipulator_state.num_revolute_joints);
sum_theta = 0; % initialization % since teh manipulator works in a plane, the rotation has to be a 2by2 matrix
end_link = [0;0]; % this is the location in the plane that the beginning of the manipulator is attached to
for i = 1:Planar_dyn_manipulator_state.num_revolute_joints
sum_theta = sum_theta + th(i); % at i-th iteration R_prod is the product of R1*R2*...*Ri
start_link = end_link(:,max(i-1,1)); % 2D position of the start of i-th link in plane
end_link(:,i) = obj.Rot_2D(sum_theta)*[obj.link_length;0] + start_link; % 2D position of the end of i-th link in plane % [obj.link_length;0] means that the length of the i-th joint is 1.
end
obj.joint_2D_locations = end_link; % Note that the i-th column of this matrix is the 2D location of the end of i-th link in the manipulator.
end
end
methods
function signed_dist_vector = signed_element_wise_dist(obj,x2) % this function returns the "Signed element-wise distnace" between two states x1 and x2
x1 = obj.val; % retrieve the value of the state vector
if isa(x2,'Planar_dyn_manipulator_state'), x2=x2.val; end % retrieve the value of the state vector
signed_dist_vector = x1 - x2;
% Following part takes care of periodicity in heading angle representation.
for i = 1:obj.num_revolute_joints
th_dist = signed_dist_vector(i);
if th_dist >= 0
th_dist_bounded = mod( th_dist , 2*pi );
if th_dist_bounded > pi, th_dist_bounded = th_dist_bounded - 2*pi; end
else
th_dist_bounded = - mod( -th_dist , 2*pi );
if th_dist_bounded < -pi, th_dist_bounded = th_dist_bounded + 2*pi; end
end
signed_dist_vector(i) = th_dist_bounded; % updating the angle distance
end
end
function obj = draw(obj, varargin) % draw state
manip_color = 'b'; %default color
robot_text = [];
font_size = 15;
text_color = 'b';
for i = 1 : 2 : length(varargin)
switch lower(varargin{i})
case lower('color')
manip_color = varargin{i+1};
case lower('text')
robot_text = varargin{i+1};
case lower('fontsize')
font_size = varargin{i+1};
case lower('textcolor')
text_color = varargin{i+1};
end
end
all_joints = [ [0;0] , obj.joint_2D_locations ];
obj.plot_handle = plot( all_joints(1,:) , all_joints(2,:) , 'color', manip_color);
if ~isempty(robot_text)
text_pos = obj.joint_2D_locations(:,end);
text_pos(1) = text_pos(1) - 0.45; % for some reason MATLAB shifts the starting point of the text a little bit to the right. So, here we return it back.
obj.text_handle = text(text_pos(1),text_pos(2),robot_text,'fontsize',font_size,'color',text_color);
end
end
function obj = delete_plot(obj,varargin) % delete state drawings
try
delete(obj.plot_handle);
end
obj.plot_handle =[];
end
function neighb_plot_handle = draw_neighborhood(obj, scale)
disp('state.draw_neighborhood has not been implemented yet');
neighb_plot_handle = [];
end
function YesNo = is_constraint_violated(obj) % this function checks if the "state" is a collilsion-free one or not.
YesNo = 0; % initialization
all_joints = [ [0;0] , obj.joint_2D_locations ]; % Actually, this is a polyline
% first we check the self-intersections
[x_inters,~] = polyxpoly(all_joints(1,:),all_joints(2,:),all_joints(1,:),all_joints(2,:)); % the intersection points must be the vertices of the manipulator polygon
if length(x_inters)>size(all_joints,2) % if there is any more intersection points than the number of manipulator joints, that means that we have a self-intersection
YesNo=1;
return
end
% now, we check the intersection with obstacls
Obst = obstacles_class.obst;
N_obst=size(Obst,2);
for ib=1:N_obst
X_obs=[Obst{ib}(:,1);Obst{ib}(1,1)];
Y_obs=[Obst{ib}(:,2);Obst{ib}(1,2)];
[x_inters,~] = polyxpoly(X_obs,Y_obs,all_joints(1,:),all_joints(2,:));
if ~isempty(x_inters)
YesNo=1;
return
end
end
end
function old_limits = zoom_in(obj,zoom_ratio)
old_xlim = xlim;
old_ylim = ylim;
old_limits = [old_xlim,old_ylim];
new_center = obj.joint_2D_locations(:,end);
new_x_length = (old_xlim(2)-old_xlim(1))/zoom_ratio;
new_y_length = (old_ylim(2)-old_ylim(1))/zoom_ratio;
new_xlim = new_center(1) + [-new_x_length,new_x_length]/2;
new_ylim = new_center(2) + [-new_y_length,new_y_length]/2;
axis([new_xlim,new_ylim])
end
end
methods (Static)
function sampled_state = sample_a_valid_state()
user_or_random = 'user';
if strcmp(user_or_random , 'user')
sampled_state = user_samples_a_state();
elseif strcmp(user_or_random , 'random')
sampled_state = randomly_sample_a_state();
else
error('not correct!');
end
end
end
methods (Access = private)
function R = Rot_2D(obj,th)
R = [cos(th) -sin(th);sin(th) cos(th)];
end
end
end
function sampled_state = user_samples_a_state()
x_circle = cos(0:0.1:2*pi)*Planar_dyn_manipulator_state.link_length; y_circle = sin(0:0.1:2*pi)*Planar_dyn_manipulator_state.link_length; % to plot indicator (helper) circles
end_link = [0;0]; % this is the location in the plane that the beginning of the manipulator is attached to
for i = 1:Planar_dyn_manipulator_state.num_revolute_joints
circle_handle = plot(x_circle + end_link(1), y_circle + end_link(2));
circle_handle = [circle_handle , plot(end_link(1),end_link(2),'*')];
[x,y]=ginput(1);
if isempty(x)
delete(circle_handle);
sampled_state = [];
return
else
start_link = end_link; % 2D position of the start of i-th link in plane
rel_vector = [x;y] - start_link; % relative vector
rel_vector = rel_vector/norm(rel_vector)*Planar_dyn_manipulator_state.link_length; % making the length of link equal to "state.link_length"
end_link = rel_vector + start_link;
tmp_h = plot( [start_link(1) , end_link(1)] , [start_link(2) , end_link(2)] ,'r');
delete(circle_handle);
th_absolute(i,1) = atan2(end_link(2) - start_link(2) , end_link(1) - start_link(1)) ;
end
end
th_joints = [th_absolute(1) ; diff(th_absolute)];
for i = 1:Planar_dyn_manipulator_state.num_revolute_joints
th_dist = th_joints(i);
if th_dist >= 0
th_dist_bounded = mod( th_dist , 2*pi );
if th_dist_bounded > pi, th_dist_bounded = th_dist_bounded - 2*pi; end
else
th_dist_bounded = - mod( -th_dist , 2*pi );
if th_dist_bounded < -pi, th_dist_bounded = th_dist_bounded + 2*pi; end
end
th_joints(i) = th_dist_bounded; % updating the angle distance
end
velocities = zeros( Planar_dyn_manipulator_state.num_revolute_joints , 1); % we are sampling in the equilibrium space
sampled_state = Planar_dyn_manipulator_state([th_joints;velocities]);
if sampled_state.is_constraint_violated()
sampled_state = user_samples_a_state();
end
end
function sampled_state = randomly_sample_a_state()
random_configuration = rand(Planar_dyn_manipulator_state.dim/2,1)*2*pi-pi;
zero_velocities = zeros( Planar_dyn_manipulator_state.num_revolute_joints , 1); % we are sampling in the equilibrium space
sampled_state_val = [random_configuration;zero_velocities];
sampled_state = Planar_dyn_manipulator_state(sampled_state_val);
link_stretch = norm(sampled_state.joint_2D_locations(:,end)); % if the base is not [0;0], we need to subtract the base before computing the norm
if link_stretch<1.9 || sampled_state.is_constraint_violated() % The first condition tries to reject the samples that are not streched enough!
sampled_state = randomly_sample_a_state();
end
end
|
github
|
mubeipeng/focused_slam-master
|
generate_measurements.m
|
.m
|
focused_slam-master/focused_mapping/lib/generate_measurements.m
| 4,391 |
utf_8
|
aaa062480dd0541c1874d179f055ca46
|
function [lm_edge, t] = generate_measurements(name,J, lm_edge, variableList, focus_lm_list, N_select)
tic
switch name
case 'focus_select'
selectIdx = selection_focus(J, variableList, focus_lm_list, N_select, lm_edge);
case 'full_select'
selectIdx = selection_full(J, variableList, N_select, lm_edge);
case 'down_select'
selectIdx = selection_down(focus_lm_list, N_select, lm_edge);
case 'down_all'
selectIdx = false(length(lm_edge.id1),1);
for i=1:length(focus_lm_list)
selectIdx(lm_edge.id2==focus_lm_list(i))=true;
end
otherwise
fprintf('unrecoginizable selection method');
end
t = toc;
% generate reduced set of measurements
lm_edge.id1 = lm_edge.id1(selectIdx);
lm_edge.id2 = lm_edge.id2(selectIdx);
lm_edge.dpos = lm_edge.dpos(:,selectIdx);
lm_edge.infoVec = lm_edge.infoVec(:,selectIdx);
end
%%
function selectIdx = selection_down(lm_focus_list, N_select, landmark_edge)
selectIdx = false(length(landmark_edge.id1),1);
candidates=[];
for i=1:length(lm_focus_list)
candidates=[candidates find(landmark_edge.id2==lm_focus_list(i))];
end
N = length(candidates);
delta = floor((N-1)/N_select);
start = ceil(rand*(N - N_select*delta));
selectIdx(candidates(start:delta:N))=true;
end
%%
function [selectIdx] = selection_focus(J, variableList, lm_focus_list, N, landmark_edge)
% compute focus covariance matrix and marginal unfocused covariance matrix
focusIdx = false(size(variableList));
for t=1:length(lm_focus_list)
focusIdx(variableList==lm_focus_list(t))=true;
end
cov_full = inv(J);
cov_cc = zeros(size(J));
cov_cc(~focusIdx,~focusIdx) = cov_full(~focusIdx,~focusIdx)...
- cov_full(~focusIdx,focusIdx)/cov_full(focusIdx,focusIdx)*cov_full(focusIdx,~focusIdx);
selectIdx = false(1, length(landmark_edge.id1));
fprintf('compute measure');
for i=1:N
fprintf(' %i',i);
% compute values
edge_value = zeros(size(variableList));
parfor t=1:length(landmark_edge.id1)
if ~selectIdx(t)
vIdx1 = find(variableList==landmark_edge.id1(t));
vIdx2 = find(variableList==landmark_edge.id2(t));
vIdx = [vIdx1 vIdx2];
noise = landmark_edge.infoVec(1,t);
edge_value(t) = log(1+noise*[1 -1]*cov_full(vIdx,vIdx)*[1;-1])...
-log(1+noise*[1 -1]*cov_cc(vIdx,vIdx)*[1;-1]);
end
end
[~,idx] = max(edge_value);
selectIdx(idx)=true;
vIdx1 = find(variableList==landmark_edge.id1(idx));
vIdx2 = find(variableList==landmark_edge.id2(idx));
vIdx = [vIdx1 vIdx2];
noise = landmark_edge.infoVec(1,idx);
% update covariance matrix
cov_full = cov_full - noise/(1+noise*[1 -1]*cov_full(vIdx,vIdx)*[1;-1])...
*cov_full(:,vIdx)*[1 -1; -1 1]*cov_full(vIdx,:);
%if(~focusIdx(vIdx1) && ~focusIdx(vIdx2))
cov_cc(~focusIdx,~focusIdx) = cov_full(~focusIdx,~focusIdx)...
- cov_full(~focusIdx,focusIdx)/cov_full(focusIdx,focusIdx)*cov_full(focusIdx,~focusIdx);
%end
end
fprintf('\n');
%% close loop on last pose
for i=lm_focus_list
idx = (selectIdx & landmark_edge.id2==i);
if sum(idx)==1
selectIdx(idx)=false;
end
end
end
%%
function [selectIdx] = selection_full(J, variableList, N_select, landmark_edge)
cov_full = inv(J);
selectIdx = false(length(landmark_edge.id1),1);
fprintf('compute measure');
for i=1:N_select
if mod(i,25)==0
fprintf(' %i\n',i);
else
fprintf(' %i',i);
end
% compute values
edge_value = zeros(size(variableList));
parfor t=1:length(landmark_edge.id1)
if ~selectIdx(t)
vIdx1 = find(variableList==landmark_edge.id1(t));
vIdx2 = find(variableList==landmark_edge.id2(t));
vIdx = [vIdx1 vIdx2];
noise = landmark_edge.infoVec(1,t);
edge_value(t) = log(1+noise*[1 -1]*cov_full(vIdx,vIdx)*[1;-1]);
end
end
[~,idx] = max(edge_value);
selectIdx(idx)=true;
vIdx1 = find(variableList==landmark_edge.id1(idx));
vIdx2 = find(variableList==landmark_edge.id2(idx));
vIdx = [vIdx1 vIdx2];
noise = landmark_edge.infoVec(1,idx);
% update covariance matrix
cov_full = cov_full - noise/(1+noise*[1 -1]*cov_full(vIdx,vIdx)*[1;-1])...
*cov_full(:,vIdx)*[1 -1; -1 1]*cov_full(vIdx,:);
end
fprintf('\n');
end
|
github
|
mubeipeng/focused_slam-master
|
generate_focused_landmark.m
|
.m
|
focused_slam-master/focused_mapping/lib/generate_focused_landmark.m
| 2,538 |
utf_8
|
6b50ff48ce6ff60d2887ae33c9df2931
|
function [lm_focused,t] = generate_focused_landmark(N,lm_edge,node_edge)
tic;
%%
lm_list = unique(lm_edge.id2);
lm_focused = [];
N_odom = length(node_edge.id2);
n_observed_lm = zeros(1,N_odom); % No. of landmarks observed at each odom node
odom_count = zeros(1,N_odom);
odom_list = unique(lm_edge.id1);
odom_count(odom_list) = hist(lm_edge.id1,odom_list);
%%
%% process and measurement noise for riccate equation
Q = 1/node_edge.infoVec(1);
R_info = lm_edge.infoVec(1);
R_prior=0.1;
node_cov = 0.5*Q+0.5*sqrt( Q.^2+4.*Q./(R_prior+R_info*n_observed_lm) );
for n = 1:N+5
%% Mahalanobis distance
dist_mahalanobis = node_edge.closeP./node_cov.*node_edge.closeP;
min_dist = min(dist_mahalanobis(odom_count>0));
minDist = zeros(length(lm_list),1);
for jj=1:length(lm_list)
if ~any(lm_list(jj)==lm_focused)
idx = lm_edge.id1( lm_edge.id2==lm_list(jj)); %odom idx observe landmark jj
minDist(jj) = sum(dist_mahalanobis(idx)<1.2*min_dist);
% minDist(jj) = min(dist_mahalanobis(idx));
end
end
[~, lm_idx] = max(minDist);
lm_id = lm_list(lm_idx);
lm_focused = [lm_focused lm_id];
%% update number of observed landmarks
lm_meas_idx = lm_edge.id2==lm_id;
odom_id = lm_edge.id1(lm_meas_idx);
odom_count(odom_id) = odom_count(odom_id)-1;
n_observed_lm(odom_id) = n_observed_lm(odom_id)+1;
node_cov = 0.5*Q+0.5*sqrt( Q.^2+4.*Q./(R_prior+R_info*n_observed_lm) );
end
t=toc;
% %% select extra landmarks to cover the space
% % process J
% n_var = length(J);
% for n=1:N
% H = jaccobian(lm_meas,R_info,lm_focused(n),n_var,variablelist);
% J = J+H*H';
% end
%
% Lambda = inv(J);
% lm_id = unique(lm_meas.id2);
% for i=1:10
% gap = zeros(length(lm_id),1);
% parfor jj=1:length(lm_id)
% if ~any(lm_focused==lm_id(jj))
% H = jaccobian(lm_meas,R_info,lm_id(jj),n_var,variablelist);
% gap(jj)= log(1+H'*Lambda*H);
% end
% end
% [~, idx]=max(gap);
% lm_focused = [lm_focused lm_id(idx)];
% H = jaccobian(lm_meas, R_info, lm_id(idx), n_var, variablelist);
% L = Lambda*H;
% Lambda = Lambda - L/(1+H'*Lambda*H)* L';
% end
end
function H = jaccobian(lm_meas, R_info, lm_id, n_var,variableList)
H=zeros(n_var,1);
lm_idx = lm_id==variableList;
n_meas = 0;
for i=1:n_var
if lm_meas.id2(i)==lm_id;
odom_idx = variableList== lm_meas.id1(i);
H(odom_idx) = -R_info;
n_meas = n_meas+1;
end
end
H(lm_idx) = R_info*n_meas;
end
|
github
|
mubeipeng/focused_slam-master
|
estimateRigidTransform.m
|
.m
|
focused_slam-master/focused_mapping/lib/estimateRigidTransform.m
| 3,606 |
utf_8
|
8edf7adcc5d938488684040c13b16fb4
|
function [T, Eps] = estimateRigidTransform(x, y)
% ESTIMATERIGIDTRANSFORM
% [T, EPS] = ESTIMATERIGIDTRANSFORM(X, Y) estimates the rigid transformation
% that best aligns x with y (in the least-squares sense).
%
% Reference: "Estimating Rigid Transformations" in
% "Computer Vision, a modern approach" by Forsyth and Ponce (1993), page 480
% (page 717(?) of the newer edition)
%
% Input:
% X: 3xN, N 3-D points (N>=3)
% Y: 3xN, N 3-D points (N>=3)
%
% Output
% T: the rigid transformation that aligns x and y as: xh = T * yh
% (h denotes homogenous coordinates)
% (corrspondence between points x(:,i) and y(:,i) is assumed)
%
% EPS: the smallest singular value. The closer this value it is
% to 0, the better the estimate is. (large values mean that the
% transform between the two data sets cannot be approximated
% well with a rigid transform.
%
% Babak Taati, 2003
% (revised 2009)
if nargin ~= 2
error('Requires two input arguments.')
end
if size(x,1)~=3 || size(y,1)~=3
error('Input point clouds must be a 3xN matrix.');
end
if size(x, 2) ~= size(y,2)
error('Input point clouds must be of the same size');
end
if size(x,2)<3 || size(y,2)<3
error('At least 3 point matches are needed');
end
pointCount = length(x); % since x has N=3+ points, length shows the number of points
x_centroid = sum(x,2) / pointCount;
y_centroid = sum(y,2) / pointCount;
x_centrized = [x(1,:)-x_centroid(1) ; x(2,:)-x_centroid(2); x(3,:)-x_centroid(3)];
y_centrized = [y(1,:)-y_centroid(1) ; y(2,:)-y_centroid(2); y(3,:)-y_centroid(3)];
R12 = y_centrized' - x_centrized';
R21 = x_centrized - y_centrized;
R22_1 = y_centrized + x_centrized;
R22 = crossTimesMatrix(R22_1(1:3,:));
B = zeros(4, 4);
A = zeros(4, 4, pointCount);
for ii=1:pointCount
A(1:4,1:4,ii) = [0, R12(ii,1:3); R21(1:3,ii), R22(1:3,1:3,ii)];
B = B + A(:,:,ii)' * A(:,:,ii);
end
[~, S, V] = svd(B);
quat = V(:,4);
rot = quat2rot(quat);
T1 = [eye(3,3), -y_centroid ; 0 0 0 1];
T2 = [rot, [0; 0; 0]; 0 0 0 1];
T3 = [eye(3,3), x_centroid ; 0 0 0 1];
T = T3 * T2 * T1;
Eps = S(4,4);
end
function V_times = crossTimesMatrix(V)
% CROSSTIMESMATRIX
% V_TIMES = CROSSTIMESMATRIX(V) returns a 3x3 (or a series of 3x3) cross times matrices of input vector(s) V
%
% Input:
% V a 3xN matrix, rpresenting a series of 3x1 vectors
%
% Output:
% V_TIMES (Vx) a series of 3x3 matrices where V_times(:,:,i) is the Vx matrix for the vector V(:,i)
%
% Babak Taati, 2003
% (revised 2009)
[a,b] = size(V);
V_times = zeros(a, 3, b);
% V_times(1,1,:) = 0;
V_times(1,2,:) = - V(3,:);
V_times(1,3,:) = V(2,:);
V_times(2,1,:) = V(3,:);
% V_times(2,2,:) = 0;
V_times(2,3,:) = - V(1,:);
V_times(3,1,:) = - V(2,:);
V_times(3,2,:) = V(1,:);
% V_times(3,3,:) = 0;
end
function R = quat2rot(Q)
% QUAT2ROT
% R = QUAT2ROT(Q) converts a quaternion (4x1 or 1x4) into a 3x3 rotation mattrix
q0 = Q(1);
q1 = Q(2);
q2 = Q(3);
q3 = Q(4);
R(1,1) = q0*q0 + q1*q1 - q2*q2 - q3*q3;
R(1,2) = 2 * (q1*q2 - q0*q3);
R(1,3) = 2 * (q1*q3 + q0*q2);
R(2,1) = 2 * (q1*q2 + q0*q3);
R(2,2) = q0*q0 - q1*q1 + q2*q2 - q3*q3;
R(2,3) = 2 * (q2*q3 - q0*q1);
R(3,1) = 2 * (q1*q3 - q0*q2);
R(3,2) = 2 * (q2*q3 + q0*q1);
R(3,3) = q0*q0 - q1*q1 - q2*q2 + q3*q3;
end
|
github
|
markf94/QML_Thesis-master
|
bloch.m
|
.m
|
QML_Thesis-master/Octave/bloch.m
| 1,061 |
utf_8
|
2a9113b120276358d347c2d37793db53
|
%Project a two-level qubit state onto Bloch sphere
function [x,y,z,theta,phi] = bloch(alpha, beta)
% INPUT
% alpha|0> + beta|1>
% a and b are probability amplitudes from qubit
% Find and eliminate global phase
angle_alpha = angle(alpha)
angle_beta = angle(beta)
if angle_alpha < angle_beta
alpha_new = alpha/exp(i*angle_beta)
beta_new = beta/exp(i*angle_beta)
else
alpha_new = alpha/exp(i*angle_alpha)
beta_new = beta/exp(i*angle_alpha)
endif
%Computing theta and phi from probability amplitudes
theta = 2*acos(alpha_new);
phi = -i*log(beta_new/sin(theta/2));
%Theta and phi
%polar to cartesian conversion
%disp("============================")
%disp("x,y,z with imaginary part")
%x = sin(abs(theta))*cos(abs(phi));
x = sin(theta)*cos(phi);
%y = sin(abs(theta))*sin(abs(phi));
y = sin(theta)*sin(phi);
%z = cos(abs(theta));
z = cos(theta);
disp("============================")
disp("Check for vector length one...")
r = round(sqrt(x^2+y^2+z^2)*10)/10
if (round(sqrt(x^2+y^2+z^2)*10)/10==1)
disp("ok")
disp("============================")
endif
endfunction
|
github
|
markf94/QML_Thesis-master
|
f.m
|
.m
|
QML_Thesis-master/Octave/f.m
| 2,049 |
utf_8
|
efed95ffb8ca4100c49f6b71a56545aa
|
%% SCRIPT FOR CREATING A CONTROLLED-U QUANTUM GATE
% THEOREM:
% For any unitary matrix U we can find a decomposition into A,B,C such that:
% A*B*C = I
% exp(i*alpha)*A*X*B*X*C = U
% where X is the first Pauli matrix (NOT gate) and alpha is some real number
% The circuit goes C > CNOT > B > CNOT > A
%% Function that computes ABC decomposition of any unitary matrix U:
function [A, B, C, alpha, beta, gamma, delta] = decompose(U)
%Compute beta and delta first
function y = f(x)
global U
%x(1) is beta
%x(2) is delta
y(1) = exp(i*(x(1)+x(2)))-U(2,2)/U(1,1);
y(2) = exp(i*(x(1)-x(2)))+U(2,1)/U(1,2);
endfunction
%% MIGHT NEED TO ADJUST THE STARTING VALUES OF FSOLVE!
[x, info] = fsolve (@f, [pi,pi]);
%correcting for imaginary round off error
global beta = real(x(1));
global delta = real(x(2));
%Compute gamma
function y = f(x)
global delta
global U
%x(1) is gamma
%y(1) = cos(x(1)/2)+sin(x(1)/2)*exp(delta)*(-U(1,1)/U(1,2))
y(1) = U(2,2)*exp(-i*delta)*tan(x(1)/2)-U(2,1)
endfunction
%% MIGHT NEED TO ADJUST THE STARTING VALUES OF FSOLVE!
%not 100% sure about this one!
[x, info] = fsolve (@f, [0]);
global gamma = real(x);
% Finally, find alpha
function y = f(x)
global beta
global delta
global gamma
global U
%x(1) is alpha
y(1) = U(2,2)*exp(-i*(beta/2+delta/2))*1/(cos(gamma/2))-exp(i*x(1))
endfunction
%% MIGHT NEED TO ADJUST THE STARTING VALUES OF FSOLVE!
[x, info] = fsolve (@f, [pi]);
global alpha = real(x);
%Compute the A Matrix
theta_z = beta
theta_y = gamma/2
R_z = [exp(-i*theta_z/2) 0; 0 exp(i*theta_z/2)];
R_y = [cos(theta_y/2) -sin(theta_y/2); sin(theta_y/2) cos(theta_y/2)]
A = R_z*R_y;
%Compute the B Matrix
theta_z = -(delta+beta)/2
theta_y = -gamma/2
R_z = [exp(-i*theta_z/2) 0; 0 exp(i*theta_z/2)];
R_y = [cos(theta_y/2) -sin(theta_y/2); sin(theta_y/2) cos(theta_y/2)];
B = R_y*R_z;
%Compute the C Matrix
theta_z = (delta-beta)/2
R_z = [exp(-i*theta_z/2) 0; 0 exp(i*theta_z/2)];
C = R_z;
endfunction
|
github
|
markf94/QML_Thesis-master
|
ownnormdistr.m
|
.m
|
QML_Thesis-master/Octave/ownnormdistr.m
| 323 |
utf_8
|
304575e882204550698678db0124a4c0
|
%global sigma = 1
%global mu = 0
% Define function for normal distribution
function y = f (x)
%global sigma
%global mu
%sigma = 1
%mu = 0
y = 1/(1 .* sqrt(2 .*pi)).*exp(-(x).^2/(2));
%y = 1/(sigma .* sqrt(2 .*pi)).*exp(-(x-mu).^2/(2.*sigma.^2));
endfunction
%x=[-4:0.1:4];
%for i=0:3
myprob = f(1)
%endfor
%plot(x,myprob)
|
github
|
optisimon/ft5406-capacitive-touch-master
|
analyze_raw_data.m
|
.m
|
ft5406-capacitive-touch-master/analyze_raw_data.m
| 3,577 |
utf_8
|
c01b6592a3ecd2a39350e1fe8f415f08
|
%
% Process captures of raw capacitance values, and plot the mutual capacitance images.
%
% Assumes that the user previously
% 1) captured a number of background mutual capacitance images (with nothing on
% the touch screen):
% for var in $(seq 1 10) ; do ./dump_raw_data.sh > background_$var.raw ; done
%
% 2) Captured a number of forground mutual capacitance images:
% for var in $(seq 1 1000) ; do ./dump_raw_data.sh > frame_$var.raw ; done
%
% Will perform the following with that data
% 1) Calculate the average background intensity.
% 2) Normalize the intensities in each frame (individually) to fully span from
% black (lowest mutual capacitance) to white (highest mutual capacitance).
% 3) Plot the result, as well as save it to disk
%
%
% Original author Simon Gustafsson (www.optisimon.com)
%
% Copyright (c) 2016 Simon Gustafsson (www.optisimon.com)
%
% Do whatever you like with this code, but please refer to me as the original author.
%
page_screen_output(0)
% Background capacitance values
bg_files_unsorted = glob("background_*.raw");
% Foreground capacitance values
fg_files_unsorted = glob("frame_*.raw");
% Number of rows and columns in the capacitance matrix to use
w = 12
h = 22
% Assumes filenames named similar to "background_5.raw"
% (underscore before number, and dot after number)
function output = customNumericSort(input)
tmp = [];
for n = 1:size(input, 1)
fname = input{n};
numAsStr = strsplit(fname, {'_', '.' })(2){};
num = str2num(numAsStr);
tmp = [tmp; num];
end
[_, index] = sort(tmp);
for n = 1:size(input, 1)
output{n,1} = input{index(n)};
end
endfunction
bg_files = customNumericSort(bg_files_unsorted)
fg_files = customNumericSort(fg_files_unsorted)
%
% Read raw capacitance values from dump file.
%
% A dumpfile (generated by dump_raw_data.sh) contains a number of lines similar to this one:
% 0x2153 0x2114 0x2191 0x2195 0x20c7 0x2057 0x20b6 0x21c3 0x20ba 0x207c 0x2065 0x213d
%
function out = readRawData(filename)
f = fopen(filename, 'r');
out = [];
while (line = fgets(f)) ~= -1
data = sscanf(line, "%x")';
out = [ out; data];
endwhile
fclose(f);
endfunction
%
% Normalize in to span values between 0 and 1.
%
function out = normalize(in)
span = max(in(:)) - min(in(:));
out = (in - min(in(:))) ./span;
endfunction
%
% Average all the background samples
%
avg_bg = zeros(h, w);
for n = 1:size(bg_files, 1)
fname = bg_files{n};
X = readRawData(fname)(1:h, 1:w);
avg_bg = avg_bg + X;
end
avg_bg = avg_bg / size(bg_files,1)
%
% Blow up the size of the image (using nearest neighbor)
%
function out = expand(in, factor)
out = imresize(in, factor, 'nearest');
endfunction
%
% playback all the forground samples
%
global_max = -Inf;
global_min = Inf;
for n = 1:size(fg_files, 1)
fname = fg_files{n};
raw = readRawData(fname)(1:h, 1:w);
X = raw - avg_bg;
%
% Draw the capacitance image in a plot window
%
imagesc(X);
sleep(0.01);
global_max = max([global_max; X(:)]);
global_min = min([global_min; X(:)]);
% Normal way of normalizing each frame individually
img = normalize(X);
% Test normalizing all frames to the same amplitude
% (coefficients needs to have been determined in an earlier run)
%img = (X - (-163.83) + 0.01) / (386.44 - (-163.83) + 0.02);
%
% Save an up-scaled version of the capacitance image to disk.
%
out_fname = sprintf("out_%06d.png", n)
imwrite(expand(img, 32), out_fname)
end
% Print global max and min capacitance value (after background correction)
global_max
global_min
|
github
|
Rathcke/uni-master
|
projfilter.m
|
.m
|
uni-master/ad/AAD/SIP/ass5/src/projfilter.m
| 535 |
utf_8
|
715dd7bb0a74b77728560e652abda084
|
% The code below takes a matrix of projections and returns
% a matrix with filtered projections whose Fourier Transform
% is |w|. By uncommenting the vairous filters, various aspects
% of the reconstructed picture will be emphasized or lost.
function FIL = projfilter(Image)
[L,C]=size(Image);
w = [-pi : (2*pi)/L : pi-(2*pi)/L];
Filt = abs(sin(w));
% Below we use the Fourier Slice Theorem to filter the image
for i = 1:C,
IMG = fft(Image(:,i));
FiltIMG = IMG.*Filt';
FIL(:,i) = ifft(FiltIMG);
end
FIL = real(FIL);
|
github
|
Rathcke/uni-master
|
q3_4.m
|
.m
|
uni-master/ad/AAD/SIP/src/q3_4.m
| 197 |
utf_8
|
107c8c55b87184a43d4a545f32cb5f04
|
I = imread('hand.tiff');
zeros(size(I, 1), size(I, 2), 100)
for i = 1:100
subplot(1, 1, 1);
imshow(I);
end
function res = dsa(x, y, t)
t/(sqrt(2*pi*s^2))*1/(2*pi*(s^2+t^2))*exp(-x/(2*
end
|
github
|
Rathcke/uni-master
|
math412demo.m
|
.m
|
uni-master/optimization/ass1/src/math412demo.m
| 12,929 |
utf_8
|
6761f8a78b28bbc2e332db4bcc7df2ac
|
function [f,x] = math412demo(fname,method,LStype,info,acc,...
maxitns,LSlimit)
% WARNING: THIS CODE IS FOR DEMONSTRATING THE BASIC PROPERTIES OF
% VARIOUS ALGORITHM TYPES ONLY. USE AT OWN RISK.
% [bestf,x] = math412demo(fname, search_direction_type,
% line_search_method, info, accuracy, maxitns, LSlimit)
%
% eg [f,x] = math412demo('rosenbrock','N','BA',3,1e-5,30,45);
%
% The argument fname must contain the file name of the function to
% be minimized, inside single quotation marks. The function fname
% must be of the form [f] = fname(x); and return the initial point
% if x is not specified. The variable accuracy gives the stopping
% tolerance on the gradient estimate's norm. If accuracy < 0 it
% is replaced with 10^accuracy. maxitns and LSlimit give the number
% of iterations and number of function evaluations in a single line
% search at which the algorithm automatically stops.
% Choices of search_direction_type are: Steepest descent ('SD'),
% Newton ('N'), modified Newton ('MN'), and quasi-Newton ('QN'),
% Memoryless QN ('MQN'), and QN and MQN with initial diagonal
% scaling ('QND' and 'MQND'). MQN and MQND are implemented using
% matrices and are O(n) slower than vector only versions.
% Choices of line_search_method types are: Back-tracking Armijo ('BA'),
% forward- (and back-)tracking ('AF'), and Wolfe-Powell ('WP').
% The variable info gives the level of printout. If info < 0, its
% absolute value is used, and the algorithm pauses after each printout.
% If info =
% 0 print out nothing.
% 1 print out only at start and end.
% 2 print out after every iteration.
% 3 as for 2, but `H not PD using SD' means the Hessian is not positive
% definite, so the steepest descent direction has been used, and
% `adding mu.I to H' means that mu times the identity was added to the
% Hessian to make it positive definite. 'no QN update' means
% the BFGS update was abandoned due to loss of positive definiteness.
% INITIALIZATION
format compact;
if nargin < 2,
fprintf('FILE NAME OR METHOD NOT SPECIFIED: RUN ABANDONED \n'); return;
end;
if ~exist('LStype'), LStype = 'AF'; end;
if ~exist('info'), info = 1; end;
if info < 0, info = abs(info); printstop = 1; else printstop = 0; end;
if ~exist('acc'), acc = 0.00001; elseif acc < 0, acc = 10^acc; end;
if ~exist('LSlimit'), LSlimit = 45; end;
if ~exist('maxitns'),
switch method,
case {'N','MN'}, maxitns = 30;
case {'QN','MQN','QND','MQND','SD'}, maxitns = 150;
end;
end;
% STEP 1: Initialize the variables
stop = 0; itn = 0; nx = 1;
% get the initial point
no_x_0 = 0;
if ~exist('x'), x = feval(fname); no_x_0 = 1; end;
sizex = size(x); n = max(sizex); if sizex(2) > 1, x = x'; end;
% initialize the remaining variables.
g = zeros(n,1); oldg = g; p = zeros(n,1); oldp = p;
D = ones(n,1); h = 1e-6; mu = 0; QNabort = 0;
% evaluate the initial function value and gradient
f = feval(fname,x);
[g,nx,D,oldg,fp] = estimate_g(fname,method,x,h,n,f,g,D,nx);
% Do the initial printout.
initial_print(info,fname,method,LStype,n,maxitns,h,acc,f,no_x_0);
% Get the Cholesky factors of the Hessian or its estimate
switch method,
case {'N','MN'},
[HR,nx,mu] = get_HChol(fname,method,x,h,n,f,fp,D,nx,info,stop);
case 'SD', HR = 0;
case {'QN','MQN'}, HR = eye(n);
case {'QND','MQND'}, HR = diag( sqrt( max(1e-8,D)));
end;
while stop == 0, % MAIN LOOP
itn = itn+1;
% Calculate the new search direction
[p,oldp] = next_search_direction(p,g,oldg,D,HR,method);
% Do a line search
[x,f,nx,stop,alpha] = line_search(fname,LStype,x,f,p,g,LSlimit,nx,stop);
% Do the printout for this iteration.
if info >1,
iteration_print(f,g,itn,nx,alpha,p,mu,QNabort,printstop,info);
end;
% estimate gradient at the new iterate.
[g,nx,D,oldg,fp] = estimate_g(fname,method,x,h,n,f,g,D,nx);
% Check the stopping conditions and do end of iteration print
stop = check_stop(f,g,acc,itn,maxitns,info,stop);
% Calculate the upper triangular Cholesky factor of the Hessian.
switch method,
case {'N','MN'},
[HR,nx,mu] = get_HChol(fname,method,x,h,n,f,fp,D,nx,info,stop);
case {'QN','MQN','MQND','QND'},
[HR,QNabort] = update_HChol(fname,method,n,f,g,oldg,D,HR,p,alpha,info);
end;
end; % MAIN LOOP
% do the final printout.
final_print(fname,method,LStype,info,x,f,g,itn,nx,n);
switch method,
case {'MQN','MQND'},
fprintf('WARNING: MQN AND MQND IMPLEMENTED USING MATRICES\n');
end;
% --------------------------------------------------------------
function [stop] = check_stop(f,g,acc,itn,maxitns,info,stop);
% CHECK THE STOPPING CONDITIONS
if stop > 1, fprintf('\n HALT BECAUSE OF A LINE SEARCH FAILURE \n'); end;
if norm(g) < min(1,acc*(1+abs(f))),
if info > 0,
fprintf('\n HALT BECAUSE GRADIENT RESTRICTION SATISFIED: normg = %12.6g\n',norm(g));
end;
stop = 1;
elseif itn >= maxitns,
if info > 0,
fprintf('\n HALT BECAUSE MAXIMUM NUMBER OF ITERATIONS REACHED: normg = %12.6g\n',norm(g));
end;
stop = 1;
end;
% --------------------------------------------------------------
function [p,oldp] = next_search_direction(p,g,oldg,D,HR,method)
oldp = p;
switch method,
case 'SD', p = -g;
case {'QN','N','MN','MQN','MQND','QND'}
p = -HR \ ( HR' \ g );
end;
% --------------------------------------------------------------
function [g,nx,D,oldg,fp] = estimate_g(fname,method,x,h,n,f,g,D,nx)
% Calculating the gradient using central differences on a MAXIMAL frame
% aligned with the axes
xx = x; oldg = g; fp = zeros(n,1);
for ii=1:n,
incr = ( abs(xx(ii)) + 1)*h;
xx(ii) = xx(ii)+incr;
fplus = feval(fname,xx); fp(ii) = fplus;
xx(ii) = xx(ii)-2*incr;
fminus = feval(fname,xx);
xx(ii) = x(ii);
g(ii) = (fplus - fminus)/(2*incr);
D(ii) = (fplus + fminus - 2*f)/(incr*incr);
end;
nx = nx + 2*n;
return;
% ------------------------------------------------------------------
function [HR,nx,mu] = get_HChol(fname,method,x,h,n,f,fp,D,nx,info,stop)
% estimate the Hessian
HH = diag(D); mu = 0;
for ii = 1:n,
for jj = ii+1:n,
incii = ( abs(x(ii)) + 1)*h;
incjj = ( abs(x(jj)) + 1)*h;
xx = x; xx(ii) = x(ii) + incii; xx(jj) = x(jj) + incjj;
HH(ii,jj) = (feval(fname,xx) - fp(ii) - fp(jj) + f)/(incii*incjj);
HH(jj,ii) = HH(ii,jj);
end;
end;
% do not count function evaluations if stopping as HR not needed then.
if stop, HR = HH; return; else nx = nx + n*(n-1)/2; end;
% Cholesky factor the Hessian
[HR,notposdef] = chol(HH); % chol routine returns upper triangular factor.
if ~notposdef, return; end;
if method=='N',
mu = -2; HR = eye(n); % change to steepest descent direction.
else % method is MN
mu = 1;
while notposdef,
[HR,notposdef] = chol(HH + mu*eye(n));
if notposdef, mu = mu*4; end;
end;
end;
return;
% ------------------------------------------------------------------
function [HR,QNabort] = update_HChol(fname,method,n,f,g,oldg,D,HR,p,alpha,info)
% update the Cholesky factors of the estimate of the Hessian
switch method,
case 'MQN', HR = eye(n);
case 'MQND', HR = diag( sqrt( max(1e-8,D)));
end;
oldHR = HR; QNabort = 0;
y = g - oldg; s = alpha*p; yts = y'*s;
if yts <= 0, QNabort = 1; return; end;
% Add y y' / y's to B
vec = y/sqrt(yts); HR = cholupdate(HR,vec,'+');
% Now subtract (B s s' B) / (s' B s)
vec = oldHR*s; vec = (oldHR'*vec)/norm(vec);
[HR,QNabort] = cholupdate(HR,vec,'-');
if QNabort, HR = oldHR; end;
return;
% --------------------------------------------------------------
function [x,f,nx,stop,alpha] = line_search(fname,LStype,x,f,p,g,LSlimit,nx,stop)
rho = 1e-4; sigma = 0.9; lsnx = 0;
alphaa = 1; xa = x + alphaa*p;
fa = feval(fname,xa); lsnx = lsnx+1;
ptg = p'*g;
while fa >= f + rho*alphaa*ptg & ~stop,
fb = fa; xb = xa; alphab = alphaa;
alphaa = alphaa/2; xa = x + alphaa*p;
fa = feval(fname,xa); lsnx = lsnx+1;
if lsnx > LSlimit, stop = 2; end;
end; % of while
if LStype=='BA' | (LStype=='AF' & lsnx > 1),
x = xa; f = fa; alpha = alphaa; nx = nx + lsnx; return;
end;
if LStype=='AF' | (LStype=='WP' & lsnx < 2),
% lsnx<2 means alpha = 1 gave descent, so do forward tracking.
alphab = 4; xb = x + alphab*p;
fb = feval(fname,xb); lsnx = lsnx+1;
while fb < f+rho*alphab*ptg & lsnx<=LSlimit & (fb<fa | LStype=='WP'),
alphaa = alphab; fa = fb; xa = xb;
alphab = 4*alphab;
xb = x + alphab*p;
fb = feval(fname,xb); lsnx = lsnx+1;
end; % of while
end;
if LStype=='AF',
x = xa; f = fa; alpha = alphaa; nx = nx + lsnx; return;
end;
% only the WP line search should reach this point.
ptgalpha = get_ptg_at_alpha(fname,x,alphaa,p); lsnx = lsnx+2;
if ptgalpha >= sigma*ptg,
x = xa; f = fa; alpha = alphaa; nx = nx + lsnx; return;
end;
lscontinue = 1;
while lscontinue,
alphac = (alphaa + alphab)/2;
xc = x + alphac*p;
fc = feval(fname,xc); lsnx = lsnx + 1;
if fc >= f + rho*alphac*ptg,
alphab = alphac;
else
ptgalpha = get_ptg_at_alpha(fname,x,alphac,p);
lsnx = lsnx+2;
if ptgalpha >= sigma*ptg,
x = xc; f = fc; alpha = alphac;
nx = nx + lsnx; lscontinue = 0;
else
alphaa = alphac;
end;
end;
if lsnx > LSlimit,
stop = 2; lscontinue = 0; alpha = alphac; nx = nx + lsnx;
end;
end;
% --------------------------------------------------------------
function ptg_alpha = get_ptg_at_alpha(fname,x,alpha,p)
xplus = x + (1 + 1e-6)*alpha*p;
xminus = x + (1 - 1e-6)*alpha*p;
fplus = feval(fname,xplus); fminus = feval(fname,xminus);
ptg_alpha = (fplus - fminus)/(2e-6*alpha);
return;
% --------------------------------------------------------------
function iteration_print(f,g,itn,nx,alpha,p,mu,QNabort,printstop,info)
fprintf(' %9i %12.6g %12i',itn,f,nx);
fprintf(' %12.6g %12.6g %12.6g',norm(g),alpha,alpha*norm(p));
if info > 2 & mu > 0, fprintf(' Adding %8.2g.I to H',mu); end;
if info > 2 & mu < 0, fprintf(' H not PD: Use SD'); end;
if QNabort & info > 2, fprintf(' no QN update'); end;
fprintf(' \n');
if itn/30 == floor(itn/30),
fprintf('\n\n itn f value nr f evals ||g|| ');
fprintf(' alpha steplength\n\n');
end;
if printstop, pause; end;
% --------------------------------------------------------------
function initial_print(info,fname,method,LStype,n,maxitns,h,acc,f,no_x_0);
if info > 0,
fprintf(' ----------------------------------------------\n');
fprintf(' File name of function is %c%c%c%c%c%c%c%c%c%c%c%c%c%c ',fname);
fprintf('\n ----------------------------------------------\n\n');
end;
if info > 0,
if no_x_0,
fprintf('No initial point: using initial pt from function\n\n');
end;
fprintf(' number of variables = %9i \n',n);
fprintf(' maximum of %9i iterations \n',maxitns);
fprintf(' increment for gradient estimation = %12.4g \n',h);
fprintf(' requested termination accuracy = %8.4g \n',acc);
fprintf(' function value at initial point = %8.4g \n \n',f);
fprintf(' itn f value nr f evals ||g|| ');
fprintf(' alpha steplength \n');
end;
% --------------------------------------------------------------
function final_print(fname,method,LStype,info,x,f,g,itn,nx,n);
if info > 0,
fprintf('\n'); fprintf(' --------------- FINAL SUMMARY ------------------\n');
fprintf(' File name of function is: %c%c%c%c%c%c%c%c%c%c%c%c%c%c',fname);
fprintf(' \n');
fprintf('\n'); fprintf(' with function value %15.8g \n',f);
fprintf(' after %6i iterations and %6i function evaluations\n',itn,nx);
fprintf(' Magnitude of gradient at final iterate is %12.6g \n',norm(g));
if n < 7,
fprintf(' Current x = %8.4g ',x(1));
for ii = 2:n, fprintf(' %8.4g ',x(ii)); end;
end;
fprintf(' \n'); fprintf(' \n');
fprintf(' Method type: %c%c%c%c%c',method);
fprintf(' Line search type: %c%c',LStype);
fprintf('\n'); fprintf('\n');
end;
% -------------------------------------------------------------
function [f] = nzf1( x )
n = 13;
if ~exist('x'), f = ones( n, 1 ); return; end;
f = (3 * x(1) + 0.1 * ( x(2) - x(3) )^2 - 60)^2;
temp = x(2)^2 + x(3)^2 + x(4)^2 * ( 1 + x(4)^2 ) + x(7);
temp = temp + x(6) / ( 1 + x(5)^2 ) + sin( 0.001 * x(5) );
f = f + temp^2;
f = f + (x(7) + x(8)-x(9)^2 + x(11))^2;
f = f + (log( 1 + x(11)^2 ) + x(12) - 5 * x(13) + 20)^2;
f = f + (x(5) + x(6) + x(5) * x(6) + 10*x(10) - 50)^2;
|
github
|
Rathcke/uni-master
|
math412demo.m
|
.m
|
uni-master/optimization/ass2/src/math412demo.m
| 13,089 |
utf_8
|
8d18ad82cf948542ea25b06b3854c046
|
function [f,x] = math412demo(fname,method,LStype,info,acc,...
maxitns,LSlimit)
% WARNING: THIS CODE IS FOR DEMONSTRATING THE BASIC PROPERTIES OF
% VARIOUS ALGORITHM TYPES ONLY. USE AT OWN RISK.
% [bestf,x] = math412demo(fname, search_direction_type,
% line_search_method, info, accuracy, maxitns, LSlimit)
%
% eg [f,x] = math412demo('rosenbrock','N','BA',3,1e-5,30,45);
%
% The argument fname must contain the file name of the function to
% be minimized, inside single quotation marks. The function fname
% must be of the form [f] = fname(x); and return the initial point
% if x is not specified. The variable accuracy gives the stopping
% tolerance on the gradient estimate's norm. If accuracy < 0 it
% is replaced with 10^accuracy. maxitns and LSlimit give the number
% of iterations and number of function evaluations in a single line
% search at which the algorithm automatically stops.
% Choices of search_direction_type are: Steepest descent ('SD'),
% Newton ('N'), modified Newton ('MN'), and quasi-Newton ('QN'),
% Memoryless QN ('MQN'), and QN and MQN with initial diagonal
% scaling ('QND' and 'MQND'). MQN and MQND are implemented using
% matrices and are O(n) slower than vector only versions.
% Choices of line_search_method types are: Back-tracking Armijo ('BA'),
% forward- (and back-)tracking ('AF'), and Wolfe-Powell ('WP').
% The variable info gives the level of printout. If info < 0, its
% absolute value is used, and the algorithm pauses after each printout.
% If info =
% 0 print out nothing.
% 1 print out only at start and end.
% 2 print out after every iteration.
% 3 as for 2, but `H not PD using SD' means the Hessian is not positive
% definite, so the steepest descent direction has been used, and
% `adding mu.I to H' means that mu times the identity was added to the
% Hessian to make it positive definite. 'no QN update' means
% the BFGS update was abandoned due to loss of positive definiteness.
% INITIALIZATION
format compact;
if nargin < 2,
fprintf('FILE NAME OR METHOD NOT SPECIFIED: RUN ABANDONED \n'); return;
end;
if ~exist('LStype'), LStype = 'AF'; end;
format compact;
if nargin < 2,
fprintf('FILE NAME OR METHOD NOT SPECIFIED: RUN ABANDONED \n'); return;
end;
if ~exist('LStype'), LStype = 'AF'; end;N
if ~exist('info'), info = 1; end;
if info < 0, info = abs(info); printstop = 1; else printstop = 0; end;
if ~exist('acc'), acc = 0.00001; elseif acc < 0, acc = 10^acc; end;
if ~exist('LSlimit'), LSlimit = 45; end;
if ~exist('maxitns'),
switch method,
case {'N','MN'}, maxitns = 30;
case {'QN','MQN','QND','MQND','SD'}, maxitns = 150;
end;
end;
% STEP 1: Initialize the variables
stop = 0; itn = 0; nx = 1;
% get the initial point
no_x_0 = 0;
if ~exist('x'), x = feval(fname); no_x_0 = 1; end;
sizex = size(x); n = max(sizex); if sizex(2) > 1, x = x'; end;
% initialize the remaining variables.
g = zeros(n,1); oldg = g; p = zeros(n,1); oldp = p;
D = ones(n,1); h = 1e-6; mu = 0; QNabort = 0;
% evaluate the initial function value and gradient
f = feval(fname,x);
[g,nx,D,oldg,fp] = estimate_g(fname,method,x,h,n,f,g,D,nx);
% Do the initial printout.
initial_print(info,fname,method,LStype,n,maxitns,h,acc,f,no_x_0);
% Get the Cholesky factors of the Hessian or its estimate
switch method,
case {'N','MN'},
[HR,nx,mu] = get_HChol(fname,method,x,h,n,f,fp,D,nx,info,stop);
case 'SD', HR = 0;
case {'QN','MQN'}, HR = eye(n);
case {'QND','MQND'}, HR = diag( sqrt( max(1e-8,D)));
end;
while stop == 0, % MAIN LOOP
itn = itn+1;
% Calculate the new search direction
[p,oldp] = next_search_direction(p,g,oldg,D,HR,method);
% Do a line search
[x,f,nx,stop,alpha] = line_search(fname,LStype,x,f,p,g,LSlimit,nx,stop);
% Do the printout for this iteration.
if info >1,
iteration_print(f,g,itn,nx,alpha,p,mu,QNabort,printstop,info);
end;
% estimate gradient at the new iterate.
[g,nx,D,oldg,fp] = estimate_g(fname,method,x,h,n,f,g,D,nx);
% Check the stopping conditions and do end of iteration print
stop = check_stop(f,g,acc,itn,maxitns,info,stop);
% Calculate the upper triangular Cholesky factor of the Hessian.
switch method,
case {'N','MN'},
[HR,nx,mu] = get_HChol(fname,method,x,h,n,f,fp,D,nx,info,stop);
case {'QN','MQN','MQND','QND'},
[HR,QNabort] = update_HChol(fname,method,n,f,g,oldg,D,HR,p,alpha,info);
end;
end; % MAIN LOOP
% do the final printout.
final_print(fname,method,LStype,info,x,f,g,itn,nx,n);
switch method,
case {'MQN','MQND'},
fprintf('WARNING: MQN AND MQND IMPLEMENTED USING MATRICES\n');
end;
% --------------------------------------------------------------
function [stop] = check_stop(f,g,acc,itn,maxitns,info,stop);
% CHECK THE STOPPING CONDITIONS
if stop > 1, fprintf('\n HALT BECAUSE OF A LINE SEARCH FAILURE \n'); end;
if norm(g) < min(1,acc*(1+abs(f))),
if info > 0,
fprintf('\n HALT BECAUSE GRADIENT RESTRICTION SATISFIED: normg = %12.6g\n',norm(g));
end;
stop = 1;
elseif itn >= maxitns,
if info > 0,
fprintf('\n HALT BECAUSE MAXIMUM NUMBER OF ITERATIONS REACHED: normg = %12.6g\n',norm(g));
end;
stop = 1;
end;
% --------------------------------------------------------------
function [p,oldp] = next_search_direction(p,g,oldg,D,HR,method)
oldp = p;
switch method,
case 'SD', p = -g;
case {'QN','N','MN','MQN','MQND','QND'}
p = -HR \ ( HR' \ g );
end;
% --------------------------------------------------------------
function [g,nx,D,oldg,fp] = estimate_g(fname,method,x,h,n,f,g,D,nx)
% Calculating the gradient using central differences on a MAXIMAL frame
% aligned with the axes
xx = x; oldg = g; fp = zeros(n,1);
for ii=1:n,
incr = ( abs(xx(ii)) + 1)*h;
xx(ii) = xx(ii)+incr;
fplus = feval(fname,xx); fp(ii) = fplus;
xx(ii) = xx(ii)-2*incr;
fminus = feval(fname,xx);
xx(ii) = x(ii);
g(ii) = (fplus - fminus)/(2*incr);
D(ii) = (fplus + fminus - 2*f)/(incr*incr);
end;
nx = nx + 2*n;
return;
% ------------------------------------------------------------------
function [HR,nx,mu] = get_HChol(fname,method,x,h,n,f,fp,D,nx,info,stop)
% estimate the Hessian
HH = diag(D); mu = 0;
for ii = 1:n,
for jj = ii+1:n,
incii = ( abs(x(ii)) + 1)*h;
incjj = ( abs(x(jj)) + 1)*h;
xx = x; xx(ii) = x(ii) + incii; xx(jj) = x(jj) + incjj;
HH(ii,jj) = (feval(fname,xx) - fp(ii) - fp(jj) + f)/(incii*incjj);
HH(jj,ii) = HH(ii,jj);
end;
end;
% do not count function evaluations if stopping as HR not needed then.
if stop, HR = HH; return; else nx = nx + n*(n-1)/2; end;
% Cholesky factor the Hessian
[HR,notposdef] = chol(HH); % chol routine returns upper triangular factor.
if ~notposdef, return; end;
if method=='N',
mu = -2; HR = eye(n); % change to steepest descent direction.
else % method is MN
mu = 1;
while notposdef,
[HR,notposdef] = chol(HH + mu*eye(n));
if notposdef, mu = mu*4; end;
end;
end;
return;
% ------------------------------------------------------------------
function [HR,QNabort] = update_HChol(fname,method,n,f,g,oldg,D,HR,p,alpha,info)
% update the Cholesky factors of the estimate of the Hessian
switch method,
case 'MQN', HR = eye(n);
case 'MQND', HR = diag( sqrt( max(1e-8,D)));
end;
oldHR = HR; QNabort = 0;
y = g - oldg; s = alpha*p; yts = y'*s;
if yts <= 0, QNabort = 1; return; end;
% Add y y' / y's to B
vec = y/sqrt(yts); HR = cholupdate(HR,vec,'+');
% Now subtract (B s s' B) / (s' B s)
vec = oldHR*s; vec = (oldHR'*vec)/norm(vec);
[HR,QNabort] = cholupdate(HR,vec,'-');
if QNabort, HR = oldHR; end;
return;
% --------------------------------------------------------------
function [x,f,nx,stop,alpha] = line_search(fname,LStype,x,f,p,g,LSlimit,nx,stop)
rho = 1e-4; sigma = 0.9; lsnx = 0;
alphaa = 1; xa = x + alphaa*p;
fa = feval(fname,xa); lsnx = lsnx+1;
ptg = p'*g;
while fa >= f + rho*alphaa*ptg & ~stop,
fb = fa; xb = xa; alphab = alphaa;
alphaa = alphaa/2; xa = x + alphaa*p;
fa = feval(fname,xa); lsnx = lsnx+1;
if lsnx > LSlimit, stop = 2; end;
end; % of while
if LStype=='BA' | (LStype=='AF' & lsnx > 1),
x = xa; f = fa; alpha = alphaa; nx = nx + lsnx; return;
end;
if LStype=='AF' | (LStype=='WP' & lsnx < 2),
% lsnx<2 means alpha = 1 gave descent, so do forward tracking.
alphab = 4; xb = x + alphab*p;
fb = feval(fname,xb); lsnx = lsnx+1;
while fb < f+rho*alphab*ptg & lsnx<=LSlimit & (fb<fa | LStype=='WP'),
alphaa = alphab; fa = fb; xa = xb;
alphab = 4*alphab;
xb = x + alphab*p;
fb = feval(fname,xb); lsnx = lsnx+1;
end; % of while
end;
if LStype=='AF',
x = xa; f = fa; alpha = alphaa; nx = nx + lsnx; return;
end;
% only the WP line search should reach this point.
ptgalpha = get_ptg_at_alpha(fname,x,alphaa,p); lsnx = lsnx+2;
if ptgalpha >= sigma*ptg,
x = xa; f = fa; alpha = alphaa; nx = nx + lsnx; return;
end;
lscontinue = 1;
while lscontinue,
alphac = (alphaa + alphab)/2;
xc = x + alphac*p;
fc = feval(fname,xc); lsnx = lsnx + 1;
if fc >= f + rho*alphac*ptg,
alphab = alphac;
else
ptgalpha = get_ptg_at_alpha(fname,x,alphac,p);
lsnx = lsnx+2;
if ptgalpha >= sigma*ptg,
x = xc; f = fc; alpha = alphac;
nx = nx + lsnx; lscontinue = 0;
else
alphaa = alphac;
end;
end;
if lsnx > LSlimit,
stop = 2; lscontinue = 0; alpha = alphac; nx = nx + lsnx;
end;
end;
% --------------------------------------------------------------
function ptg_alpha = get_ptg_at_alpha(fname,x,alpha,p)
xplus = x + (1 + 1e-6)*alpha*p;
xminus = x + (1 - 1e-6)*alpha*p;
fplus = feval(fname,xplus); fminus = feval(fname,xminus);
ptg_alpha = (fplus - fminus)/(2e-6*alpha);
return;
% --------------------------------------------------------------
function iteration_print(f,g,itn,nx,alpha,p,mu,QNabort,printstop,info)
fprintf(' %9i %12.6g %12i',itn,f,nx);
fprintf(' %12.6g %12.6g %12.6g',norm(g),alpha,alpha*norm(p));
if info > 2 & mu > 0, fprintf(' Adding %8.2g.I to H',mu); end;
if info > 2 & mu < 0, fprintf(' H not PD: Use SD'); end;
if QNabort & info > 2, fprintf(' no QN update'); end;
fprintf(' \n');
if itn/30 == floor(itn/30),
fprintf('\n\n itn f value nr f evals ||g|| ');
fprintf(' alpha steplength \n\n');
end;
if printstop, pause; end;
% --------------------------------------------------------------
function initial_print(info,fname,method,LStype,n,maxitns,h,acc,f,no_x_0);
if info > 0,
fprintf(' ----------------------------------------------\n');
fprintf(' File name of function is %c%c%c%c%c%c%c%c%c%c%c%c%c%c ',fname);
fprintf('\n ----------------------------------------------\n\n');
end;
if info > 0,
if no_x_0,
fprintf('No initial point: using initial pt from function\n\n');
end;
fprintf(' number of variables = %9i \n',n);
fprintf(' maximum of %9i iterations \n',maxitns);
fprintf(' increment for gradient estimation = %12.4g \n',h);
fprintf(' requested termination accuracy = %8.4g \n',acc);
fprintf(' function value at initial point = %8.4g \n \n',f);
fprintf(' itn f value nr f evals ||g|| ');
fprintf(' alpha steplength \n');
end;
% --------------------------------------------------------------
function final_print(fname,method,LStype,info,x,f,g,itn,nx,n);
if info > 0,
fprintf('\n'); fprintf(' --------------- FINAL SUMMARY ------------------\n');
fprintf(' File name of function is: %c%c%c%c%c%c%c%c%c%c%c%c%c%c',fname);
fprintf(' \n');
fprintf('\n'); fprintf(' with function value %15.8g \n',f);
fprintf(' after %6i iterations and %6i function evaluations\n',itn,nx);
fprintf(' Magnitude of gradient at final iterate is %12.6g \n',norm(g));
if n < 7,
fprintf(' Current x = %8.4g ',x(1));
for ii = 2:n, fprintf(' %8.4g ',x(ii)); end;
end;
fprintf(' \n'); fprintf(' \n');
fprintf(' Method type: %c%c%c%c%c',method);
fprintf(' Line search type: %c%c',LStype);
fprintf('\n'); fprintf('\n');
end;
% -------------------------------------------------------------
function [f] = nzf1( x )
n = 13;
if ~exist('x'), f = ones( n, 1 ); return; end;
f = (3 * x(1) + 0.1 * ( x(2) - x(3) )^2 - 60)^2;
temp = x(2)^2 + x(3)^2 + x(4)^2 * ( 1 + x(4)^2 ) + x(7);
temp = temp + x(6) / ( 1 + x(5)^2 ) + sin( 0.001 * x(5) );
f = f + temp^2;
f = f + (x(7) + x(8)-x(9)^2 + x(11))^2;
f = f + (log( 1 + x(11)^2 ) + x(12) - 5 * x(13) + 20)^2;
f = f + (x(5) + x(6) + x(5) * x(6) + 10*x(10) - 50)^2;
|
github
|
Rathcke/uni-master
|
q2_4.m
|
.m
|
uni-master/sip/ass3/src/q2_4.m
| 316 |
utf_8
|
c531e726ae2dad95ce674f3c1ae9b300
|
function q2_4()
for i = 1:6
res = scale((i-1)*3+1);
subplot(2, 3, i);
imshow(res);
title(sprintf('With sigma = %d', (i-1)*3+1));
end
end
function res = scale(arg)
I = imread('lena.tiff');
h = fspecial('gaussian', [arg arg], arg);
res = imfilter(I, h);
end
|
github
|
Rathcke/uni-master
|
q2_2.m
|
.m
|
uni-master/sip/ass3/src/q2_2.m
| 2,682 |
utf_8
|
ed9165b054f9d4749be6fc2984655dbc
|
function q2_2()
%q2_2a()
%q2_2b()
q2_2c()
end
function q2_2a()
I = imread('lena.tiff');
h = fspecial('gaussian');
A = nestedConv(h, I);
B = fourConv(h, I);
subplot(1, 3, 1);
imagesc(I);
colormap gray;
title('Original image');
subplot(1, 3, 2);
imagesc(A);
colormap gray;
title('Image after convolution');
subplot(1, 3, 3);
imagesc(B);
colormap gray;
title('Image after convolution using FFT');
end
function q2_2b()
I = imread('lena.tiff');
fst = [];
snd = [];
for i = 1:7
h = fspecial('gaussian', [i*2+1 i*2+1]);
tic;
A = nestedConv(h, I);
fst(i) = toc;
tic
B = fourConv(h, I);
snd(i) = toc;
end
subplot(1, 1, 1);
plot([3:2:15], fst, [3:2:15], snd);
xlabel('Window size in n*n');
ylabel('Computation time in seconds');
title('Nested for-loop convolution vs. convolution using FFT');
end
function q2_2c()
I = imread('lena.tiff');
fst = [];
snd = [];
for i = 1:10
h = fspecial('gaussian');
I2 = imresize(I, i/10);
tic;
A = nestedConv(h, I2);
fst(i) = toc;
tic
B = fourConv(h, I2);
snd(i) = toc;
end
subplot(1, 1, 1);
plot([0.1:0.1:1], fst, [0.1:0.1:1], snd);
xlabel('Image size in scale = n/10');
ylabel('Computation time in seconds');
title('Nested for-loop convolution vs. convolution using FFT');
end
function res = nestedConv(ker, img)
x = size(img, 1);
y = size(img, 2);
x2 = size(ker, 1);
y2 = size(ker, 2);
x3 = fix(x2/2);
y3 = fix(y2/2);
res = zeros(x, y);
for i = 1:x
for j = 1:y
acc = 0;
for k = -x3:x3
for l = -y3:y3
if (i+k > 0 && i+k < x)
if (j+l > 0 && j+l < y)
acc = acc + ker(k+x3+1, l+y3+1) * img(i+k, j+l);
else
acc = acc + ker(k+x3+1, l+y3+1) * img(i+k, j-l);
end
elseif (j+l > 0 && j+l < y)
acc = acc + ker(k+x3+1, l+y3+1) * img(i-k, j+l);
else
acc = acc + ker(k+x3+1, l+y3+1) * img(i-k, j-l);
end
end
end
res(i, j) = acc;
end
end
end
function res = fourConv(ker, img)
cumSize = size(img) + size(ker) - 1;
img(cumSize(1), cumSize(2)) = 0;
ker(cumSize(1), cumSize(2)) = 0;
res = ifft2(fft2(img).*fft2(ker));
end
|
github
|
Rathcke/uni-master
|
q2_3.m
|
.m
|
uni-master/sip/ass3/src/q2_3.m
| 850 |
utf_8
|
08a7a6fbb57427610672bdd8eeea1461
|
function q2_3()
I = imread('lena.tiff');
I2 = addFunc(I, 50, 0.25, 0.25);
subplot(2,2,1);
imshow(I);
title('Original image');
colormap gray;
subplot(2,2,2);
imshow(I2);
title('Image with added function');
colormap gray;
ps = 10*log10(fftshift(abs(fft2(I2)).^2));
subplot(2,2,3);
imagesc(ps);
title('Power Spectrum of modified image');
colormap gray;
ps = fftshift(fft2(I2));
ps(105, 105) = 0;
ps(123, 123) = 0;
subplot(2,2,4);
imagesc(abs(real(ifft2(ps))));
title('Image after removing cosine noise');
colormap gray;
end
function res = addFunc(img, a, v, w)
x = size(img, 1);
y = size(img, 2);
for i = 1:x
for j = 1:y
res(i, j) = img(i, j) + a*cos(v*i+w*j);
end
end
end
|
github
|
Rathcke/uni-master
|
q2_6.m
|
.m
|
uni-master/sip/ass3/src/q2_6.m
| 534 |
utf_8
|
1dcd1970ffdcab5ea4550620c5cc68d6
|
function q2_6()
I = imread('lena.tiff');
for i = 0:2
for j = 0:2
A = deriveImg(I, i, j);
subplot(3, 3, 3*i+j+1);
imagesc(A);
colormap gray;
title(sprintf('With n = %d and m = %d', i, j));
end
end
end
function res = deriveImg(img, n, m)
ft = fft2(img);
x = size(ft, 1);
y = size(ft, 2);
for i = 1:x
for j = 1:x
ftd(i, j)= (1j * i).^n *(1j * j).^m * ft(i, j);
end
end
res = real(ifft2(ftd));
end
|
github
|
Rathcke/uni-master
|
SVM_soft.m
|
.m
|
uni-master/dataAnalysis/afl6/code/SVM_soft.m
| 1,011 |
utf_8
|
8f4c7fd36aa1ffa4d511447f87cd15ce
|
% N is number of datapoints
% X is data in rows
% Y is labels in a column
% C is a number
function u = SVM_soft(X, Y, C)
% Get the datasample dimension
[N, d]=size(X);
% p: a column of N 0's followed by N C/N's
p = [zeros(d+1,1); (C/N)*ones(N,1)];
% c: a column of N 1's followed by N 0's
c = [ones(N,1); zeros(N,1)];
% Q is a (d+N+1)x(d+N+1) matrix with a dxd identity matrix in entry 2x2
Q = zeros(N+d+1,N+d+1);
Q(2:d+1,2:d+1) = eye(d);
% A: first a 2N x (d+N+1) matrix of 0's
A = zeros(2*N, d+N+1);
% The vector of labels
A(1:N,1) = Y;
% YX: labels multiplied by data matrix with a column of 1's to the left
A(1:N,2:d+1) = (Y * ones(1, d)) .* X;
% NIden: a NxN Identity matrix
NIden = eye(N);
% NIden is inserted to the right in A
% both in the right top and bottom right corner
% of A
A(1:N,d+2:d+N+1) = NIden;
A(N+1:2*N,d+2:d+N+1) = NIden;
u = quadprog(Q,p,-A,-c);
end
|
github
|
zhuhan1236/dhn-caffe-master
|
prepare_batch.m
|
.m
|
dhn-caffe-master/matlab/caffe/prepare_batch.m
| 1,298 |
utf_8
|
68088231982895c248aef25b4886eab0
|
% ------------------------------------------------------------------------
function images = prepare_batch(image_files,IMAGE_MEAN,batch_size)
% ------------------------------------------------------------------------
if nargin < 2
d = load('ilsvrc_2012_mean');
IMAGE_MEAN = d.image_mean;
end
num_images = length(image_files);
if nargin < 3
batch_size = num_images;
end
IMAGE_DIM = 256;
CROPPED_DIM = 227;
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
center = floor(indices(2) / 2)+1;
num_images = length(image_files);
images = zeros(CROPPED_DIM,CROPPED_DIM,3,batch_size,'single');
parfor i=1:num_images
% read file
fprintf('%c Preparing %s\n',13,image_files{i});
try
im = imread(image_files{i});
% resize to fixed input size
im = single(im);
im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% Transform GRAY to RGB
if size(im,3) == 1
im = cat(3,im,im,im);
end
% permute from RGB to BGR (IMAGE_MEAN is already BGR)
im = im(:,:,[3 2 1]) - IMAGE_MEAN;
% Crop the center of the image
images(:,:,:,i) = permute(im(center:center+CROPPED_DIM-1,...
center:center+CROPPED_DIM-1,:),[2 1 3]);
catch
warning('Problems with file',image_files{i});
end
end
|
github
|
zhuhan1236/dhn-caffe-master
|
matcaffe_demo_vgg.m
|
.m
|
dhn-caffe-master/matlab/caffe/matcaffe_demo_vgg.m
| 3,036 |
utf_8
|
f836eefad26027ac1be6e24421b59543
|
function scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file)
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file)
%
% Demo of the matlab wrapper using the networks described in the BMVC-2014 paper "Return of the Devil in the Details: Delving Deep into Convolutional Nets"
%
% INPUT
% im - color image as uint8 HxWx3
% use_gpu - 1 to use the GPU, 0 to use the CPU
% model_def_file - network configuration (.prototxt file)
% model_file - network weights (.caffemodel file)
% mean_file - mean BGR image as uint8 HxWx3 (.mat file)
%
% OUTPUT
% scores 1000-dimensional ILSVRC score vector
%
% EXAMPLE USAGE
% model_def_file = 'zoo/VGG_CNN_F_deploy.prototxt';
% model_file = 'zoo/VGG_CNN_F.caffemodel';
% mean_file = 'zoo/VGG_mean.mat';
% use_gpu = true;
% im = imread('../../examples/images/cat.jpg');
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file);
%
% NOTES
% the image crops are prepared as described in the paper (the aspect ratio is preserved)
%
% PREREQUISITES
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% init caffe network (spews logging info)
matcaffe_init(use_gpu, model_def_file, model_file);
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im, mean_file)};
toc;
% do forward pass to get scores
% scores are now Width x Height x Channels x Num
tic;
scores = caffe('forward', input_data);
toc;
scores = scores{1};
% size(scores)
scores = squeeze(scores);
% scores = mean(scores,2);
% [~,maxlabel] = max(scores);
% ------------------------------------------------------------------------
function images = prepare_image(im, mean_file)
% ------------------------------------------------------------------------
IMAGE_DIM = 256;
CROPPED_DIM = 224;
d = load(mean_file);
IMAGE_MEAN = d.image_mean;
% resize to fixed input size
im = single(im);
if size(im, 1) < size(im, 2)
im = imresize(im, [IMAGE_DIM NaN]);
else
im = imresize(im, [NaN IMAGE_DIM]);
end
% RGB -> BGR
im = im(:, :, [3 2 1]);
% oversample (4 corners, center, and their x-axis flips)
images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices_y = [0 size(im,1)-CROPPED_DIM] + 1;
indices_x = [0 size(im,2)-CROPPED_DIM] + 1;
center_y = floor(indices_y(2) / 2)+1;
center_x = floor(indices_x(2) / 2)+1;
curr = 1;
for i = indices_y
for j = indices_x
images(:, :, :, curr) = ...
permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :)-IMAGE_MEAN, [2 1 3]);
images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);
curr = curr + 1;
end
end
images(:,:,:,5) = ...
permute(im(center_y:center_y+CROPPED_DIM-1,center_x:center_x+CROPPED_DIM-1,:)-IMAGE_MEAN, ...
[2 1 3]);
images(:,:,:,10) = images(end:-1:1, :, :, curr);
|
github
|
zhuhan1236/dhn-caffe-master
|
matcaffe_demo.m
|
.m
|
dhn-caffe-master/matlab/caffe/matcaffe_demo.m
| 3,344 |
utf_8
|
669622769508a684210d164ac749a614
|
function [scores, maxlabel] = matcaffe_demo(im, use_gpu)
% scores = matcaffe_demo(im, use_gpu)
%
% Demo of the matlab wrapper using the ILSVRC network.
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = matcaffe_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab for putting image data into the correct
% format:
% % convert from uint8 to single
% im = single(im);
% % reshape to a fixed size (e.g., 227x227)
% im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % permute from RGB to BGR and subtract the data mean (already in BGR)
% im = im(:,:,[3 2 1]) - data_mean;
% % flip width and height to make width the fastest dimension
% im = permute(im, [2 1 3]);
% If you have multiple images, cat them with cat(4, ...)
% The actual forward function. It takes in a cell array of 4-D arrays as
% input and outputs a cell array.
% init caffe network (spews logging info)
if exist('use_gpu', 'var')
matcaffe_init(use_gpu);
else
matcaffe_init();
end
if nargin < 1
% For demo purposes we will use the peppers image
im = imread('peppers.png');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Width x Height x Channels x Num
tic;
scores = caffe('forward', input_data);
toc;
scores = scores{1};
size(scores)
scores = squeeze(scores);
scores = mean(scores,2);
[~,maxlabel] = max(scores);
% ------------------------------------------------------------------------
function images = prepare_image(im)
% ------------------------------------------------------------------------
d = load('ilsvrc_2012_mean');
IMAGE_MEAN = d.image_mean;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% resize to fixed input size
im = single(im);
im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% permute from RGB to BGR (IMAGE_MEAN is already BGR)
im = im(:,:,[3 2 1]) - IMAGE_MEAN;
% oversample (4 corners, center, and their x-axis flips)
images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
curr = 1;
for i = indices
for j = indices
images(:, :, :, curr) = ...
permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :), [2 1 3]);
images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);
curr = curr + 1;
end
end
center = floor(indices(2) / 2)+1;
images(:,:,:,5) = ...
permute(im(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:), ...
[2 1 3]);
images(:,:,:,10) = images(end:-1:1, :, :, curr);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.