Commit 971def62 authored by Hamed Nili's avatar Hamed Nili
Browse files

first commit

parents
function cols=RDMcolormap
% this function provides a convenient colormap for visualizing
% dissimilarity matrices. it goes from blue to yellow and has grey for
% intermediate values.
%__________________________________________________________________________
% Copyright (C) 2012 Medical Research Council
import rsa.*
import rsa.fig.*
import rsa.fmri.*
import rsa.rdm.*
import rsa.sim.*
import rsa.spm.*
import rsa.stat.*
import rsa.util.*
nCols = 256;
%% blue-cyan-gray-red-yellow with increasing V (BCGRYincV)
anchorCols=[0 0 1
0 1 1
.5 .5 .5
1 0 0
1 1 0];
anchorCols_hsv=rgb2hsv(anchorCols);
incVweight=1;
anchorCols_hsv(:,3)=(1-incVweight)*anchorCols_hsv(:,3)+incVweight*linspace(0.5,1,size(anchorCols,1))';
brightness(anchorCols);
anchorCols=hsv2rgb(anchorCols_hsv);
cols=colorScale(anchorCols,nCols);
cols1=cols;
% figure(1); colormap(cols);
% cm=colormap; hsvcm=rgb2hsv(cm);
% subplot(3,1,3); cla; plot(brightness(colormap),'r'); hold on; plot(hsvcm(:,3),'k'); axis tight; legend({'brightness','V'});
% th=addHeading('blue-cyan-gray-red-yellow with increasing V');
end%function
% this function adds the pairwise copmparison bars to a figure; the 'hold on'
% should have been set before executing this function
% pairWisePs: an nxn pairwise comparison matrix. This is supposed to be
% sorted in descending order of average values (large to small heights)
% a horizontal bar would be displayed whenever the (one-sided) comparison
% reaches a threshold.
% HN, May 2013
%__________________________________________________________________________
% Copyright (C) 2012 Medical Research Council
function y = addComparisonBars(pairwisePs,cYMax,threshold)
import rsa.*
import rsa.fig.*
import rsa.rdm.*
import rsa.stat.*
import rsa.util.*
nTestRDMs = size(pairwisePs,1);
eachLineHeight = 0.03;
padding = 2;
% Set `y` here in case no comparisons are significant.
y = cYMax;
nSignificantComparison = 0;
pairwiseI = 0;
for i = 1:nTestRDMs
for j = i+1:nTestRDMs
% The p value for i (the lower bar) being significantly smaller than j (the higher bar) is the p value for j being significantly higher than i. This is pairwisePs(j,i) (the lt?)
thisPairwiseP = pairwisePs(i,j);
if thisPairwiseP <= threshold
y = cYMax;
pairwiseI = pairwiseI + 1;
xx = [i j];
y = y + (cYMax * eachLineHeight * padding / 2); %padding
y = y + (pairwiseI * eachLineHeight * cYMax); %line separation
yy = [y y];
line(xx, yy, 'LineStyle', '-', 'LineWidth', 2, 'Marker', 'none', 'Color', [0 0 0]);
nSignificantComparison = nSignificantComparison + 1;
end%if
end%for:j
end%for:i
end%function
function addHeading(heading,figI,x,y)
% adds a heading to a figure. The user also has the option of specifying
% the location of the inserted heading text.
import rsa.*
import rsa.fig.*
import rsa.fmri.*
import rsa.rdm.*
import rsa.sim.*
import rsa.spm.*
import rsa.stat.*
import rsa.util.*
% replace underscores
if iscell(heading)
for lineI=1:numel(heading)
line=heading{lineI};
line(line==95)='-';
heading{lineI}=line;
end
else
heading(heading==95)='-';
end
if ~exist('figI','var')
newFigure = gcf;
figI=newFigure.Number;
end
pageFigure(figI);
if ~exist('x','var'), x=1.11; end
if ~exist('y','var'), y=1.08; end
h=axes('Parent',gcf); hold on;
set(h,'Visible','off');
axis([0 1 0 1]);
% add heading(s)
text(x,y,heading,'HorizontalAlignment','Right','VerticalAlignment','Top','FontSize',12,'FontWeight','bold','Color','k');
end%function
function addImageSequenceToAxes(ax,il)
% USAGE
% addImageSequenceToAxes(ax,imagelabels)
% FUNCTION
% places a set of images at equal distances along a line in a 2d
% coordinate system, which is then mapped to the axes of the RDM
% in ax. imagelabels is a struct with the following fields:
% images : struct containing
% image : RGB image matrix (x,y,3)
% alpha: optional alpha layer for image
% sequence : vector of custom indices for images. Optional.
% nRows : number of rows/columns to plot labels in. Default 2.
% transparentCol : Remove background based on rgb colour. Default undefined.
% blackdisks : Logical. Place black disks under images. Default false.
% Default parameters
% In principle the only default we can't set is il.images
% transparentCol is left out here
%__________________________________________________________________________
% Copyright (C) 2010 Medical Research Council
import rsa.*
import rsa.fig.*
import rsa.fmri.*
import rsa.rdm.*
import rsa.sim.*
import rsa.spm.*
import rsa.stat.*
import rsa.util.*
defaultil = struct('sequence',1:length(il.images),'nRows',2, ...
'blackdisks',false);
for fn = fieldnames(defaultil)'
if ~isfield(il,fn{1})
il.(fn{1}) = defaultil.(fn{1});
end
end
nImagesInSeq=numel(il.sequence);
% Get axes
axes(ax);
da_orig = daspect;
set(ax,'layer','bottom');
xlim=get(gca,'XLim');
ylim=get(gca,'YLim');
% figure out how large the plotted RDM is
% rdmlen = length(get(min(get(ax,'children')),'cdata'));
% The RDMs get plotted with a .5 offset
offset = .5;
% Offset in Z to make lines reliably appear behind faces
% Doesn't actually do anything (?)
offset_z = 500;
% Padding the axes slightly at the end helps with images clipping outside the frame
padding = 1.05;
% Add space to X and Y to make room for labels
set(ax,'xlim',[xlim(1) - il.nRows xlim(2)]);
set(ax,'ylim',[ylim(1) - il.nRows ylim(2)]);
% Get updated values
xlim=get(gca,'XLim');
ylim=get(gca,'YLim');
% Place in the space we've created
start_xy_c{1} = [xlim(1)-1 ylim(2)-offset];
end_xy_c{1} = [xlim(1)-1 ylim(1)+il.nRows+offset];
start_xy_c{2} = [xlim(2)-offset ylim(1)+1];
end_xy_c{2} = [xlim(1)+il.nRows+offset ylim(1)+1];
% Making these changes tends to mess up the axes slightly..
daspect(da_orig);
da=daspect; % need this to render image pixels square
set(gca,'XTick',[]); % switch off horizontal-axis ticks and image index numbers
hold on;
% DIMENSION
for dim = 1:2
start_xy = start_xy_c{dim};
end_xy = end_xy_c{dim};
%daspect(daspect);
% looks moot, but causes the current data aspect ratio to be preserved when the figure is resized
%% compute image size
% images assumed to be square
seqVec_sqA=(end_xy-start_xy)./da(1:2); % vector in il.sequence direction (in square axis)
imageWidth=max(abs(seqVec_sqA))/(nImagesInSeq-1)*il.nRows;
imW_ax=imageWidth*da(1);
imW_ay=imageWidth*da(2);
%% prepare multi-row arrangement
% compute vector orthogonal to il.sequence direction
orthVec=-(null(seqVec_sqA)'*imageWidth).*da(1:2);
% shift start and end positions to center the multiple rows on the
% requested il.sequence line
% start_xy=start_xy-orthVec*(il.nRows-1)/2;
% end_xy=end_xy-orthVec*(il.nRows-1)/2;
%% arrange the images
for sequenceI=1:nImagesInSeq
imageI=il.sequence(sequenceI);
xy=start_xy+(end_xy-start_xy)/(nImagesInSeq-1)*(sequenceI-1);
xy=xy+mod(sequenceI,il.nRows)*orthVec; % lateral displacement for multiple rows
%[xs,ys,rgb3]=size(il.images(imageI).image); % assuming square images for now, so this isn't needed
% If there is a transparency column, use it
% If there is also an alpha channel, use that too
% If there is nothing, just use whatever we have..
st = size(il.images(imageI).image(:,:,1));
% If there is a colour that should be made transparent
if exist('il.transparentCol','var')
transparent=il.images(imageI).image(:,:,1)==il.transparentCol(1) & il.images(imageI).image(:,:,2)==il.transparentCol(2) & il.images(imageI).image(:,:,3)==il.transparentCol(3);
else
% Once again, assuming square stimuli...
transparent = logical(zeros(st(1),st(2)));
end
% If we have an alpha layer
if isfield(il.images(imageI),'alpha')
alpha = il.images(imageI).alpha == 0;
else
alpha = logical(zeros(st(1),st(2)));
end
% Merge colour and alpha layers
transparentalpha = (transparent + alpha) > 0;
% black disks underneath
% TODO: Make these actually work
if il.blackdisks
angles=0:0.1:2*pi;
X=sin(angles)*imW_ax/2+xy(1);
Y=cos(angles)*imW_ay/2+xy(2);
Z=-2*ones(size(X));
patch(X,Y,Z,[0 0 0]);
end
%rectangle('Position',[xy(1)-imW_ax/2 xy(2)-imW_ay/2 imW_ax imW_ay],'Curvature',[1 1],'FaceColor','k','EdgeColor','none','EraseMode','normal');
%plot(xy(1),xy(2),'o','MarkerSize',10,'MarkerFaceColor','k');
% Tick line
switch dim
case 1
tick_y = repmat(mean(xy(2)+[imW_ay/2, -imW_ay/2]),2,1);
tick_x = [mean(xy(1)+[imW_ax/2, -imW_ax/2]) .5];
case 2
tick_x = repmat(mean(xy(1)+[imW_ax/2, -imW_ax/2]),2,1);
tick_y = [mean(xy(2)+[imW_ay/2, -imW_ay/2]) .5];
end
pl(dim).x(:,sequenceI) = tick_x;
pl(dim).y(:,sequenceI) = tick_y;
pl(dim).z(:,sequenceI) = [offset_z offset_z];
% low-level version of image function
imh(sequenceI) = image('CData',flipdim(il.images(imageI).image,1),'XData',xy(1)+[-imW_ax/2, imW_ax/2],'YData',xy(2)+[imW_ay/2, -imW_ay/2],'AlphaData',~flipdim(transparentalpha,1),'EraseMode','normal');
% high-level version of image function
% image(xy(1)+[-imW_ax/2, imW_ax/2],xy(2)+[imW_ay/2, -imW_ay/2],il.images(imageI).image,'AlphaData',~transparentalpha,'EraseMode','normal');
xlim(1)=min(xlim(1),xy(1)-imW_ax/2);
xlim(2)=max(xlim(2),xy(1)+imW_ax/2);
ylim(1)=min(ylim(1),xy(2)-imW_ay/2);
ylim(2)=max(ylim(2),xy(2)+imW_ay/2);
end
set(gca, 'XLim',xlim, 'YLim',ylim);
end
%switch dim
%case 1
%pl(dim).x(:,end+1) = [offset offset];
%pl(dim).y(:,end+1) = [start_xy(2)+offset end_xy(2)-offset];
%pl(dim).z(:,end+1) = [offset_z offset_z];
%case 2
%pl(dim).x(:,end+1) = [start_xy(1)+offset end_xy(1)-offset];
%pl(dim).y(:,end+1) = [offset offset];
%pl(dim).z(:,end+1) = [offset_z offset_z];
%end
%start_xy = start_xy_c{dim};
% Add a main supporting line
main.x = [start_xy_c{2}(1)+offset end_xy_c{2}(1)-offset offset offset];
main.y = [offset offset start_xy_c{1}(2)+offset end_xy_c{1}(2)-offset];
main.z = [offset_z offset_z offset_z offset_z];
% Plot all the tick lines in one go
l = line([pl(1).x pl(2).x],[pl(1).y pl(2).y],[pl(1).z pl(2).z]);
set(l,'color','k','linewidth',1);
uistack(l,'bottom');
% And the main supporting line
lmain = line(main.x,main.y,main.z);
set(lmain,'color','k','linewidth',1);
uistack(lmain,'bottom');
% Add a little bit of padding
oldx = get(ax,'xlim');
oldy = get(ax,'ylim');
set(ax,'xlim',oldx * padding);
set(ax,'ylim',oldy * padding);
end%function
function cols=colorScale(anchorCols,nCols,monitor)
% linearly interpolates between a set of given 'anchor' colours to give
% nCols and displays them if monitor is set
%__________________________________________________________________________
% Copyright (C) 2012 Medical Research Council
import rsa.*
import rsa.fig.*
import rsa.fmri.*
import rsa.rdm.*
import rsa.sim.*
import rsa.spm.*
import rsa.stat.*
import rsa.util.*
%% preparations
if ~exist('monitor','var'), monitor=false; end
%% define color scale
nAnchors=size(anchorCols,1);
cols = interp1((1:nAnchors)',anchorCols,linspace(1,nAnchors,nCols));
%% visualise
if monitor
figure(123); clf;
imagesc(reshape(cols,[nCols 1 3]));
end
end%function
function exportCurrentFigAsPDF(filespec,userOptions)
% exports the current figures to the file [filespec,'.pdf'] in pdf
% format.
% filespec is the full path (including the file name) of the file to be
% saved.
% userOptions can be used to modify the dots per inch (dpi) or the
% tightness of the figure in the printed page.
%__________________________________________________________________________
% Copyright (C) 2009 Medical Research Council
import rsa.*
import rsa.fig.*
import rsa.fmri.*
import rsa.rdm.*
import rsa.sim.*
import rsa.spm.*
import rsa.stat.*
import rsa.util.*
if ~isfield(userOptions,'dpi'), userOptions.dpi = 300; end;
if ~isfield(userOptions,'tightInset'), userOptions.tightInset = false; end;
% If we are trimming the paper size to match the figure
if userOptions.tightInset
setPapertoFigPos;
end
appendFlag = 0;
switch appendFlag
case 0
print('-dpdf',sprintf('-r%d',userOptions.dpi),filespec);
case 1
print('-dpdf',sprintf('-r%d',userOptions.dpi),'-append',filespec);
case 3
print('-dpdf',sprintf('-r%d',userOptions.dpi),[filespec,'_',num2str(gcf)]);
print('-dpdf',sprintf('-r%d',userOptions.dpi),'-append',filespec);
end
end%function
function exportCurrentFigAsPostscript(filespec,appendFlag,userOptions)
% exports the current figures to the file [filespec,'.ps'] in postscript
% format. if appendFlag is 0 any existing file [filespec,'.ps'] is
% overwritten. if appendFlag is 1 the figure is appended to the existing
% postscript file [filespec,'.ps']. if appendFlag is 3 (default) the figure
% is appended to the existing postscript file [filespec,'.ps'] and exported
% to a separate file [filespec,'_',num2str(gcf),'.ps'].
%
% exportCurrentFigAsPostscript(filespec,appendFlag,userOptions)
%__________________________________________________________________________
% Copyright (C) 2010 Medical Research Council
import rsa.*
import rsa.fig.*
import rsa.fmri.*
import rsa.rdm.*
import rsa.sim.*
import rsa.spm.*
import rsa.stat.*
import rsa.util.*
if ~exist('filespec','var'), filespec='currentFigAsPostscript'; end;
if ~exist('appendFlag','var'), appendFlag=1; end;
if ~isfield(userOptions,'dpi'), userOptions.dpi = 300; end;
if ~isfield(userOptions,'tightInset'), userOptions.tightInset = false; end;
% If we are trimming the paper size to match the figure
if userOptions.tightInset
setPapertoFigPos;
end
switch appendFlag
case 0
print('-dpsc2',sprintf('-r%d',userOptions.dpi),filespec);
case 1
print('-dpsc2',sprintf('-r%d',userOptions.dpi),'-append',filespec);
case 3
print('-dpsc2',sprintf('-r%d',userOptions.dpi),[filespec,'_',num2str(gcf)]);
print('-dpsc2',sprintf('-r%d',userOptions.dpi),'-append',filespec);
case 4
print('-dpsc2',sprintf('-r%d',userOptions.dpi),filespec);
print('-dpsc2',sprintf('-r%d',userOptions.dpi),'-append','^ALL_POSTSCRIPTS_appendFlag4');
end
end%function
function exportfig(varargin)
%EXPORTFIG Export a figure to Encapsulated Postscript.
% EXPORTFIG(H, FILENAME) writes the figure H to FILENAME. H is
% a figure handle and FILENAME is a string that specifies the
% name of the output file.
%
% EXPORTFIG(...,PARAM1,VAL1,PARAM2,VAL2,...) specifies
% parameters that control various characteristics of the output
% file.
%
% Format Paramter:
% 'Format' one of the strings 'eps','eps2','jpeg','png','preview'
% specifies the output format. Defaults to 'eps'.
% The output format 'preview' does not generate an output
% file but instead creates a new figure window with a
% preview of the exported figure. In this case the
% FILENAME parameter is ignored.
%
% 'Preview' one of the strings 'none', 'tiff'
% specifies a preview for EPS files. Defaults to 'none'.
%
% Size Parameters:
% 'Width' a positive scalar
% specifies the width in the figure's PaperUnits
% 'Height' a positive scalar
% specifies the height in the figure's PaperUnits
%
% Specifying only one dimension sets the other dimension
% so that the exported aspect ratio is the same as the
% figure's current aspect ratio.
% If neither dimension is specified the size defaults to
% the width and height from the figure's PaperPosition.
%
% Rendering Parameters:
% 'Color' one of the strings 'bw', 'gray', 'cmyk'
% 'bw' specifies that lines and text are exported in
% black and all other objects in grayscale
% 'gray' specifies that all objects are exported in grayscale
% 'cmyk' specifies that all objects are exported in color
% using the CMYK color space
% 'Renderer' one of the strings 'painters', 'zbuffer', 'opengl'
% specifies the renderer to use
% 'Resolution' a positive scalar
% specifies the resolution in dots-per-inch.
%
% The default color setting is 'bw'.
%
% Font Parameters:
% 'FontMode' one of the strings 'scaled', 'fixed'
% 'FontSize' a positive scalar
% in 'scaled' mode multiplies with the font size of each
% text object to obtain the exported font size
% in 'fixed' mode specifies the font size of all text
% objects in points
% 'FontEncoding' one of the strings 'latin1', 'adobe'
% specifies the character encoding of the font
%
% If FontMode is 'scaled' but FontSize is not specified then a
% scaling factor is computed from the ratio of the size of the
% exported figure to the size of the actual figure. The minimum
% font size allowed after scaling is 5 points.
% If FontMode is 'fixed' but FontSize is not specified then the
% exported font sizes of all text objects is 7 points.
%
% The default 'FontMode' setting is 'scaled'.
%
% Line Width Parameters:
% 'LineMode' one of the strings 'scaled', 'fixed'
% 'LineWidth' a positive scalar
% the semantics of LineMode and LineWidth are exactly the
% same as FontMode and FontSize, except that they apply
% to line widths instead of font sizes. The minumum line
% width allowed after scaling is 0.5 points.
% If LineMode is 'fixed' but LineWidth is not specified
% then the exported line width of all line objects is 1
% point.
%
% Examples:
% exportfig(gcf,'fig1.eps','height',3);
% Exports the current figure to the file named 'fig1.eps' with
% a height of 3 inches (assuming the figure's PaperUnits is
% inches) and an aspect ratio the same as the figure's aspect
% ratio on screen.
%
% exportfig(gcf, 'fig2.eps', 'FontMode', 'fixed',...
% 'FontSize', 10, 'color', 'cmyk' );
% Exports the current figure to 'fig2.eps' in color with all
% text in 10 point fonts. The size of the exported figure is
% the figure's PaperPostion width and height.
import rsa.*
import rsa.fig.*
import rsa.fmri.*
import rsa.rdm.*
import rsa.sim.*
import rsa.spm.*
import rsa.stat.*
import rsa.util.*
if (nargin < 2)
error('Too few input arguments');
end
% exportfig(H, filename, ...)
H = varargin{1};
if ~ishandle(H) | ~strcmp(get(H,'type'), 'figure')
error('First argument must be a handle to a figure.');
end
filename = varargin{2};
if ~ischar(filename)
error('Second argument must be a string.');
end
paramPairs = varargin(3:end);
% Do some validity checking on param-value pairs
if (rem(length(paramPairs),2) ~= 0)
error(['Invalid input syntax. Optional parameters and values' ...
' must be in pairs.']);
end
format = 'eps';
preview = 'none';
width = -1;
height = -1;
color = 'bw';
fontsize = -1;
fontmode='scaled';
linewidth = -1;
linemode=[];