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
|
zhehedream/UAV-Path-Optimization-master
|
Get_Point_Cluster.m
|
.m
|
UAV-Path-Optimization-master/sub/Get_Point_Cluster.m
| 985 |
utf_8
|
c87a022c3541eda8931d80b99dfb7655
|
% Get_Point_Cluster
% Get Point sets which each point (p0) in this set meets
% the condition with other points (px) that Euclidean_distance(p0,px)<distance
%
% Input: A
% point vector that has the coordinates of all the points
% Input: distance
% Output: point_cluster
function point_cluster=Get_Point_Cluster(A,distance)
n=size(A,1);
V=1:1:n;
point_cluster=cell(10000,1);
num=0;
DIS=zeros(n,n);
for i=1:n
for j=1:n
DIS(i,j)=sqrt((A(i,1)-A(j,1))^2+(A(i,2)-A(j,2))^2);
end
end
for i=2:n
tmp=nchoosek(V,i);
for j=1:size(tmp,1)
tmp2=tmp(j,:);
f=1;
for k=1:i-1
if f==0
break;
end
for l=k+1:i
if DIS(tmp2(k),tmp2(l))>distance
f=0;
break;
end
end
end
if f==1
num=num+1;
point_cluster{num,1}=tmp2;
end
end
end
point_cluster=point_cluster(1:num,:);
|
github
|
zhehedream/UAV-Path-Optimization-master
|
Show_Result.m
|
.m
|
UAV-Path-Optimization-master/sub/Show_Result.m
| 337 |
utf_8
|
c17a98ffb5f6b879f54eae1febc2a224
|
% Show_Result
% Input: str
% Message on MessageBox
function Show_Result(str)
h=msgbox(str);
th = findall(0, 'Tag','MessageBox' );
boxPosition = get(h,'position');
textPosition = get(th, 'position');
set(th, 'position', [boxPosition(3).*0.5 textPosition(2) textPosition(3)]);
set(th, 'HorizontalAlignment', 'center');
|
github
|
zhehedream/UAV-Path-Optimization-master
|
Draw_Station.m
|
.m
|
UAV-Path-Optimization-master/sub/Draw_Station.m
| 354 |
utf_8
|
c9ce117454b3d96871c766e8f16d508a
|
% Draw_Station
% Input: fig_id
% The figure id of the window you want to overly
% Input: Station
% The data matrix of Station
function Draw_Station(fig_id,Station)
figure(fig_id);
for i=1:length(Station)
if Station(i,3)==0
plot(Station(i,1),Station(i,2),'rx');
else
plot(Station(i,1),Station(i,2),'ro');
end
end
|
github
|
zhehedream/UAV-Path-Optimization-master
|
Get_Plane_Point_After_Road.m
|
.m
|
UAV-Path-Optimization-master/sub/Get_Plane_Point_After_Road.m
| 940 |
utf_8
|
8adf2e993be0a730d561678e25a3da37
|
% Get_Plane_Point_After_Road
% Get the coordinate of plane after it travels through point in t with
% speed
%
% Input: point
% points vector of Road
% Input: t_limit
% time limit
% Input: speed
% Output: x, y
% plane coordinate after traveling
% (x & y==1000) means cannot finish in t_limit
% Output: n
% retardation points amount
function [x,y,n]=Get_Plane_Point_After_Road(point,t_limit,speed)
n=1;
while t_limit>0
n=n+1;
if n>size(point,1)
x=-1000;
y=-1000;
break;
end
dt=sqrt((point(n,1)-point(n-1,1))^2+(point(n,2)-point(n-1,2))^2)/speed;
if t_limit-dt>0
t_limit=t_limit-dt;
else
ll=speed*t_limit;
xx=point(n,1)-point(n-1,1);
yy=point(n,2)-point(n-1,2);
mm=sqrt(xx^2+yy^2);
xe=xx/mm*ll;
ye=yy/mm*ll;
x=xe+point(n-1,1);
y=ye+point(n-1,2);
t_limit=-1;
end
end
n=n-1;
|
github
|
zhehedream/UAV-Path-Optimization-master
|
Calc_Rad_Destroy.m
|
.m
|
UAV-Path-Optimization-master/sub/Calc_Rad_Destroy.m
| 834 |
utf_8
|
555d90692ef2abce735ce68065288008
|
function [result,p]=Calc_Rad_Destroy(point,n,rp)
point_tmp={};
min_rd=1e12;
min_p=[];
for i=1:size(point,1)
point_tmp=[point_tmp;Get_Circle_Point(point(i,1),point(i,2),30,n)];
end
point_index_list=Get_NL(n,size(point,1));
for i=1:size(point_index_list,1)
temp=[];
for j=1:size(point_index_list,2)
index=point_index_list(i,j);
temp_list=point_tmp{j};
x=temp_list(index,1);
y=temp_list(index,2);
temp=[temp;x y];
end
[rd,~]=Get_Plane_Time(temp,rp);
if rd<min_rd
min_rd=rd;
min_p=temp;
end
end
p=min_p;
result=min_rd;
function result=Get_NL(n,l)
if l==1
result=1:1:n;
result=result';
else
result_tmp=Get_NL(n,l-1);
result=[];
for i=1:n
tmp=[ones(size(result_tmp,1),1)*i result_tmp];
result=[result;tmp];
end
end
|
github
|
zhehedream/UAV-Path-Optimization-master
|
Get_Circle_Point.m
|
.m
|
UAV-Path-Optimization-master/sub/Get_Circle_Point.m
| 482 |
utf_8
|
68db6bee1c4e0f9cb36ed345c5144463
|
% Get_Circle_Point
% Get (point coordinate) * n on Circle(x,y,r)
% Input: x,y
% Center coordinate
% Input: r
% Radius
% Output: point
% matrix of point coordinates on Circle
%
% Example:
% >>Get_Circle_Point(0,0,1,3)
% ans =
% 1.0000 0
% -0.5000 0.8660
% -0.5000 -0.8660
function point=Get_Circle_Point(x,y,r,n)
st=2*pi/n;
dt=0;
point=[];
while dt<2*pi
dx=r*cos(dt)+x;
dy=r*sin(dt)+y;
point=[point;dx dy];
dt=dt+st;
end
|
github
|
zhehedream/UAV-Path-Optimization-master
|
Get_Total_Dist.m
|
.m
|
UAV-Path-Optimization-master/sub/Get_Total_Dist.m
| 229 |
utf_8
|
2fe733178a53d8bea91de1a450b33d4d
|
% Get_Total_Dist
% Get the total traveling distance through point
function result=Get_Total_Dist(point)
n=size(point,1);
result=0;
for i=1:n-1
result=result+sqrt((point(i,1)-point(i+1,1))^2+(point(i,2)-point(i+1,2))^2);
end
|
github
|
zhehedream/UAV-Path-Optimization-master
|
Circle.m
|
.m
|
UAV-Path-Optimization-master/sub/Circle.m
| 317 |
utf_8
|
b00cb510af2f78c479f2aef5f568f0f3
|
% Circle
% Draw a circle as you want
% Input: fig_num
% The figure id of the window you want to overly
% Input: R
% radius
% Input: rx, ry
% center coordinate
function Circle(fig_num,R,rx,ry)
figure(fig_num);
alpha=0:pi/50:2*pi;
x=R*cos(alpha)+rx;
y=R*sin(alpha)+ry;
plot(x,y,'r-')
axis equal
|
github
|
zhehedream/UAV-Path-Optimization-master
|
Get_Group_Dist.m
|
.m
|
UAV-Path-Optimization-master/sub/Get_Group_Dist.m
| 308 |
utf_8
|
84aff7c6f1baba3e1a171b3cfc37a056
|
% Get_Group_Dist
% Get the Distance_Matrix of group A
function group_dist=Get_Group_Dist(A)
n=size(A,1);
group_dist=zeros(n,n);
for i=1:n
for j=1:n
if i==j
group_dist(i,j)=0;
else
group_dist(i,j)=sqrt((A(i,1)-A(j,1))^2+(A(i,2)-A(j,2))^2);
end
end
end
|
github
|
zhehedream/UAV-Path-Optimization-master
|
Get_Plane_Time.m
|
.m
|
UAV-Path-Optimization-master/sub/Get_Plane_Time.m
| 717 |
utf_8
|
d5ade61a7777be49a120e84b76f2a0ad
|
% Get_Plane_Time
% Input: point
% Coordinate of start station
% Input: rp
% Coordinates of radars
% Output: total_time
% Output: rad_time
% total time that plane is in radar scale
function [rad_time,total_time]=Get_Plane_Time(point,rp)
time_t=0;
step=0.01;
dd=30/720;
rt=0;
rad_time=0;
%while ~is_my_empty(rp)
while find(rp+1000~=0)
time_t=time_t+step;
[x,y,n]=Get_Plane_Point_After_Road(point,time_t,300);
if x==-1000
break;
end
if rp(n,1)~=1000
rt=rt+step;
if rt>=dd
rt=0;
rp(n,:)=[-1000 -1000];
end
end
if Is_Plane_In_Radar(rp,[x y],70)==1
rad_time=rad_time+step;
end
end
total_time=time_t;
|
github
|
JaneliaSciComp/JRCLUST-main
|
jrc.m
|
.m
|
JRCLUST-main/jrc.m
| 4,939 |
utf_8
|
41e344ea661891ce9fdd12a80a9fa36a
|
% JRCLUST v4
% Alan Liddell, Vidrio Technologies
% Originally written by James Jun
function hJRC_ = jrc(varargin)
%JRC
if nargout > 0
hJRC_ = [];
end
if nargin < 1
disp(jrclust.utils.help()); % later: GUI
return;
end
% discard try-catch here for now as these messages are next to useless
hJRC = JRC(varargin{:});
if hJRC.inProgress()
hJRC.hCfg.verbose = 1; % invocation from command line is always verbose
hJRC.run();
end
if hJRC.isError
error(hJRC.errMsg);
end
if nargout > 0
hJRC_ = hJRC;
elseif ~isempty(hJRC.res) && hJRC.hCfg.exportResults % export results to workspace
jrclust.utils.exportToWorkspace(struct('res', hJRC.res), 0);
end
return;
end
%%
% case 'import-tsf'
% import_tsf_(vcArg1);
%
% case 'import-h5'
% import_h5_(vcArg1);
%
% case 'import-intan'
% vcFile_prm_ = import_intan_(vcArg1, vcArg2, vcArg3);
% return;
%
% case {'import-nsx', 'import-ns5'}
% vcFile_prm_ = import_nsx_(vcArg1, vcArg2, vcArg3);
% return;
%
% case 'nsx-info'
% [~, ~, S_file] = nsx_info_(vcArg1);
% assignWorkspace_(S_file);
% return;
%
% case 'load-nsx'
% load_nsx_(vcArg1);
% return;
%
% case 'import-gt'
% import_gt_silico_(vcArg1);
%
% case 'unit-test'
% unit_test_(vcArg1);
%
% case 'test'
% varargout{1} = test_(vcArg1, vcArg2, vcArg3, vcArg4, vcArg5);
%
% case {'make-trial', 'maketrial', 'load-trial', 'loadtrial'}
% make_trial_(vcFile_prm, 0);
%
% case {'loadtrial-imec', 'load-trial-imec', 'make-trial-imec', 'maketrial-imec'}
% make_trial_(vcFile_prm, 1);
%
% case 'batch'
% batch_(vcArg1, vcArg2);
%
% case {'batch-verify', 'batch-validate'}
% batch_verify_(vcArg1, vcArg2);
%
% case {'batch-plot', 'batch-activity'}
% batch_plot_(vcArg1, vcArg2);
%
% case 'describe'
% describe_(vcFile_prm);
%
% case {'import-kilosort', 'import-ksort'}
% import_ksort_(vcFile_prm);
%
% case 'import-silico'
% import_silico_(vcFile_prm, 0);
%
% case 'import-silico-sort'
% import_silico_(vcFile_prm, 1);
%
% case 'export-imec-sync'
% export_imec_sync_(vcFile_prm);
%
% case 'export-prm'
% export_prm_(vcFile_prm, vcArg2);
%
% case 'preview-test'
% preview_(P, 1);
% gui_test_(P, 'Fig_preview');
%
% case 'traces-lfp'
% traces_lfp_(P)
%
% case 'traces-test'
% traces_(P);
% traces_test_(P);
%
% case 'manual-test'
% manual_(P, 'debug');
% manual_test_(P);
% return;
%
% case 'manual-test-menu'
% manual_(P, 'debug');
% manual_test_(P, 'Menu');
% return;
%
% case 'export-spk'
% S0 = get(0, 'UserData');
% trSpkWav = jrclust.utils.readBin(jrclust.utils.subsExt(P.vcFile_prm, '_spkwav.jrc'), 'int16', S0.dimm_spk);
% assignWorkspace_(trSpkWav);
%
% case 'export-raw'
% S0 = get(0, 'UserData');
% trWav_raw = jrclust.utils.readBin(jrclust.utils.subsExt(P.vcFile_prm, '_spkraw.jrc'), 'int16', S0.dimm_spk);
% assignWorkspace_(trWav_raw);
%
% case {'export-spkwav', 'spkwav'}
% export_spkwav_(P, vcArg2); % export spike waveforms
%
% case {'export-chan'}
% export_chan_(P, vcArg2); % export channels
%
% case {'export-car'}
% export_car_(P, vcArg2); % export common average reference
%
% case {'export-spkwav-diff', 'spkwav-diff'}
% export_spkwav_(P, vcArg2, 1); % export spike waveforms
%
% case 'export-spkamp'
% export_spkamp_(P, vcArg2); %export microvolt unit
%
% case {'export-csv', 'exportcsv'}
% export_csv_(P);
%
% case {'export-quality', 'exportquality', 'quality'}
% export_quality_(P);
%
% case {'export-csv-msort', 'exportcsv-msort'}
% export_csv_msort_(P);
%
% case {'export-fet', 'export-features', 'export-feature'}
% export_fet_(P);
%
% case 'export-diff'
% export_diff_(P); %spatial differentiation for two column probe
%
% case 'import-lfp'
% import_lfp_(P);
%
% case 'export-lfp'
% export_lfp_(P);
%
% case 'drift'
% plot_drift_(P);
%
% case 'plot-rd'
% plot_rd_(P);
%
% if contains_(lower(vcCmd), {'verify', 'validate'})
% if ~is_detected_(P)
% detect_(P);
% end
% if ~is_sorted_(P)
% sort_(P);
% end
% validate_(P);
% elseif contains_(lower(vcCmd), {'filter'})
% TWfilter_(P);
% elseif fError
% help_();
% end
|
github
|
JaneliaSciComp/JRCLUST-main
|
computeDelta.m
|
.m
|
JRCLUST-main/+jrclust/+sort/computeDelta.m
| 5,692 |
utf_8
|
31d6b7ec2f2a77c4b7904396922feda7
|
function res = computeDelta(dRes, res, hCfg)
%COMPUTEDELTA Compute delta for spike features
hCfg.updateLog('computeDelta', 'Computing delta', 1, 0);
% create CUDA kernel
chunkSize = 16;
nC_max = 45;
if hCfg.useGPU
ptxFile = fullfile(jrclust.utils.basedir(), '+jrclust', '+CUDA', 'jrc_cuda_delta.ptx');
cuFile = fullfile(jrclust.utils.basedir(), '+jrclust', '+CUDA', 'jrc_cuda_delta.cu');
deltaCK = parallel.gpu.CUDAKernel(ptxFile, cuFile);
deltaCK.ThreadBlockSize = [hCfg.nThreadsGPU, 1];
deltaCK.SharedMemorySize = 4 * chunkSize * (3 + nC_max + 2*hCfg.nThreadsGPU);
else
deltaCK = [] ;
end
spikeData = struct('spikeTimes', dRes.spikeTimes);
for iSite = 1:hCfg.nSites
if isfield(dRes, 'spikesBySite')
spikeData.spikes1 = dRes.spikesBySite{iSite};
else
spikeData.spikes1 = dRes.spikeSites(dRes.spikeSites==iSite);
end
if isfield(dRes, 'spikesBySite2') && ~isempty(dRes.spikesBySite2)
spikeData.spikes2 = dRes.spikesBySite2{iSite};
elseif isfield(dRes, 'spikeSites2')
spikeData.spikes2 = dRes.spikeSites2(dRes.spikeSites2==iSite);
end
if isfield(dRes, 'spikesBySite3') && ~isempty(dRes.spikesBySite3)
spikeData.spikes3 = dRes.spikesBySite3{iSite};
elseif isfield(dRes, 'spikeSites3')
spikeData.spikes3 = dRes.spikeSites3(dRes.spikeSites3==iSite);
end
[siteFeatures, spikes, n1, n2, spikeOrder] = jrclust.features.getSiteFeatures(dRes.spikeFeatures, iSite, spikeData, hCfg);
if hCfg.useGPU
deltaCK.GridSize = [ceil(n1/chunkSize^2), chunkSize]; % MaxGridSize: [2.1475e+09 65535 65535]
end
if isempty(siteFeatures)
continue;
end
rhoOrder = jrclust.utils.rankorder(res.spikeRho(spikes), 'descend');
siteFeatures = jrclust.utils.tryGpuArray(siteFeatures, hCfg.useGPU);
rhoOrder = jrclust.utils.tryGpuArray(rhoOrder, hCfg.useGPU);
spikeOrder = jrclust.utils.tryGpuArray(spikeOrder, hCfg.useGPU);
try
[siteDelta, siteNN] = computeDeltaSite(siteFeatures, spikeOrder, rhoOrder, n1, n2, res.rhoCutSite(iSite), deltaCK, hCfg);
[siteDelta, siteNN] = jrclust.utils.tryGather(siteDelta, siteNN);
catch ME % can't continue!
error('Error at site %d: %s', iSite, ME.message);
end
res.spikeDelta(spikeData.spikes1) = siteDelta;
res.spikeNeigh(spikeData.spikes1) = spikes(siteNN);
[siteFeatures, rhoOrder, spikeOrder] = jrclust.utils.tryGather(siteFeatures, rhoOrder, spikeOrder); %#ok<ASGLU>
hCfg.updateLog('deltaSite', sprintf('Site %d: median delta: %0.5f (%d spikes)', iSite, median(siteDelta), n1), 0, 0);
end
% set delta for spikes with no nearest neighbor of higher density to
% maximum distance, ensure they don't get grouped into another cluster
nanDelta = find(isnan(res.spikeDelta));
if ~isempty(nanDelta)
res.spikeDelta(nanDelta) = max(res.spikeDelta);
end
hCfg.updateLog('computeDelta', 'Finished computing delta', 0, 1);
end
%% LOCALFUNCTIONS
function [delta, nNeigh] = computeDeltaSite(siteFeatures, spikeOrder, rhoOrder, n1, n2, distCut2, deltaCK, hCfg)
%COMPUTEDELTASITE Compute site-wise delta for spike features
[nC, n12] = size(siteFeatures); % nc is constant with the loop
dn_max = int32(round((n1 + n2) / hCfg.nClusterIntervals));
if hCfg.useGPU
try
% set every time function is called
delta = zeros([1, n1], 'single', 'gpuArray');
nNeigh = zeros([1, n1], 'uint32', 'gpuArray');
consts = int32([n1, n12, nC, dn_max, hCfg.getOr('fDc_spk', 0)]);
[delta, nNeigh] = feval(deltaCK, delta, nNeigh, siteFeatures, spikeOrder, rhoOrder, consts, distCut2);
return;
catch ME
warning('CUDA kernel failed: %s', ME.message);
end
end
rhoOrderN1 = rhoOrder(1:n1)';
spikeOrderN1 = spikeOrder(1:n1)';
% we can quickly run out of space here, ensure this doesn't happen
availMem = 2^33; % 8 GiB
if jrclust.utils.typeBytes(class(spikeOrder))*n1*n12 > availMem
stepSize = floor(availMem/n12/jrclust.utils.typeBytes(class(spikeOrder)));
delta = zeros(1, n1, 'single');
nNeigh = zeros(1, n1, 'uint32');
for iChunk = 1:stepSize:n1
iRange = iChunk:min(iChunk+stepSize-1, n1);
% find spikes with a larger rho and are nearby enough in time
isDenserChunk = bsxfun(@lt, rhoOrder, rhoOrderN1(iRange));
nearbyTimeChunk = abs(bsxfun(@minus, spikeOrder, spikeOrderN1(iRange))) <= dn_max;
distsChunk = pdist2(siteFeatures', siteFeatures(:, iRange)', 'squaredeuclidean');
distsChunk(~(isDenserChunk & nearbyTimeChunk)) = nan;
distsChunk = sqrt(distsChunk/distCut2); % normalize
[delta(iRange), nNeigh(iRange)] = min(distsChunk);
end
else
dists = pdist2(siteFeatures', siteFeatures(:, 1:n1)', 'squaredeuclidean');
isDenser = bsxfun(@lt, rhoOrder, rhoOrder(1:n1)');
nearbyInTime = abs(bsxfun(@minus, spikeOrder, spikeOrderN1)) <= dn_max;
dists(~(isDenser & nearbyInTime)) = nan;
dists = sqrt(dists/distCut2); % normalize
[delta, nNeigh] = min(dists);
end
% spikes which are maximally dense get SINGLE_INF
maximallyDense = isnan(delta);
delta(maximallyDense) = sqrt(3.402E+38/distCut2); % to (more or less) square with CUDA kernel's SINGLE_INF
nNeigh(maximallyDense) = find(maximallyDense);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
computeRho.m
|
.m
|
JRCLUST-main/+jrclust/+sort/computeRho.m
| 7,725 |
utf_8
|
e105308d09ac426b49d8fe7da60fb1a6
|
function res = computeRho(dRes, res, hCfg)
%COMPUTERHO Compute rho values for spike features
res.rhoCutSite = zeros(hCfg.nSites, 1, 'single');
res.rhoCutGlobal = [];
% compute rho cutoff globally
if hCfg.useGlobalDistCut
res.rhoCutGlobal = estRhoCutGlobal(dRes, hCfg);
end
hCfg.updateLog('computeRho', 'Computing rho', 1, 0);
% create CUDA kernel
chunkSize = 16;
nC_max = 45;
if hCfg.useGPU
ptxFile = fullfile(jrclust.utils.basedir(), '+jrclust', '+CUDA', 'jrc_cuda_rho.ptx');
cuFile = fullfile(jrclust.utils.basedir(), '+jrclust', '+CUDA', 'jrc_cuda_rho.cu');
rhoCK = parallel.gpu.CUDAKernel(ptxFile, cuFile);
rhoCK.ThreadBlockSize = [hCfg.nThreadsGPU, 1];
rhoCK.SharedMemorySize = 4 * chunkSize * (2 + nC_max + 2*hCfg.nThreadsGPU);
else
rhoCK = [] ;
end
spikeData = struct('spikeTimes', dRes.spikeTimes);
for iSite = 1:hCfg.nSites
if isfield(dRes, 'spikesBySite')
spikeData.spikes1 = dRes.spikesBySite{iSite};
else
spikeData.spikes1 = dRes.spikeSites(dRes.spikeSites==iSite);
end
if isfield(dRes, 'spikesBySite2') && ~isempty(dRes.spikesBySite2)
spikeData.spikes2 = dRes.spikesBySite2{iSite};
elseif isfield(dRes, 'spikeSites2')
spikeData.spikes2 = dRes.spikeSites2(dRes.spikeSites2==iSite);
end
if isfield(dRes, 'spikesBySite3') && ~isempty(dRes.spikesBySite3)
spikeData.spikes3 = dRes.spikesBySite3{iSite};
elseif isfield(dRes, 'spikesBySite3')
spikeData.spikes3 = dRes.spikesBySite3(dRes.spikesBySite3==iSite);
end
[siteFeatures, ~, n1, n2, spikeOrder] = jrclust.features.getSiteFeatures(dRes.spikeFeatures, iSite, spikeData, hCfg);
if hCfg.useGPU
rhoCK.GridSize = [ceil(n1/chunkSize^2), chunkSize]; %MaxGridSize: [2.1475e+09 65535 65535]
end
if isempty(siteFeatures)
continue;
end
siteFeatures = jrclust.utils.tryGpuArray(siteFeatures, hCfg.useGPU);
spikeOrder = jrclust.utils.tryGpuArray(spikeOrder, hCfg.useGPU);
if isempty(res.rhoCutGlobal) % estimate rhoCut in CPU
siteCut = estRhoCutSite(siteFeatures, spikeOrder, n1, n2, hCfg);
else
siteCut = res.rhoCutGlobal.^2;
end
siteRho = computeRhoSite(siteFeatures, spikeOrder, n1, n2, siteCut, rhoCK, hCfg);
res.spikeRho(spikeData.spikes1) = jrclust.utils.tryGather(siteRho);
res.rhoCutSite(iSite) = jrclust.utils.tryGather(siteCut);
clear siteFeatures spikeOrder siteRho;
hCfg.updateLog('rhoSite', sprintf('Site %d: rho cutoff, %0.2f; average rho: %0.5f (%d spikes)', iSite, siteCut, mean(res.spikeRho), n1), 0, 0);
end
hCfg.updateLog('computeRho', 'Finished computing rho', 0, 1);
end
%% LOCAL FUNCTIONS
function rho = computeRhoSite(siteFeatures, spikeOrder, n1, n2, rhoCut, rhoCK, hCfg)
%COMPUTERHOSITE Compute site-wise rho for spike features
[nC, n12] = size(siteFeatures); % nc is constant with the loop
dn_max = int32(round((n1 + n2) / hCfg.nClusterIntervals));
rhoCut = single(rhoCut);
if hCfg.useGPU
try
rho = zeros(1, n1, 'single', 'gpuArray');
consts = int32([n1, n12, nC, dn_max, hCfg.getOr('fDc_spk', 0)]);
rho = feval(rhoCK, rho, siteFeatures, spikeOrder, consts, rhoCut);
return;
catch ME
warning('CUDA kernel failed: %s', ME.message);
end
end
% retry in CPU
[siteFeatures, spikeOrder] = jrclust.utils.tryGather(siteFeatures, spikeOrder);
spikeOrderN1 = spikeOrder(1:n1)';
% we can quickly run out of space here, ensure this doesn't happen
availMem = 2^33; % 8 GiB
if jrclust.utils.typeBytes(class(spikeOrder))*n1*n12 > availMem
stepSize = floor(availMem/n12/jrclust.utils.typeBytes(class(spikeOrder)));
rho = zeros(1, n1, 'single');
for iChunk = 1:stepSize:n1
iRange = iChunk:min(iChunk+stepSize-1, n1);
nearbyTimeChunk = abs(bsxfun(@minus, spikeOrder, spikeOrderN1(iRange))) <= dn_max;
nearbySpaceChunk = pdist2(siteFeatures', siteFeatures(:, iRange)', 'squaredeuclidean') <= rhoCut;
rho(iRange) = sum(nearbyTimeChunk & nearbySpaceChunk) ./ sum(nearbyTimeChunk);
end
else
nearbyTime = abs(bsxfun(@minus, spikeOrder, spikeOrderN1)) <= dn_max;
nearbySpace = (pdist2(siteFeatures', siteFeatures(:, 1:n1)', 'squaredeuclidean') <= rhoCut); % include self
rho = sum(nearbyTime & nearbySpace);
rho = single(rho ./ sum(nearbyTime)); % normalize
end
end
function rhoCut = estRhoCutGlobal(dRes, hCfg, vlRedo_spk)
%ESTRHOCUTGLOBAL Estimate rho cutoff distance over all sites
if nargin < 3
vlRedo_spk = [];
end
spikeData = struct('spikeTimes', dRes.spikeTimes, ...
'vlRedo_spk', vlRedo_spk);
hCfg.updateLog('estimateCutDist', 'Estimating cutoff distance', 1, 0);
% estimate rho cutoff for each site
siteCuts = nan(1, hCfg.nSites);
for iSite = 1:hCfg.nSites
if isfield(dRes, 'spikesBySite')
spikeData.spikes1 = dRes.spikesBySite{iSite};
else
spikeData.spikes1 = dRes.spikeSites(dRes.spikeSites==iSite);
end
if isfield(dRes, 'spikesBySite2') && ~isempty(dRes.spikesBySite2)
spikeData.spikes2 = dRes.spikesBySite2{iSite};
end
if isfield(dRes, 'spikesBySite3') && ~isempty(dRes.spikesBySite3)
spikeData.spikes3 = dRes.spikesBySite3{iSite};
end
[siteFeatures, ~, n1, n2, spikeOrder] = jrclust.features.getSiteFeatures(dRes.spikeFeatures, iSite, spikeData, hCfg);
if isempty(siteFeatures)
continue;
end
siteCuts(iSite) = estRhoCutSite(siteFeatures, spikeOrder, n1, n2, hCfg);
hCfg.updateLog('rhoCutSite', sprintf('Estimated rho cutoff for site %d: %0.2f', iSite, res.rhoCutSite(iSite)), 0, 0);
end
rhoCut = sqrt(abs(quantile(siteCuts, .5)));
hCfg.updateLog('estimateCutDist', sprintf('Finished estimating cutoff distance: %0.2f', rhoCut), 0, 1);
end
function rhoCut = estRhoCutSite(siteFeatures, spikeOrder, n1, n2, hCfg)
%ESTRHOCUTSITE Estimate site-wise rho cutoff
if hCfg.getOr('fDc_spk', 0)
rhoCut = (hCfg.distCut/100).^2;
return;
end
nSubsample = 1000;
[nPrimary, nSecondary] = deal(nSubsample, 4*nSubsample);
ss = jrclust.utils.subsample(1:n1, nPrimary);
spikeOrderPrimary = spikeOrder(ss);
featuresPrimary = siteFeatures(:, ss);
ss = jrclust.utils.subsample(1:n1, nSecondary);
spikeOrder = spikeOrder(ss);
siteFeatures = siteFeatures(:, ss);
for iRetry = 1:2
try
featureDists = pdist2(siteFeatures', featuresPrimary', 'squaredeuclidean');
fSubset = abs(bsxfun(@minus, spikeOrder, spikeOrderPrimary')) < (n1 + n2) / hCfg.nClusterIntervals;
featureDists(~fSubset) = nan;
break;
catch ME
siteFeatures = jrclust.utils.tryGather(siteFeatures);
end
end
if hCfg.getOr('fDc_subsample_mode', 0)
featureDists(featureDists <= 0) = nan;
rhoCut = quantile(featureDists(~isnan(featureDists)), hCfg.distCut/100);
else
featureDists = jrclust.utils.tryGather(featureDists);
featureDists(featureDists <=0) = nan;
rhoCut = nanmedian(quantile(featureDists, hCfg.distCut/100));
if isnan(rhoCut) % featureDists was completely nan
rhoCut = quantile(featureDists(:), hCfg.distCut/100);
end
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
detrendRhoDelta.m
|
.m
|
JRCLUST-main/+jrclust/+sort/detrendRhoDelta.m
| 3,219 |
utf_8
|
5eb83d93119c4695dab3563811a087c3
|
function [centers, logRho, zscores] = detrendRhoDelta(hClust, spikesBySite, fLocal, hCfg)
%DETREND Detrend rho-delta plot to identify cluster centers (high rho, high delta)
logRho = log10(hClust.spikeRho);
delta = hClust.spikeDelta;
if fLocal % detrend for each site
rhosBySite = cellfun(@(spikes) hClust.spikeRho(spikes), spikesBySite, 'UniformOutput', 0);
deltasBySite = cellfun(@(spikes) delta(spikes), spikesBySite, 'UniformOutput', 0);
centersBySite = cell(size(spikesBySite));
zscores = zeros(size(delta), 'like', delta);
for iSite = 1:numel(spikesBySite)
siteSpikes = spikesBySite{iSite};
if isempty(siteSpikes)
continue;
end
logRhoSite = log10(rhosBySite{iSite});
deltaSite = deltasBySite{iSite};
% select only those rho values between 10^cutoff and 0.1
% and delta values between 0 and 1
detIndices = find(logRhoSite > hCfg.log10RhoCut & logRhoSite < -1 & deltaSite > 0 & deltaSite < 1 & isfinite(logRhoSite) & isfinite(deltaSite));
[yhat, zsite] = detrendQuadratic(logRhoSite, deltaSite, detIndices);
% spikes with exact same features
yhat(deltaSite == 0) = nan;
zsite(deltaSite == 0) = nan;
% get the indices of the maxClustersSite largest detrended
% values where the rho values beat the cutoff
centers_ = nLargest(yhat, hCfg.maxClustersSite, find(logRhoSite > hCfg.log10RhoCut & ~isnan(yhat)));
if isempty(centers_)
continue;
end
centersBySite{iSite} = siteSpikes(centers_);
zscores(siteSpikes) = zsite;
end
centers = cell2vec(centersBySite);
else % detrend globally
detIndices = find(delta > 0 & delta < 1 & hClust.spikeRho > 10^hCfg.log10RhoCut & hClust.spikeRho < .1 & isfinite(logRho) & isfinite(delta));
[~, zscores] = detrendQuadratic(logRho, delta, detIndices);
zscores(delta == 0) = nan;
[centers, zLargest] = nLargest(zscores, hCfg.maxClustersSite*numel(spikesBySite), find(hClust.spikeRho > 10^hCfg.log10RhoCut & ~isnan(zscores)));
centers(zLargest < 10^hCfg.log10DeltaCut) = [];
end
end
%% LOCAL FUNCTIONS
function [yhat, zscores] = detrendQuadratic(x, y, indices)
%DETRENDQUADRATIC Remove quadratic component from y~x
x = x(:);
y = y(:);
eps_ = eps(class(x));
X = [x.^2 + eps_, x + eps_, ones(numel(x), 1)];
b = X(indices, :)\y(indices);
yhat = y - X*b;
zscores = (yhat - nanmean(yhat(indices))) / nanstd(yhat(indices));
end
function [iLargest, largest] = nLargest(vals, n, indices)
%NLARGEST Get the (indices of the) n largest elements in an array
n = min(n, numel(indices));
[~, argsort] = sort(vals(indices), 'descend');
iLargest = indices(argsort(1:n));
largest = vals(iLargest);
end
function vals = cell2vec(vals)
%CELL2VEC Convert cell array to vector
vals = vals(:);
vals = vals(cellfun(@(x) ~isempty(x), vals));
for i = 1:numel(vals)
v = vals{i};
vals{i} = v(:);
end
vals = cell2mat(vals);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
assignClusters.m
|
.m
|
JRCLUST-main/+jrclust/+sort/assignClusters.m
| 5,777 |
utf_8
|
7a148b0d500650e1792590c71be17900
|
function sRes = assignClusters(dRes, sRes, hCfg)
%ASSIGNCLUSTERS Given rho-delta information, assign spikes to clusters
sRes = computeCenters(dRes, sRes, hCfg);
sRes.spikeClusters = [];
% do initial assignment
hCfg.updateLog('assignClusters', sprintf('Assigning clusters (nClusters: %d)', numel(sRes.clusterCenters)), 1, 0);
sRes = doAssign(dRes, sRes, hCfg);
nClusters = numel(sRes.clusterCenters);
% split clusters by site distance
sRes = splitDist(dRes, sRes, hCfg);
% reassign spikes if we had to split
if nClusters ~= numel(sRes.clusterCenters)
sRes.spikeClusters = [];
sRes = doAssign(dRes, sRes, hCfg);
nClusters = numel(sRes.clusterCenters);
end
% remove small clusters
for iRepeat = 1:1000
sRes = removeSmall(dRes, sRes, hCfg);
if nClusters == numel(sRes.clusterCenters)
break;
end
sRes = doAssign(dRes, sRes, hCfg);
nClusters = numel(sRes.clusterCenters);
end
hCfg.updateLog('assignClusters', sprintf('Finished initial assignment (%d clusters)', nClusters), 0, 1);
end
%% LOCAL FUNCTIONS
function sRes = computeCenters(dRes, sRes, hCfg)
%COMPUTECENTERS Find cluster centers
if ~isfield(dRes, 'spikesBySite')
dRes.spikesBySite = arrayfun(@(iSite) dRes.spikes(dRes.spikeSites==iSite), hCfg.siteMap, 'UniformOutput', 0);
end
if strcmp(hCfg.RDDetrendMode, 'local') % perform detrending site by site
sRes.clusterCenters = jrclust.sort.detrendRhoDelta(sRes, dRes.spikesBySite, 1, hCfg);
elseif strcmp(hCfg.RDDetrendMode, 'global') % detrend over all sites
sRes.clusterCenters = jrclust.sort.detrendRhoDelta(sRes, dRes.spikesBySite, 0, hCfg);
elseif strcmp(hCfg.RDDetrendMode, 'logz') % identify centers with sufficiently high z-scores
% sRes.clusterCenters = log_ztran_(sRes.spikeRho, sRes.spikeDelta, hCfg.log10RhoCut, 4 + hCfg.log10DeltaCut);
x = log10(sRes.spikeRho(:));
y = log10(sRes.spikeDelta(:));
mask = isfinite(x) & isfinite(y);
y(mask) = jrclust.utils.zscore(y(mask));
sRes.clusterCenters = find(x >= hCfg.log10RhoCut & y >= 4 + hCfg.log10DeltaCut);
elseif strcmp(hCfg.RDDetrendMode, 'regress') % regression method
sRes.clusterCenters = jrclust.sort.regressCenters(sRes, dRes.spikesBySite, hCfg.log10DeltaCut);
else % don't detrend
sRes.clusterCenters = find(sRes.spikeRho(:) > 10^(hCfg.log10RhoCut) & sRes.spikeDelta(:) > 10^(hCfg.log10DeltaCut));
end
end
function sRes = doAssign(dRes, sRes, hCfg)
%DOASSIGN Assign spikes to clusters
nSpikes = numel(sRes.ordRho);
nClusters = numel(sRes.clusterCenters);
if isempty(sRes.spikeClusters)
sRes.spikeClusters = zeros([nSpikes, 1], 'int32');
sRes.spikeClusters(sRes.clusterCenters) = 1:nClusters;
end
% one or no center, assign all spikes to one cluster
if numel(sRes.ordRho) > 0 && (numel(sRes.clusterCenters) == 0 || numel(sRes.clusterCenters) == 1)
sRes.spikeClusters = ones([nSpikes, 1], 'int32');
sRes.clusterCenters = sRes.ordRho(1);
else
unassigned = sRes.spikeClusters <= 0;
canAssign = sRes.spikeClusters(sRes.spikeNeigh) > 0;
doAssign = unassigned & canAssign;
while any(doAssign)
hCfg.updateLog('assignIter', sprintf('%d/%d spikes unassigned, %d can be assigned', ...
sum(unassigned), nSpikes, sum(doAssign)), 0, 0);
sRes.spikeClusters(doAssign) = sRes.spikeClusters(sRes.spikeNeigh(doAssign));
unassigned = sRes.spikeClusters <= 0;
canAssign = sRes.spikeClusters(sRes.spikeNeigh) > 0;
doAssign = unassigned & canAssign;
end
end
nClusters = numel(sRes.clusterCenters);
% count spikes in clusters
sRes.spikesByCluster = arrayfun(@(iC) find(sRes.spikeClusters == iC), 1:nClusters, 'UniformOutput', 0);
sRes.unitCount = cellfun(@numel, sRes.spikesByCluster);
sRes.clusterSites = double(arrayfun(@(iC) mode(dRes.spikeSites(sRes.spikesByCluster{iC})), 1:nClusters));
end
function sRes = splitDist(dRes, sRes, hCfg)
nClusters = numel(sRes.clusterCenters);
for jCluster = 1:nClusters
% get the number of unique sites for this cluster
jSpikes = sRes.spikesByCluster{jCluster};
jSites = dRes.spikeSites(jSpikes);
uniqueSites = unique(jSites);
if numel(unique(jSites)) == 1
continue;
end
% order spike sites by density, descending
jRho = sRes.spikeRho(jSpikes);
[~, ordering] = sort(jRho, 'descend');
jSpikes = jSpikes(ordering);
jSites = jSites(ordering);
siteOrdering = arrayfun(@(k) find(jSites == k, 1), uniqueSites);
[~, siteOrdering] = sort(siteOrdering);
uniqueSites = uniqueSites(siteOrdering);
siteLocs = hCfg.siteLoc(uniqueSites, :);
siteDists = pdist2(siteLocs, siteLocs);
% find pairwise distances which exceed the merge radius
isFar = siteDists > 2*hCfg.evtMergeRad;
[r, c] = find(isFar);
if isempty(r)
continue;
end
splitOff = jSpikes(arrayfun(@(k) find(jSites == k, 1), unique(uniqueSites(r(r > c)))));
sRes.clusterCenters = [sRes.clusterCenters; splitOff];
end
end
function sRes = removeSmall(dRes, sRes, hCfg)
hCfg.minClusterSize = max(hCfg.minClusterSize, 2*size(dRes.spikeFeatures, 1));
% remove small clusters
smallClusters = sRes.unitCount <= hCfg.minClusterSize;
if any(smallClusters)
sRes.clusterCenters(smallClusters) = [];
sRes.spikeClusters = [];
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
v3.m
|
.m
|
JRCLUST-main/+jrclust/+import/v3.m
| 10,097 |
utf_8
|
e135825cb7562eb7126f7341643710de
|
function [hCfg, res] = v3(filename)
%V3 Import an old-style session (_jrc.mat) to the new style
[hCfg, res] = deal([]);
filename_ = jrclust.utils.absPath(filename);
if isempty(filename_)
error('Could not find ''%s''', filename);
end
try
S0 = load(filename_, '-mat');
catch ME
error('Failed to load ''%s'': %s', filename, ME.message);
end
% load config
if ~isfield(S0, 'P')
error('Could not find params struct (P)');
end
prmFile = jrclust.utils.absPath(S0.P.vcFile_prm, fileparts(filename_));
if isempty(prmFile)
% couldn't find vcFile_prm; set it manually
dlgFieldNames = {'New config filename'};
dlgFieldVals = {jrclust.utils.subsExt(strrep(filename_, '_jrc', ''), '.prm')};
dlgAns = inputdlg(dlgFieldNames, 'Please specify a config filename', 1, dlgFieldVals, struct('Resize', 'on', 'Interpreter', 'tex'));
if isempty(dlgAns) % abort
return;
end
S0.P.vcFile_prm = dlgAns{1};
% create the new config file
[fid, errmsg] = fopen(S0.P.vcFile_prm, 'w');
if fid == -1
error('Could not open file ''%s'' for writing: %s', S0.P.vcFile_prm, errmsg);
end
fclose(fid);
hCfg = jrclust.Config();
else
hCfg = jrclust.Config(prmFile);
end
% try to import params directly
oldPrms = fieldnames(S0.P);
% handle special cases in P
if isfield(S0.P, 'spkLim_raw_ms') && isempty(S0.P.spkLim_raw_ms)
if isfield(S0.P, 'spkLim_ms') && isfield(S0.P, 'spkLim_raw_factor')
S0.P.spkLim_raw_ms = S0.P.spkLim_ms * S0.P.spkLim_raw_factor;
end
end
for i = 1:numel(oldPrms)
propname = oldPrms{i};
if isfield(hCfg.oldParamSet, propname) && ~isempty(S0.P.(propname))
% these will be converted automatically
try
hCfg.(propname) = S0.P.(propname);
catch % use default
end
end
end
% construct dRes
res = struct();
errMsg = {};
if ~isfield(S0, 'viTime_spk')
errMsg{end+1} = 'missing viTime_spk';
end
if ~isfield(S0, 'viSite_spk')
errMsg{end+1} = 'missing viTime_spk';
end
if ~isempty(errMsg)
error(strjoin(errMsg, ';'));
end
res.spikeTimes = S0.viTime_spk;
res.spikeSites = S0.viSite_spk;
if isfield(S0, 'vrAmp_spk')
res.spikeAmps = S0.vrAmp_spk;
end
if isfield(S0, 'mrPos_spk')
res.spikePositions = S0.mrPos_spk;
end
if isfield(S0, 'cviSpk_site')
res.spikesBySite = S0.cviSpk_site;
end
if isfield(S0, 'cviSpk2_site')
res.spikesBySite2 = S0.cviSpk2_site;
end
if isfield(S0, 'cviSpk3_site')
res.spikesBySite3 = S0.cviSpk3_site;
end
if isfield(S0, 'viSite2_spk')
res.spikeSites2 = S0.viSite2_spk;
end
if isfield(S0, 'vrThresh_site')
res.siteThresh = S0.vrThresh_site;
end
if isfield(S0, 'dimm_raw')
res.rawShape = S0.dimm_raw;
end
if isfield(S0, 'dimm_spk')
res.filtShape = S0.dimm_spk;
end
if isfield(S0, 'dimm_fet')
res.featuresShape = S0.dimm_fet;
end
% rename spkraw, spkwav, spkfet
spkraw = jrclust.utils.subsExt(strrep(filename_, '_jrc', ''), '_spkraw.jrc');
if exist(spkraw, 'file') == 2
renameFile(spkraw, hCfg.rawFile);
fid = fopen(hCfg.rawFile, 'r');
res.spikesRaw = fread(fid, '*int16');
fclose(fid);
res.spikesRaw = reshape(res.spikesRaw, res.rawShape);
else
warning('Could not find file ''%s''', spkraw);
res.spikesRaw = [];
end
spkwav = jrclust.utils.subsExt(strrep(filename_, '_jrc', ''), '_spkwav.jrc');
if exist(spkwav, 'file') == 2
renameFile(spkwav, hCfg.filtFile);
fid = fopen(hCfg.filtFile, 'r');
res.spikesFilt = fread(fid, '*int16');
fclose(fid);
res.spikesFilt = reshape(res.spikesFilt, res.filtShape);
else
warning('Could not find file ''%s''', spkwav);
res.spikesFilt = [];
end
spkfet = jrclust.utils.subsExt(strrep(filename_, '_jrc', ''), '_spkfet.jrc');
if exist(spkfet, 'file') == 2
renameFile(spkfet, hCfg.featuresFile);
fid = fopen(hCfg.featuresFile, 'r');
res.spikeFeatures = fread(fid, '*single');
fclose(fid);
res.spikeFeatures = reshape(res.spikeFeatures, res.featuresShape);
else
warning('Could not find file ''%s''', spkfet);
res.spikeFeatures = [];
end
% construct sRes
if isfield(S0, 'S_clu')
S_clu = S0.S_clu;
sRes = struct();
reqFields = {'viClu', 'rho', 'delta', 'nneigh'};
if all(ismember(reqFields, fieldnames(S_clu)))
sRes.spikeClusters = S_clu.viClu;
sRes.spikeRho = S_clu.rho;
sRes.spikeDelta = S_clu.delta;
sRes.spikeNeigh = S_clu.nneigh;
if isfield(S_clu, 'ordrho')
sRes.ordRho = S_clu.ordrho;
else
[~, sRes.ordRho] = sort(sRes.spikeRho, 'descend');
end
if isfield(S_clu, 'cviSpk_clu')
sRes.spikesByCluster = S_clu.cviSpk_clu;
else
sRes.spikesByCluster = arrayfun(@(iC) find(sRes.spikeClusters == iC), 1:max(sRes.spikeClusters), 'UniformOutput', 0);
end
if isfield(S_clu, 'csNote_clu')
sRes.clusterNotes = S_clu.csNote_clu;
end
if isfield(S_clu, 'icl')
clusterCenters = zeros(max(sRes.spikeClusters), 1);
for iCluster = 1:numel(clusterCenters)
iSpikes = sRes.spikesByCluster{iCluster};
iCenters = intersect(S_clu.icl, iSpikes);
if isempty(iCenters)
[~, densest] = max(sRes.spikeRho(iSpikes));
clusterCenters(iCluster) = iSpikes(densest);
else
[~, densest] = max(sRes.spikeRho(iCenters));
clusterCenters(iCluster) = iCenters(densest);
end
end
sRes.clusterCenters = clusterCenters;
end
if isfield(S_clu, 'mrWavCor')
sRes.waveformSim = S_clu.mrWavCor;
end
if isfield(S_clu, 'tmrWav_spk_clu')
sRes.meanWfGlobal = S_clu.tmrWav_spk_clu;
end
if isfield(S_clu, 'tmrWav_raw_clu')
sRes.meanWfGlobalRaw = S_clu.tmrWav_raw_clu;
end
if isfield(S_clu, 'trWav_spk_clu')
sRes.meanWfLocal = S_clu.trWav_spk_clu;
end
if isfield(S_clu, 'trWav_raw_clu')
sRes.meanWfLocalRaw = S_clu.trWav_raw_clu;
end
if isfield(S_clu, 'tmrWav_raw_hi_clu')
sRes.meanWfRawHigh = S_clu.tmrWav_raw_hi_clu;
end
if isfield(S_clu, 'tmrWav_raw_hi_clu')
sRes.meanWfRawLow = S_clu.tmrWav_raw_hi_clu;
end
if isfield(S_clu, 'viSite_clu')
sRes.clusterSites = S_clu.viSite_clu;
end
if isfield(S_clu, 'viClu_auto')
sRes.initialClustering = S_clu.viClu_auto;
end
if isfield(S_clu, 'viSite_min_clu')
sRes.unitPeakSites = S_clu.viSite_min_clu;
end
if isfield(S_clu, 'vnSite_clu')
sRes.nSitesOverThresh = S_clu.vnSite_clu;
end
if isfield(S_clu, 'vnSpk_clu')
sRes.unitCount = S_clu.vnSpk_clu;
end
if isfield(S_clu, 'vrDc2_site')
sRes.rhoCutSite = S_clu.vrDc2_site;
end
if isfield(S_clu, 'vrIsiRatio_clu')
sRes.unitISIRatio = S_clu.vrIsiRatio_clu;
end
if isfield(S_clu, 'vrIsoDist_clu')
sRes.unitIsoDist = S_clu.vrIsoDist_clu;
end
if isfield(S_clu, 'vrLRatio_clu')
sRes.unitLRatio = S_clu.vrLRatio_clu;
end
if isfield(S_clu, 'vrPosX_clu') && isfield(S_clu, 'vrPosY_clu')
sRes.clusterCentroids = [S_clu.vrPosX_clu(:), S_clu.vrPosY_clu(:)];
end
if isfield(S_clu, 'vrSnr_clu')
sRes.unitSNR = S_clu.vrSnr_clu;
end
if isfield(S_clu, 'vrVmin_clu')
sRes.unitPeaks = S_clu.vrVmin_clu;
end
if isfield(S_clu, 'vrVmin_clu')
sRes.unitPeaksRaw = S_clu.vrVmin_clu;
end
if isfield(S_clu, 'vrVpp_clu')
sRes.unitVpp = S_clu.vrVpp_clu;
end
if isfield(S_clu, 'vrVpp_uv_clu')
sRes.unitVppRaw = S_clu.vrVpp_uv_clu;
end
if isfield(S_clu, 'vrVrms_site')
sRes.siteRMS = S_clu.vrVrms_site;
end
end
hClust = jrclust.sort.DensityPeakClustering(hCfg, sRes, res);
msgs = hClust.inconsistentFields();
assert(isempty(msgs), strjoin(msgs, ', '));
% remove quality scores/initial clustering from sRes
sRes = rmfield(sRes, {'clusterCentroids', 'clusterNotes', 'initialClustering', ...
'meanWfGlobal', 'meanWfGlobalRaw', 'meanWfLocal', 'meanWfLocalRaw', ...
'meanWfRawHigh', 'meanWfRawLow', 'nSitesOverThresh', 'waveformSim', ...
'siteRMS', 'unitISIRatio', 'unitIsoDist', 'unitLRatio', 'unitPeakSites', ...
'unitPeaks', 'unitPeaksRaw', 'unitSNR', 'unitVpp', 'unitVppRaw'});
res = jrclust.utils.mergeStructs(res, sRes);
res.hClust = hClust;
end
end
%% LOCAL FUNCTIONS
function renameFile(oldfile, newfile)
try
movefile(oldfile, newfile);
catch ME
warning('failed to rename %s to %s: %s (try to move it manually?)', oldfile, newfile, ME.message);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
loadPhy.m
|
.m
|
JRCLUST-main/+jrclust/+import/private/loadPhy.m
| 2,295 |
utf_8
|
3b2cb8ce5b1f9a7ed98fe7f5c4d9025c
|
function phyData = loadPhy(loadPath)
%LOADPHY Load and return Phy-formatted .npy files
phyData = struct();
if exist('readNPY', 'file') ~= 2
warning('Please make sure you have npy-matlab installed (https://github.com/kwikteam/npy-matlab)');
return;
end
loadPath_ = jrclust.utils.absPath(loadPath);
if isempty(loadPath_)
error('Could not find path ''%s''', loadPath);
elseif exist(loadPath, 'dir') ~= 7
error('''%s'' is not a directory', loadPath);
end
loadPath = loadPath_;
ls = dir(loadPath);
for iFile = 1:numel(ls)
file = ls(iFile);
if file.isdir || isempty(regexp(file.name, 'py$', 'once'))
continue
end
[~, fn, ext] = fileparts(file.name);
switch ext
case '.py'
if strcmp(fn, 'params')
phyData.params = parseParams(fullfile(loadPath, file.name));
end
case '.npy'
fn = matlab.lang.makeValidName(fn);
phyData.(fn) = readNPY(fullfile(loadPath, file.name));
end
end
phyData.loadPath = loadPath;
end % function
%% LOCAL FUNCTIONS
function params = parseParams(paramFile)
%PARSEPARAMS Parse a Phy params.py file, returning a struct
params = [];
if exist(paramFile, 'file') ~= 2
return;
end
params = struct();
keysVals = cellfun(@(line) strsplit(line, '='), jrclust.utils.readLines(paramFile), 'UniformOutput', 0);
for i = 1:numel(keysVals)
kv = cellfun(@strip, keysVals{i}, 'UniformOutput', 0);
key = kv{1}; val = kv{2};
% strip quote marks from strings
val = regexprep(val, '^r?[''"]', ''); % remove r", r', ", or ' from beginning of string
val = regexprep(val, '[''"]$', ''); % remove " or ' from end of string
switch key
case 'dat_path' % get full path to dat_path
val_ = jrclust.utils.absPath(val, fileparts(paramFile));
if isempty(val_)
warning('File ''%s'' was not found; consider updating params.py with the new path', val);
end
val = val_;
case {'n_channels_dat', 'offset', 'sample_rate', 'n_features_per_channel'}
val = str2double(val);
case 'hp_filtered'
val = strcmp(val, 'True');
case 'dtype'
val = strip(val, '''');
end
params.(key) = val;
end
end %function
|
github
|
JaneliaSciComp/JRCLUST-main
|
nwb.m
|
.m
|
JRCLUST-main/+jrclust/+export/nwb.m
| 17,128 |
utf_8
|
4a2bdc1a2a095661d8f768b20c3f8d8f
|
function nwbData = nwb(hClust, outPath)
%NWBEXPORT exports jrclust data to NWB
% Assumes matnwb is in path and generateCore is called
% hClust is a regular hClust object with certain additions for config data
% outFileName is the destination file name produced by NWB.
% Should use the .nwb extension
if exist('nwbRead', 'file') ~= 2
warning('Please make sure you have MatNWB installed and on your path (https://github.com/NeurodataWithoutBorders/matnwb)');
return;
end
assert(ischar(outPath), 'output filename should be a char array');
if 2 == exist(outPath, 'file')
[~, filename, ~] = fileparts(outPath);
prompt = ['This file already exists. '...
'Would you like to overwrite or update the file? '...
'You will lose all data if you overwrite. '...
'Updating a NWB file is currently incomplete.'];
title = 'Overwrite Prompt';
selection = questdlg(prompt, title, 'Overwrite', 'Update', 'Cancel', 'Overwrite');
switch selection
case 'Overwrite'
warning(toMsgID('File'),...
'Deleting `%s` and starting anew.', filename);
delete(outPath);
case 'Update'
error(toMsgID('Internal', 'Todo'),...
'This feature is a work in progress. Please wait warmly.');
case {'Cancel' ''} % including X-ing out
warning(toMsgID('Abort'), 'Aborting export.');
return;
otherwise
error(toMsgID('Internal', 'InvalidSelection'),...
'Unknown questdlg selection %s', selection);
end
end
hCfg = hClust.hCfg;
%% Metadata
log_progress('Filling out Metadata');
nwbData = NwbFile;
nwbData.identifier = hCfg.sessionName;
nwbData.session_start_time = datetime(hClust.detectedOn, 'ConvertFrom', 'datenum');
param_fid = fopen([hCfg.sessionName '-full.prm']);
param_data = fread(param_fid, '*char');
fclose(param_fid);
nwbData.general_data_collection = param_data .';
% TODO invalid data, replace with file create date if it exists.
nwbData.timestamps_reference_time = datetime('now');
nwbData.session_description = 'JRCLust Spike Data';
nwbData.general_source_script_file_name = mfilename('fullpath');
log_done();
%% Devices
log_progress('Filling out electrode hardware data');
prompt = 'Please provide a probe name that was used to acquire this data.';
probe_name = prompt_required_input(prompt);
nwbData.general_devices.set(probe_name, types.core.Device());
probe_path = ['/general/devices/' probe_name];
%% Electrode Groups
shank_ids = unique(hCfg.shankMap);
num_shanks = length(shank_ids);
groups_path_stub = '/general/extracellular_ephys/';
Shank2Name_Map = containers.Map('KeyType', 'double', 'ValueType', 'char');
for i = 1:num_shanks
shank_number = shank_ids(i);
name = sprintf('Shank%02d', shank_number);
description = sprintf('shank %02d of %02d', shank_number, num_shanks);
prompt = sprintf('What is the location of shank %02d?', shank_number);
location = prompt_required_input(prompt);
Electrode_Group = types.core.ElectrodeGroup(...
'description', description,...
'location', location,...
'device', types.untyped.SoftLink(probe_path));
nwbData.general_extracellular_ephys.set(name, Electrode_Group);
Shank2Name_Map(shank_number) = name;
end
%% Electrode Sites
% Note: sites is a subset of channels. They would be channels of interest.
% There is no location data for non-site channels, so we assume that all sites
% are valid electrodes
num_sites = hCfg.nSites;
vector_shape = [num_sites 1];
site_locations = hCfg.siteLoc;
invalid_str_column = {repmat({'N/A'}, vector_shape)}; % extra cell layer due to struct behavior
zero_column = zeros(vector_shape);
electrode_names = cell(vector_shape);
electrode_references = types.untyped.ObjectView.empty;
for i = 1:num_sites
shank_name = Shank2Name_Map(hCfg.shankMap(i));
electrode_names{i} = shank_name;
path = [groups_path_stub shank_name];
electrode_references(i) = types.untyped.ObjectView(path);
end
Electrode_Data = struct(...
'x', site_locations(:, 1),...
'y', site_locations(:, 1),...
'z', zero_column,...
'imp', zero_column,...
'location', invalid_str_column,...
'filtering', invalid_str_column,...
'group', electrode_references,...
'group_name', {electrode_names},...
'channel_index', hCfg.siteMap);
Descriptions = struct(...
'channel_index', 'index to valid channels');
nwbData.general_extracellular_ephys_electrodes =...
to_electrode_table(Electrode_Data, Descriptions);
electrodes_path = '/general/extracellular_ephys/electrodes';
log_done();
%% Recording
% log_progress('Converting to HDF5 files and Linking (This will take a while)');
%
% % calculate channel -> site indices
% site_indices = zeros(Config.nChans, 1);
% for i = 1:Config.nChans
% index = find(Electrode_Data.channel_index == i, 1);
% if ~isempty(index)
% site_indices(i) = index;
% end
% end
% Electrodes_Ref = to_table_region(site_indices,...
% 'Sites associated with these channels (0 indicates invalid channel)',...
% electrodes_path);
%
% % can be multiple raw files. Assumed that they're in order.
% raw_filenames = Config.rawRecordings;
% start_sample = 0;
% for i = 1:length(raw_filenames)
% raw = raw_filenames{i};
% File_Meta = dir(raw);
% sample_size = Config.bytesPerSample * Config.nChans;
% num_samples = File_Meta.bytes / sample_size;
% data_shape = [Config.nChans num_samples];
% Raw_Series = types.core.ElectricalSeries(...
% 'data', bin_to_hdf5(raw, data_shape, Config.dataType),...
% 'starting_time', start_sample,...
% 'starting_time_rate', Config.sampleRate,...
% 'electrodes', Electrodes_Ref);
% nwb.acquisition.set(sprintf('RawRecording%02d', i), Raw_Series);
% start_sample = start_sample + num_samples;
% end
%
% log_done();
%% Units
log_progress('Organising spike units');
num_clusters = length(hClust.spikesByCluster);
cluster_shape = [num_clusters 1];
spike_time_by_cluster = cell(cluster_shape);
for i = 1:num_clusters
spike_i = hClust.spikesByCluster{i};
spike_time_by_cluster{i} = hClust.spikeTimes(spike_i);
end
means = squeeze(hClust.meanWfLocalRaw(:, 1, :));
waveform_size = size(means, 1);
num_waveforms = size(means, 2);
means_per_cluster = mat2cell(means,...
waveform_size,...
ones(num_waveforms, 1));
% determine group ref based on sites
sites_per_cluster = hClust.clusterSites;
electrodes_per_cluster = types.untyped.ObjectView.empty;
Electrodes_Table = nwbData.general_extracellular_ephys_electrodes;
groups_per_site = Electrodes_Table.vectordata.get('group').data;
for i = length(sites_per_cluster)
site_i = sites_per_cluster(i);
electrodes_per_cluster(end+1) = groups_per_site(site_i);
end
Electrodes_Ref = struct(...
'data', {num2cell(hClust.clusterSites)},...
'table_path', electrodes_path);
Cluster_Data = struct(...
'spike_times', {spike_time_by_cluster},...
'electrode_group', electrodes_per_cluster,...
'electrodes', Electrodes_Ref,...
'notes', {hClust.clusterNotes},...
'waveform_mean', {means_per_cluster},...
'peak_to_peak', hClust.unitVpp);
if isprop(hClust, 'unitSNR')
Cluster_Data.signal_to_noise = hClust.unitSNR;
end
Cluster_Descriptions = struct(...
'spike_times', 'Spike times per cluster',...
'electrode_group', 'shank used',...
'electrodes', 'electrode site indices',...
'notes', 'cluster-specific notes',...
'waveform_mean', 'the spike waveform mean for each spike unit',...
'signal_to_noise', 'signal to noise ratio for each unit.',...
'peak_to_peak', 'Voltage peak to peak for this unit');
nwbData.units = types.core.Units('description', 'Spikes organized by Cluster');
nwbData.units = fill_dynamic_columns(nwbData.units, Cluster_Data, Cluster_Descriptions, '/units');
log_done();
%% WRITE
log_progress('Writing NWB file');
nwbExport(nwbData, outPath);
log_done();
end
%% TO_INDEXED_VECTOR converts cell array data, description, and index path into a Vector[Index/Data] pair.
% Return value is a struct containing 'data' -> VectorData and 'index' -> VectorIndex
function Vector = to_indexed_vector(data, description, index_path)
assert(iscell(data) && ~iscellstr(data), toMsgID('IndexedVector', 'InvalidArg'),...
'To make a regular vector data object, use to_vector instead.');
indices = cumsum(cellfun('length', data));
ref = types.untyped.ObjectView(index_path);
is_vertical = all(cellfun('size', data, 1) > 1);
if is_vertical
full_data = vertcat(data{:});
else
full_data = [data{:}];
end
Vector = struct(...
'data', to_vector(full_data, description),...
'index', types.core.VectorIndex('data', indices, 'target', ref));
end
%% TO_VECTOR converts data and description to valid VectorData or Vector[Index/Data] pair.
function Vector_Data = to_vector(data, description)
assert(~iscell(data) || iscellstr(data), toMsgID('DataVector', 'InvalidArg'),...
'To make an indexed vector data pair, use to_indexed_vector instead');
Vector_Data = types.core.VectorData('data', data, 'description', description);
end
%% TO_TABLE_REGION converts indices and h5_path to a DynamicTableRegion object
function Table_Region = to_table_region(indices, description, h5_path)
Table_Region = types.core.DynamicTableRegion(...
'data', indices,...
'description', description,...
'table', types.untyped.ObjectView(h5_path));
end
%% TO_ELECTRODE_TABLE converts a struct of column names and data with column data.
function Electrode_Table = to_electrode_table(Column_Data, varargin)
% ripped from NWB format since electrode table isn't an actual type
Descriptions = struct(...
'x', 'the x coordinate of the channel location',...
'y', 'the y coordinate of the channel location',...
'z', 'the z coordinate of the channel location',...
'imp', 'the impedance of the channel',...
'location', 'the location of channel within the subject e.g. brain region',...
'filtering', 'description of hardware filtering',...
'group', 'a reference to the ElectrodeGroup this electrode is a part of',...
'group_name', 'the name of the ElectrodeGroup this electrode is a part of');
if ~isempty(varargin)
Extra_Descriptions = varargin{1};
extra_fields = fieldnames(Extra_Descriptions);
for i = 1:length(extra_fields)
field = extra_fields{i};
Descriptions.(field) = Extra_Descriptions.(field);
end
end
Electrode_Table = types.core.DynamicTable('description', 'relevent electrodes in experiment');
Electrode_Table = fill_dynamic_columns(Electrode_Table, Column_Data, Descriptions);
end
%% FILL_DYNAMIC_COLUMNS given a DynamicTable or a subclass of DynamicTable, fills available column data
function Table = fill_dynamic_columns(Table, Column_Data, Column_Description, varargin)
error_stub = 'FillColumns';
if isempty(varargin)
ref_path = '';
else
ref_path = varargin{1};
end
assert(ischar(ref_path), toMsgID(error_stub, 'InvalidArgs'),...
'reference path must be a valid HDF5 path.');
column_names = fieldnames(Column_Data);
column_lengths = zeros(size(column_names));
for name_i = 1:length(column_names)
name = column_names{name_i};
data = Column_Data.(name);
description = Column_Description.(name);
is_table_region = isstruct(data);
if is_table_region
Region = data;
data = Region.data;
end
[Data, Vector_Index] = compose_column_data(name, data, description, ref_path);
if is_table_region
Data = to_table_region(Data.data, description, Region.table_path);
end
assign_to_table(Table, name, Data, Vector_Index);
end
table_height = unique(column_lengths);
assert(isscalar(table_height), toMsgID(error_stub, 'InvalidHeight'),...
'table columns must have the same length');
Table.colnames = column_names;
Table.id = types.core.ElementIdentifiers('data', 1:table_height);
function [Data, Index] = compose_column_data(name, data, description, ref_path)
is_indexed = iscell(data) && ~iscellstr(data);
if is_indexed
assert(~isempty(ref_path), toMsgID(error_stub, 'InvalidPath'),...
'Indexed data detected in column but reference path was not provided.');
full_ref_path = [ref_path '/' name];
Vector = to_indexed_vector(data, description, full_ref_path);
Data = Vector.data;
Index = Vector.index;
else
Data = to_vector(data, description);
Index = [];
end
end
function assign_to_table(Table, name, data, varargin)
if isprop(Table, name)
Table.(name) = data;
else
Table.vectordata.set(name, data);
end
if ~isempty(varargin) && ~isempty(varargin{1})
index = varargin{1};
index_name = [name '_index'];
if isprop(Table, index_name)
Table.(index_name) = index;
else
Table.vectorindex.set(index_name, index);
end
end
end
end
%% PROMPT_REQUIRED_INPUT creates a dialog asking the user to input data
% The return value is the inputted string data.
function input = prompt_required_input(query)
input = inputdlg(query);
assert(~isempty(input),...
toMsgID('Abort'),...
'Required input was canceled. Aborting export.');
input = input{1};
end
%% LOG_PROGRESS logs to command window. Completed with LOG_DONE
function log_progress(log)
fprintf('%s...\n', log);
end
%% LOG_DONE returns Done after a LOG_PROGRESS call
function log_done()
fprintf('\bDone!\n');
end
%% TO_MSG_ID returns proper filterable msg_id used in error, warning, assert, etc.
function msgID = toMsgID(varargin)
rootID = 'NwbExport';
if isempty(varargin) || ~iscellstr(varargin)
error(toMsgID('Internal', 'InvalidArg'),...
'arguments must be non-empty cell strings.');
end
msgID = strjoin([{rootID} varargin], ':');
end
%% BIN_TO_HDF5 utility function to move binary data files to HDF5 equivalent.
function External_Link = bin_to_hdf5(filename, shape, datatype)
[path, name, ~] = fileparts(filename);
destination = [fullfile(path, name) '.h5'];
fcpl = H5P.create('H5P_FILE_CREATE');
fapl = H5P.create('H5P_FILE_ACCESS');
h5_fid = H5F.create(destination,'H5F_ACC_TRUNC', fcpl, fapl);
H5P.close(fcpl);
H5P.close(fapl);
fid = fopen(filename);
h5_type = mat2h5_datatype(datatype);
h5_shape = fliplr(shape);
space_id = H5S.create_simple(length(shape), h5_shape, h5_shape);
dataset_id = H5D.create(h5_fid, '/data', h5_type, space_id, 'H5P_DEFAULT');
h5_count = zeros(length(shape),1);
stripe_length = shape(1);
h5_count(end) = stripe_length;
for dim_i = 2:length(shape)
factors = factor(shape(dim_i));
largest_factor = max(factors);
largest_selection = largest_factor^(sum(factors == largest_factor));
stripe_length = stripe_length * largest_selection;
h5_count(end - dim_i + 1) = largest_selection;
end
h5_start = zeros(length(shape), 1);
wait_bar = waitbar(0, 'Copying');
while ~feof(fid)
data = fread(fid, stripe_length, ['*' datatype]);
H5S.select_hyperslab(space_id, 'H5S_SELECT_SET', h5_start, [], h5_count, []);
mem_space_id = H5S.create_simple(1, stripe_length, stripe_length);
H5D.write(dataset_id, h5_type, mem_space_id, space_id, 'H5P_DEFAULT', data);
H5S.close(mem_space_id);
h5_start(1) = h5_start(1) + h5_count(1);
waitbar(h5_start(1) / h5_shape(1), wait_bar,...
sprintf('Copying %d/%d', h5_start(1), h5_shape(1)));
end
waitbar(1, 'Done');
H5S.close(space_id);
H5D.close(dataset_id);
H5F.close(h5_fid);
fclose(fid);
External_Link = types.untyped.ExternalLink(destination, '/data');
function h5_datatype = mat2h5_datatype(mat_datatype)
assert(startsWith(mat_datatype, {'int', 'uint'}),...
'bin_to_h5 currently only supports integer data types');
int_pattern = 'u?int(8|16|32|64)$';
type_width = regexp(mat_datatype, int_pattern, 'tokens', 'once');
assert(~isempty(type_width), 'invalid/unsupported datatype %s', mat_datatype);
if mat_datatype(1) == 'u'
unsigned_flag = 'U';
else
unsigned_flag = 'I';
end
h5_datatype = ['H5T_STD_' unsigned_flag type_width{1} 'LE'];
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
phy.m
|
.m
|
JRCLUST-main/+jrclust/+export/phy.m
| 7,408 |
utf_8
|
ba6c593290b356e7d5e4c522f8572f35
|
function phy(hClust)
%PHY Export JRCLUST data to .npy format for Phy
if exist('writeNPY', 'file') ~= 2
warning('Please make sure you have npy-matlab installed and on your path (https://github.com/kwikteam/npy-matlab)');
return;
elseif ~isa(hClust, 'jrclust.sort.DensityPeakClustering')
error('Phy export not supported for this type of clustering.');
end
hCfg = hClust.hCfg;
[nSites, ~, nSpikes] = size(hClust.spikeFeatures);
% spikeAmps/amplitudes
ampFile = fullfile(hCfg.outputDir, 'amplitudes.npy');
writeNPY(abs(hClust.spikeAmps), ampFile);
hCfg.updateLog('phy', sprintf('Saved spikeAmps to %s', ampFile), 0, 0);
% spikeTimes/spike_times
timeFile = fullfile(hCfg.outputDir, 'spike_times.npy');
writeNPY(uint64(hClust.spikeTimes), timeFile);
hCfg.updateLog('phy', sprintf('Saved spikeTimes to %s', timeFile), 0, 0);
% spikeSites/spike_sites (0 offset)
siteFile = fullfile(hCfg.outputDir, 'spike_sites.npy');
writeNPY(int32(hClust.spikeSites) - 1, siteFile); % -1 for zero indexing
hCfg.updateLog('phy', sprintf('Saved spikeSites to %s', siteFile), 0, 0);
% siteMap/channel_map (0 offset)
mapFile = fullfile(hCfg.outputDir, 'channel_map.npy');
writeNPY((int32(hCfg.siteMap) - 1)', mapFile); % -1 for zero indexing
hCfg.updateLog('phy', sprintf('Saved siteMap to %s', mapFile), 0, 0);
% siteLoc/channel_positions
locFile = fullfile(hCfg.outputDir, 'channel_positions.npy');
writeNPY(hCfg.siteLoc, locFile);
hCfg.updateLog('phy', sprintf('Saved siteLoc to %s', locFile), 0, 0);
% similar templates
simFile = fullfile(hCfg.outputDir, 'similar_templates.npy');
writeNPY(single(hClust.waveformSim), simFile);
hCfg.updateLog('phy', sprintf('Saved waveformSim to %s', simFile), 0, 0);
% template feature ind
tfiFile = fullfile(hCfg.outputDir, 'template_feature_ind.npy');
[~, argsort] = sort(hClust.waveformSim, 1);
tfi = argsort((hClust.nClusters-5):end, 1:end)';
writeNPY(uint32(tfi), tfiFile);
hCfg.updateLog('phy', sprintf('Saved template feature inds to %s', tfiFile), 0, 0);
% template features
tfFile = fullfile(hCfg.outputDir, 'template_features.npy');
% meanWfLocalRaw, spikesRaw
tf = zeros(hClust.nSpikes, 6, 'single');
for i = 1:hClust.nClusters
near = tfi(i, :);
iSpikes = hClust.spikesByCluster{i};
waves = reshape(hClust.spikesFilt(:, :, iSpikes), size(hClust.spikesFilt, 1)*size(hClust.spikesFilt, 2), numel(iSpikes));
for j = 1:numel(near)
wave_mu = reshape(hClust.meanWfLocal(:, :, j), 1, size(hClust.meanWfLocal, 1)*size(hClust.meanWfLocal,2));
template_features = (single(wave_mu)*single(waves))./(numel(wave_mu).*std(single(wave_mu)).*std(single(waves), [], 1));
tf(iSpikes,j)=template_features;
end
end
writeNPY(tf, tfFile);
hCfg.updateLog('phy', sprintf('Saved template features to %s', tfFile), 0, 0);
% templates (mwf)
templatesFile = fullfile(hCfg.outputDir, 'templates.npy');
templates = zeros(hClust.nClusters, diff(hClust.hCfg.evtWindowSamp) + 1, numel(hClust.siteRMS), 'single');
for i = 1:hClust.nClusters
templates(i, :, :) = hClust.meanWfGlobal(:, :, i)./max(max(abs(hClust.meanWfGlobal(:, :, i))))./max(max(abs(hClust.meanWfGlobal(:,:,i))));
end
writeNPY(templates, templatesFile);
hCfg.updateLog('phy', sprintf('Saved templates to %s', templatesFile), 0, 0);
% templates_ind (meaningless?)
tiFile = fullfile(hCfg.outputDir, 'templates_ind.npy');
nsites = numel(hClust.siteRMS);
templatesInd = zeros(hClust.nClusters,nsites);
for i = 1:hClust.nClusters
templatesInd(i, :, :) = (1:nsites) - 1;
end
writeNPY(templatesInd, tiFile);
hCfg.updateLog('phy', sprintf('Saved templates to %s', tiFile), 0, 0);
% spike_templates
stFile = fullfile(hCfg.outputDir, 'spike_templates.npy');
st = hClust.spikeClusters - 1;
st(st < 0) = 0;
writeNPY(uint32(st), stFile);
hCfg.updateLog('phy', sprintf('Saved templates to %s', stFile), 0, 0);
% whitening mat
wmFile = fullfile(hCfg.outputDir, 'whitening_mat.npy');
nsites = numel(hClust.siteRMS);
writeNPY(eye(nsites, nsites).*.4, wmFile);
hCfg.updateLog('phy', sprintf('Saved whitening mat to %s', wmFile), 0, 0);
% whitening mat inv
wmiFile = fullfile(hCfg.outputDir, 'whitening_mat_inv.npy');
nsites = numel(hClust.siteRMS);
writeNPY(eye(nsites, nsites).*.4, wmiFile);
hCfg.updateLog('phy', sprintf('Saved whitening mat inv to %s', wmiFile), 0, 0);
% spikeClusters/spike_clusters
spikeClusters = hClust.spikeClusters;
spikeClusters(spikeClusters < 0) = 0;
clusterFile = fullfile(hCfg.outputDir, 'spike_clusters.npy');
writeNPY(uint32(spikeClusters) - 1, clusterFile); % -1 for zero indexing
hCfg.updateLog('phy', sprintf('Saved spikeClusters to %s', clusterFile), 0, 0);
% write out PC features
if ismember(hCfg.clusterFeature, {'pca', 'gpca'})
% take just primary peak
spikeFeatures = squeeze(hClust.spikeFeatures(:, 1, :))'; % nSpikes x nFeatures
if hCfg.nPCsPerSite == 1
pcFeatures = reshape(spikeFeatures, size(spikeFeatures, 1), 1, []);
pcFeatures(:,2,:) = 0;
else
nSites = nSites/hCfg.nPCsPerSite;
pcFeatures = zeros(nSpikes, hCfg.nPCsPerSite, nSites, 'single');
for i = 1:hCfg.nPCsPerSite
pcFeatures(:, i, :) = spikeFeatures(:, ((i-1)*nSites+1):i*nSites);
end
end
featuresFile = fullfile(hCfg.outputDir, 'pc_features.npy');
writeNPY(pcFeatures, featuresFile);
hCfg.updateLog('phy', sprintf('Saved spikeFeatures to %s', featuresFile), 0, 0);
indFile = fullfile(hCfg.outputDir, 'pc_feature_ind.npy');
pfi = zeros(hClust.nClusters, nSites, 'uint32');
for i = 1:hClust.nClusters
pfi(i, :) = hCfg.siteNeighbors(1:nSites, hClust.clusterSites(i)) - 1; % - 1 for zero indexing
end
writeNPY(pfi, indFile);
hCfg.updateLog('phy', sprintf('Saved spikeFeature indices to %s', indFile), 0, 0);
end
% param file
if exist(fullfile(hCfg.outputDir, 'params.py'), 'file') ~= 2
paramFile = fullfile(hCfg.outputDir, 'params.py');
fid = fopen(paramFile, 'w');
rawRecordings = cellfun(@(x) sprintf('r''%s''', x), hCfg.rawRecordings, 'UniformOutput', 0);
rawRecordings = ['[' strjoin(rawRecordings, ', ') ']'];
fprintf(fid, 'dat_path = %s\n', rawRecordings);
fprintf(fid, 'n_channels_dat = %i\n', hCfg.nChans);
fprintf(fid, 'dtype = ''%s''\n', dtype2NPY(hCfg.dataType));
fprintf(fid, 'offset = %d\n', hCfg.headerOffset);
if hCfg.sampleRate ~= floor(hCfg.sampleRate)
fprintf(fid,'sample_rate = %i\n', hCfg.sampleRate);
else
fprintf(fid,'sample_rate = %i.\n', hCfg.sampleRate);
end
fprintf(fid,'hp_filtered = False');
fclose(fid);
hCfg.updateLog('phy', sprintf('Saved params to %s', paramFile), 0, 0);
end
end
%% LOCAL FUNCTIONS
function dtype = dtype2NPY(dtype)
switch dtype
case 'single'
dtype = 'float32';
case 'double'
dtype = 'float64';
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
plotFigMap.m
|
.m
|
JRCLUST-main/+jrclust/+views/plotFigMap.m
| 2,032 |
utf_8
|
0099e1d2529c7838cdb359201ba2cf50
|
function hFigMap = plotFigMap(hFigMap, hClust, hCfg, selected, channel_idx)
%PLOTFIGMAP Plot probe map
iWaveforms = hClust.meanWfGlobal(:, :, selected(1));
clusterVpp = squeeze(max(iWaveforms) - min(iWaveforms));
vpp = repmat(clusterVpp(:)', [4, 1]);
if ~hFigMap.hasAxes('default')
hFigMap.addAxes('default');
[XData, YData] = getAllCoordinates(hCfg);
hFigMap.addPlot('hPatch', @patch, XData, YData, vpp, 'EdgeColor', 'k', 'FaceColor', 'flat');
hFigMap.axApply('default', @colormap, 'hot');
hFigMap.addPlot('hText', @text, hCfg.siteLoc(:, 1), hCfg.siteLoc(:, 2), ...
arrayfun(@(i) num2str(i), channel_idx(1:hCfg.nSites), 'UniformOutput', 0), ...
'VerticalAlignment', 'bottom', ...
'HorizontalAlignment', 'left');
hFigMap.axApply('default', @xlabel, 'X Position (\mum)');
hFigMap.axApply('default', @ylabel, 'Y Position (\mum)');
else
hFigMap.plotApply('hPatch', @set, 'CData', vpp);
end
hFigMap.axApply('default', @title, sprintf('Unit %d; Max: %0.1f \\muVpp', selected(1), max(clusterVpp)));
hFigMap.axApply('default', @caxis, [0, max(clusterVpp)]);
% set limits
[XData, YData] = getSiteCoordinates(find(clusterVpp(:) ~= 0), hCfg);
hFigMap.axApply('default', @axis, [min(XData(:)) - hCfg.umPerPix, ...
max(XData(:)) + hCfg.umPerPix, ...
min(YData(:)) - hCfg.umPerPix, ...
max(YData(:)) + hCfg.umPerPix]);
end
%% LOCAL FUNCTIONS
function [XData, YData] = getSiteCoordinates(sites, hCfg)
xOffsets = [0 0 1 1] * hCfg.probePad(2);
yOffsets = [0 1 1 0] * hCfg.probePad(1);
XData = bsxfun(@plus, hCfg.siteLoc(sites, 1)', xOffsets(:));
YData = bsxfun(@plus, hCfg.siteLoc(sites, 2)', yOffsets(:));
end
function [XData, YData] = getAllCoordinates(hCfg)
[XData, YData] = getSiteCoordinates(1:hCfg.nSites, hCfg);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
plotFigProj.m
|
.m
|
JRCLUST-main/+jrclust/+views/plotFigProj.m
| 4,858 |
utf_8
|
5345f70e2051d3d1fd75c97079bc3ec1
|
function hFigProj = plotFigProj(hFigProj, hClust, sitesToShow, selected, boundScale, channel_idx, doAutoscale)
%PLOTFIGPROJ Plot feature projection figure
if nargin < 7
doAutoscale = 1;
end
hCfg = hClust.hCfg;
hFigProj.clearPlot('foreground2'); % clear secondary cluster spikes
if strcmp(hCfg.dispFeature, 'vpp')
XLabel = 'Site # (%0.0f \\muV; upper: V_{min}; lower: V_{max})';
YLabel = 'Site # (%0.0f \\muV_{min})';
elseif ismember(hCfg.dispFeature, {'template', 'pca', 'ppca'})
XLabel = sprintf('Site # (PC %d) (a.u.)', hCfg.pcPair(1));
YLabel = sprintf('Site # (PC %d) (a.u.)', hCfg.pcPair(2));
else
XLabel = sprintf('Site # (%%0.0f %s; upper: %s1; lower: %s2)', hCfg.dispFeature, hCfg.dispFeature, hCfg.dispFeature);
YLabel = sprintf('Site # (%%0.0f %s)', hCfg.dispFeature);
end
nSites = numel(sitesToShow);
if ~hFigProj.hasAxes('default')
hFigProj.addAxes('default');
hFigProj.axApply('default', @set, 'Position', [.1 .1 .85 .85], 'XLimMode', 'manual', 'YLimMode', 'manual');
hFigProj.addPlot('background', @line, nan, nan, 'Color', hCfg.colorMap(1, :));
hFigProj.addPlot('foreground', @line, nan, nan, 'Color', hCfg.colorMap(2, :)); % placeholder
hFigProj.addPlot('foreground2', @line, nan, nan, 'Color', hCfg.colorMap(3, :)); % placeholder
plotStyle = {'Marker', 'o', 'MarkerSize', 1, 'LineStyle', 'none'};
hFigProj.plotApply('background', @set, plotStyle{:});
hFigProj.plotApply('foreground', @set, plotStyle{:});
hFigProj.plotApply('foreground2', @set, plotStyle{:});
% plot boundary
hFigProj.addTable('hTable', [0, nSites], '-', 'Color', [.5 .5 .5]);
hFigProj.addDiag('hDiag', [0, nSites], '-', 'Color', [0 0 0], 'LineWidth', 1.5);
hFigProj.setHideOnDrag('background');
end
dispFeatures = getFigProjFeatures(hClust, sitesToShow, selected);
bgYData = dispFeatures.bgYData;
bgXData = dispFeatures.bgXData;
fgYData = dispFeatures.fgYData;
fgXData = dispFeatures.fgXData;
fg2YData = dispFeatures.fg2YData;
fg2XData = dispFeatures.fg2XData;
if doAutoscale
autoscalePct = hClust.hCfg.getOr('autoscalePct', 99.5)/100;
if numel(selected) == 1
projData = {fgYData, fgXData};
else
projData = {fgYData, fgXData, fg2YData, fg2XData};
end
if ~all(cellfun(@isempty, projData))
projData = cellfun(@(x) x(~isnan(x)), projData, 'UniformOutput', 0);
boundScale = max(cellfun(@(x) quantile(abs(x(:)), autoscalePct), projData));
end
end
% save scales for later
hFigProj.figData.initialScale = boundScale;
hFigProj.figData.boundScale = boundScale;
% plot background spikes
plotFeatures(hFigProj, 'background', bgYData, bgXData, boundScale, hCfg);
% plot foreground spikes
plotFeatures(hFigProj, 'foreground', fgYData, fgXData, boundScale, hCfg);
% plot secondary foreground spikes
if numel(selected) == 2
plotFeatures(hFigProj, 'foreground2', fg2YData, fg2XData, boundScale, hCfg);
figTitle = sprintf('Unit %d (black), Unit %d (red); (press [H] for help)', selected(1), selected(2));
else % or hide the plot
hFigProj.clearPlot('foreground2');
figTitle = sprintf('Unit %d (black); (press [H] for help)', selected(1));
hFigProj.figData.foreground2.XData = nan;
hFigProj.figData.foreground2.YData = nan;
end
% Annotate axes
hFigProj.axApply('default', @axis, [0 nSites 0 nSites]);
hFigProj.axApply('default', @set, 'XTick', 0.5:1:nSites, 'YTick', 0.5:1:nSites, ...
'XTickLabel', channel_idx(sitesToShow), 'YTickLabel', channel_idx(sitesToShow), ...
'Box', 'off');
hFigProj.axApply('default', @xlabel, sprintf(XLabel, boundScale));
hFigProj.axApply('default', @ylabel, sprintf(YLabel, boundScale));
hFigProj.axApply('default', @title, figTitle);
end
%% LOCAL FUNCTIONS
function plotFeatures(hFigProj, plotKey, featY, featX, boundScale, hCfg)
%PLOTFEATURES Plot features in a grid
if strcmp(hCfg.dispFeature, 'vpp')
bounds = boundScale*[0 1];
else
bounds = boundScale*[-1 1];
end
[XData, YData] = ampToProj(featY, featX, bounds, hCfg.nSiteDir, hCfg);
hFigProj.figData.(plotKey).XData = XData;
hFigProj.figData.(plotKey).YData = YData;
% subset features if plotting foreground
if strcmp(plotKey, 'foreground')
nSpikes = size(YData, 1);
subset = jrclust.utils.subsample(1:nSpikes, hCfg.nSpikesFigProj);
XData = XData(subset, :);
YData = YData(subset, :);
hFigProj.figData.foreground.subset = subset;
end
hFigProj.updatePlot(plotKey, XData(:), YData(:));
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
plotFigTraces.m
|
.m
|
JRCLUST-main/+jrclust/+views/plotFigTraces.m
| 8,160 |
utf_8
|
fbeb77a831e9f43002615fcabc32cef9
|
function tracesFilt = plotFigTraces(hFigTraces, hCfg, tracesRaw, resetAxis, hClust)
%PLOTFIGTRACES Plot raw traces view
hBox = jrclust.utils.qMsgBox('Plotting...', 0, 1);
hFigTraces.wait(1);
sampleRate = hCfg.sampleRate / hCfg.nSkip;
viSamples1 = 1:hCfg.nSkip:size(tracesRaw, 2);
evtWindowSamp = round(hCfg.evtWindowSamp / hCfg.nSkip); %show 2x of range
if strcmpi(hFigTraces.figData.filter, 'on')
% back up old settings
sampleRateOld = hCfg.sampleRate;
filterTypeOld = hCfg.filterType;
% temporarily alter settings to send traces through a filter
hCfg.sampleRate = sampleRate;
hCfg.useGPU = 0;
hCfg.filterType = hCfg.dispFilter;
if hCfg.fftThresh > 0
tracesRaw = jrclust.filters.fftClean(tracesRaw, hCft.fftThresh, hCfg);
end
tracesFilt = jrclust.filters.filtCAR(tracesRaw(:, viSamples1), [], [], 0, hCfg);
tracesFilt = jrclust.utils.bit2uV(tracesFilt, hCfg);
filterToggle = hCfg.filterType;
% restore old settings
hCfg.sampleRate = sampleRateOld;
hCfg.useGPU = 1;
hCfg.filterType = filterTypeOld;
else
tracesFilt = jrclust.utils.meanSubtract(single(tracesRaw(:, viSamples1))) * hCfg.bitScaling;
filterToggle = 'off';
end
if hCfg.nSegmentsTraces == 1
XData = ((hFigTraces.figData.windowBounds(1):hCfg.nSkip:hFigTraces.figData.windowBounds(end))-1) / hCfg.sampleRate;
XLabel = 'Time (s)';
else
XData = (0:(size(tracesFilt, 2) - 1)) / (hCfg.sampleRate / hCfg.nSkip) + (hFigTraces.figData.windowBounds(1)-1) / hCfg.sampleRate;
[multiBounds, multiRange, multiEdges] = jrclust.views.sampleSkip(hFigTraces.figData.windowBounds, hFigTraces.figData.nSamplesTotal, hCfg.nSegmentsTraces);
tlim_show = (cellfun(@(x) x(1), multiBounds([1, end]))) / hCfg.sampleRate;
XLabel = sprintf('Time (s), %d segments merged (%0.1f ~ %0.1f s, %0.2f s each)', hCfg.nSegmentsTraces, tlim_show, diff(hCfg.dispTimeLimits));
mrX_edges = XData(repmat(multiEdges(:)', [3, 1]));
mrY_edges = repmat([0; hCfg.nSites + 1; nan], 1, numel(multiEdges));
hFigTraces.plotApply('hEdges', @set, 'XData', mrX_edges(:), 'YData', mrY_edges(:));
csTime_bin = cellfun(@(x) sprintf('%0.1f', x(1)/hCfg.sampleRate), multiBounds, 'UniformOutput', 0);
hFigTraces.axApply('default', @set, {'XTick', 'XTickLabel'}, {XData(multiEdges), csTime_bin});
end
hFigTraces.multiplot('hPlot', hFigTraces.figData.maxAmp, XData, tracesFilt', 1:hCfg.nSites);
hFigTraces.axApply('default', @grid, hFigTraces.figData.grid);
hFigTraces.axApply('default', @set, 'YTick', 1:hCfg.nSites);
hFigTraces.axApply('default', @title, sprintf(hFigTraces.figData.title, hFigTraces.figData.maxAmp));
hFigTraces.axApply('default', @xlabel, XLabel);
hFigTraces.axApply('default', @ylabel, 'Site #');
hFigTraces.plotApply('hPlot', @set, 'Visible', hFigTraces.figData.traces);
% Delete spikes from other threads (TODO: break this out into a function)
plotKeys = keys(hFigTraces.hPlots);
chSpk = plotKeys(startsWith(plotKeys, 'chSpk'));
if ~isempty(chSpk)
cellfun(@(pk) hFigTraces.rmPlot(pk), chSpk);
end
% plot spikes
if strcmpi(hFigTraces.figData.spikes, 'on') && ~isempty(hClust)
recPos = find(strcmp(hFigTraces.figData.hRec.rawPath, hCfg.rawRecordings));
if recPos == 1
offset = 0;
else
% find all recordings coming before hRec and sum up nSamples
% for each
hRecs = arrayfun(@(iRec) jrclust.detect.newRecording(hCfg.rawRecordings{iRec}, hCfg), 1:(recPos-1), 'UniformOutput', 0);
offset = sum(cellfun(@(hR) hR.nSamples, hRecs));
end
recTimes = hClust.spikeTimes - uint64(offset);
tStart = single(hFigTraces.figData.windowBounds(1) - 1)/hCfg.sampleRate;
if hCfg.nSegmentsTraces > 1
spikesInRange = inRange(recTimes, multiBounds);
spikeSites = hClust.spikeSites(spikesInRange);
spikeTimes = double(recTimes(spikesInRange));
spikeTimes = round(whereMember(spikeTimes, multiRange) / hCfg.nSkip);
else
spikesInRange = recTimes >= hFigTraces.figData.windowBounds(1) & recTimes < hFigTraces.figData.windowBounds(end);
spikeSites = hClust.spikeSites(spikesInRange);
spikeTimes = double(recTimes(spikesInRange));
spikeTimes = round((spikeTimes - hCfg.sampleRate*tStart) / hCfg.nSkip); % time offset
end
spikeSites = single(spikeSites);
% check if clustered
if isempty(hClust)
for iSite = 1:hCfg.nSites % deal with subsample factor
onSite = find(spikeSites == iSite);
if isempty(onSite)
continue;
end
timesOnSite = spikeTimes(onSite);
[mrY11, mrX11] = vr2mr3_(tracesFilt(iSite, :), timesOnSite, evtWindowSamp); %display purpose x2
mrT11 = single(mrX11-1) / sampleRate + tStart;
plotKey = sprintf('chSpk%d', iSite);
hFigTraces.addPlot(plotKey, @line, ...
nan, nan, 'Color', [1 0 0], 'LineWidth', 1.5);
hFigTraces.multiplot(plotKey, hFigTraces.figData.maxAmp, mrT11, mrY11, iSite);
end
else % different color for each cluster
inRangeClusters = hClust.spikeClusters(spikesInRange);
spikeColors = [jet(hClust.nClusters); 0 0 0];
lineWidths = (mod((1:hClust.nClusters) - 1, 3) + 1)'/2 + 0.5; %(randi(3, S_clu.nClusters, 1)+1)/2;
% shuffle colors
spikeColors = spikeColors(randperm(size(spikeColors, 1)), :);
lineWidths = lineWidths(randperm(size(lineWidths, 1)), :);
nSpikes = numel(spikeTimes);
for iSpike = 1:nSpikes
iCluster = inRangeClusters(iSpike);
if iCluster <= 0
continue;
end
iTime = spikeTimes(iSpike);
iSite = spikeSites(iSpike);
iColor = spikeColors(iCluster, :);
iLinewidth = lineWidths(iCluster);
[mrY11, mrX11] = vr2mr3_(tracesFilt(iSite, :), iTime, evtWindowSamp); %display purpose x2
mrT11 = double(mrX11-1) / sampleRate + tStart;
plotKey = sprintf('chSpk%d', iSpike);
hFigTraces.addPlot(plotKey, @line, ...
nan, nan, 'Color', iColor, 'LineWidth', iLinewidth);
hFigTraces.multiplot(plotKey, hFigTraces.figData.maxAmp, mrT11, mrY11, iSite);
end
end
end
if resetAxis
jrclust.views.resetFigTraces(hFigTraces, tracesRaw, hCfg);
end
hFigTraces.figApply(@set, 'Name', sprintf('%s: filter: %s', hCfg.configFile, filterToggle));
hFigTraces.wait(0);
jrclust.utils.tryClose(hBox);
end
%% LOCAL FUNCTIONS
function isInRange = inRange(vals, ranges)
isInRange = false(size(vals));
if ~iscell(ranges)
ranges = {ranges};
end
for iRange = 1:numel(ranges)
bounds = ranges{iRange};
isInRange = isInRange | (vals >= bounds(1) & vals <= bounds(2));
end
end
function loc = whereMember(needle, haystack)
% needle = int32(needle); % ??
% haystack = int32(haystack); % ??
[~, loc] = ismember(int32(needle), int32(haystack));
end
function [mr, ranges] = vr2mr3_(traces, spikeTimes, evtWindow)
% JJJ 2015 Dec 24
% vr2mr2: quick version and doesn't kill index out of range
% assumes vi is within range and tolerates spkLim part of being outside
% works for any datatype
% prepare indices
spikeTimes = spikeTimes(:)';
ranges = int32(bsxfun(@plus, (evtWindow(1):evtWindow(end))', spikeTimes));
ranges(ranges < 1) = 1;
ranges(ranges > numel(traces)) = numel(traces); %keep # sites consistent
% build spike table
nSpikes = numel(spikeTimes);
mr = reshape(traces(ranges(:)), [], nSpikes);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
plotAuxCorr.m
|
.m
|
JRCLUST-main/+jrclust/+views/plotAuxCorr.m
| 5,406 |
utf_8
|
e6c6e367d0977e3822bffc05f1190406
|
function corrData = plotAuxCorr(hClust, selected)
%PLOTAUXCORR Plot aux channel correlation with firing rates figure
if nargin < 2
selected = [];
end
hCfg = hClust.hCfg;
% load aux channel data
[auxSamples, auxTimes] = loadAuxChannel(hCfg);
if isempty(auxSamples)
corrData = [];
jrclust.utils.qMsgBox('Aux input not found');
return;
end
% compute firing rates and correlate with the aux channel
firingRates = hClust.getFiringRates([], numel(auxSamples));
auxChanCorr = arrayfun(@(i) corr(auxSamples, firingRates(:, i), 'type', 'Pearson'), 1:size(firingRates, 2));
[~, argsort] = sort(auxChanCorr, 'descend');
nClustersShow = min(hCfg.nClustersShowAux, numel(auxChanCorr));
auxLabel = hCfg.getOr('auxLabel', 'aux');
nSubsamplesAux = hCfg.getOr('nSubsamplesAux', 100);
if ~isempty(selected)
nClustersShow = 1;
argsort = selected;
end
hFigAux = jrclust.views.Figure('FigAux', [.5 0 .5 1], hCfg.sessionName, 1, 1);
hTabGroup = hFigAux.figApply(@uitabgroup);
for iiCluster = 1:nClustersShow
iCluster = argsort(iiCluster);
hTab = uitab(hTabGroup, 'Title', sprintf('Unit %d', iCluster), 'BackgroundColor', 'w');
axes('Parent', hTab);
subplot(2, 1, 1);
hAx = plotyy(auxTimes, firingRates(:, iCluster), auxTimes, auxSamples);
xlabel('Time (s)');
ylabel(hAx(1),'Firing Rate (Hz)');
ylabel(hAx(2), auxLabel);
iSite = hClust.clusterSites(iCluster);
iTitle = sprintf('Unit %d (Site %d, Chan %d): Corr=%0.3f', iCluster, iSite, hCfg.siteMap(iSite), auxChanCorr(iCluster));
title(iTitle);
set(hAx, 'XLim', auxTimes([1,end]));
grid on;
subplot(2, 1, 2);
plot(auxSamples(1:nSubsamplesAux:end), firingRates(1:nSubsamplesAux:end,iCluster), 'k.');
xlabel(auxLabel);
ylabel('Firing Rate (Hz)');
grid on;
end
corrData = struct('firingRates', firingRates, ...
'auxSamples', auxSamples, ...
'auxChanCorr', auxChanCorr, ...
'auxTimes', auxTimes);
end
%% LOCAL FUNCTIONS
function [auxSamples, auxTimes] = loadAuxChannel(hCfg)
%LOADAUXCHANNEL Load the aux channel
[auxSamples, auxTimes] = deal([]);
if numel(hCfg.rawRecordings) > 1
jrclust.utils.qMsgBox('Multi-file mode is currently not supported');
return;
end
% try to guess auxFile
if isempty(hCfg.auxFile)
[~, ~, ext] = fileparts(hCfg.rawRecordings{1});
if strcmpi(ext, '.ns5')
try
hCfg.auxFile = jrclust.utils.subsExt(hCfg.rawRecordings{1}, '.ns2');
catch
return;
end
elseif ismember(lower(ext), {'.bin', '.dat'})
try
hCfg.auxFile = hCfg.rawRecordings{1};
catch
return;
end
else
return;
end
end
[~, ~, auxExt] = fileparts(hCfg.auxFile);
switch lower(auxExt)
% case '.ns2'
% auxChan = hCfg.getOr('auxChan', 1);
% [mnWav_aux, hFile_aux, auxData] = load_nsx_(hCfg.auxFile);
% scale_aux = hFile_aux.Entity(auxChan).Scale * hCfg.auxScale;
% vrWav_aux = single(mnWav_aux(auxChan,:)') * scale_aux;
% auxRate = auxData.sRateHz;
case '.mat'
auxData = load(hCfg.auxFile);
auxDataFields = fieldnames(auxData);
auxSamples = auxData.(auxDataFields{1});
auxRate = hCfg.getOr('auxRate', hCfg.sampleRate);
case {'.dat', '.bin'}
if isempty(hCfg.auxChan)
try % ask where it is
hCfg.auxFile = fullfile(hCfg.outputDir,uigetfile({'*.mat;*.csv'},...
'Select the Aux file',hCfg.outputDir));
catch
return;
end
end
try
hRec = jrclust.detect.newRecording(hCfg.auxFile, hCfg);
auxSamples = single(hRec.readRawROI(hCfg.auxChan, 1:hRec.nSamples))*hCfg.bitScaling*hCfg.auxScale;
auxRate = hCfg.getOr('auxRate', hCfg.sampleRate);
catch % data not from SpikeGLX
auxData = load(hCfg.auxFile); %load .mat file containing Aux data
auxDataFields = fieldnames(auxData);
auxRateFieldIdx= ~cellfun(@isempty, cellfun(@(fn) strfind(fn,'Rate') |...
strfind(fn,'sampling'), auxDataFields,'UniformOutput', false));
if any(auxRateFieldIdx) %there's a sampling rate field
auxSamples = auxData.(auxDataFields{~auxRateFieldIdx});
auxRate = auxData.(auxDataFields{auxRateFieldIdx});
else %load as usual
auxSamples = auxData.(auxDataFields{1});
auxRate = hCfg.getOr('auxRate', hCfg.sampleRate);
end
end
case '.csv'
auxSamples = load(hCfg.auxFile);
auxRate = hCfg.getOr('auxRate', hCfg.sampleRate);
otherwise
jrclust.utils.qMsgBox(sprintf('hCfg.auxFile: unsupported file format: %s\n', auxExt));
return;
end % switch
if nargout >= 2
auxTimes = single(1:numel(auxSamples))'/auxRate;
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
plotFigPos.m
|
.m
|
JRCLUST-main/+jrclust/+views/plotFigPos.m
| 3,173 |
utf_8
|
6015f33647d46b93b6b2e1b00de79a57
|
function plotFigPos(hFigPos, hClust, hCfg, selected, maxAmp)
%PLOTFIGPOS Plot position of cluster on probe
c1Data = hClust.exportUnitInfo(selected(1));
if numel(selected) > 1
c2Data = hClust.exportUnitInfo(selected(2));
end
if ~hFigPos.hasAxes('default')
hFigPos.addAxes('default');
else
hFigPos.axApply('default', @cla);
end
plotPosUnit(hFigPos, c1Data, hCfg, 0, maxAmp);
clusterPos = hClust.clusterCentroids(c1Data.cluster, :)/hCfg.umPerPix;
nSpikes = hClust.unitCount(c1Data.cluster);
if numel(selected) == 1
figTitle = sprintf('Unit %d: %d spikes; (X=%0.1f, Y=%0.1f) [um]', c1Data.cluster, nSpikes, clusterPos);
try
figTitle = sprintf('%s\n%0.1fuVmin, %0.1fuVpp, SNR:%0.1f ISI%%:%2.3f IsoDist:%0.1f L-rat:%0.1f', ...
figTitle, c1Data.peaksRaw, c1Data.vpp, c1Data.SNR, c1Data.ISIRatio*100, c1Data.IsoDist, c1Data.LRatio);
catch
end
else
nSpikes2 = hClust.unitCount(c2Data.cluster);
clusterPos2 = hClust.clusterCentroids(c2Data.cluster, :)/hCfg.umPerPix;
plotPosUnit(hFigPos, c2Data, hCfg, 1, maxAmp);
figTitle = sprintf('Unit %d(black)/%d(red); (%d/%d) spikes\n(X=%0.1f/%0.1f, Y=%0.1f/%0.1f) [um]', ...
c1Data.cluster, c2Data.cluster, nSpikes, nSpikes2, ...
[clusterPos(1), clusterPos2(1), clusterPos(2), clusterPos2(2)]);
end
hFigPos.axApply('default', @title, figTitle);
end
%% LOCAL FUNCTIONS
function plotPosUnit(hFigPos, cData, hCfg, fSecondary, maxAmp)
%PLOTPOSUNIT
if isempty(cData)
return;
end
if fSecondary
cmapMean = hCfg.colorMap(3, :); % red
else
cmapMean = hCfg.colorMap(2, :); % black
end
% plot individual unit
nSamples = size(cData.meanWf, 1);
XBase = (1:nSamples)'/nSamples;
XBase([1, end]) = nan; % line break
if fSecondary
sampleWf = zeros(1, 1, 0, 'single');
else
sampleWf = single(cData.sampleWf);
end
siteXData = hCfg.siteLoc(cData.neighbors, 1) / hCfg.umPerPix;
siteYData = hCfg.siteLoc(cData.neighbors, 2) / hCfg.umPerPix;
% show example traces
for iWav = size(sampleWf, 3):-1:0
if iWav == 0 % plot the cluster mean waveform
YData = cData.meanWf/maxAmp;
lineWidth = 1.5;
cmap = cmapMean;
else
YData = sampleWf(:,:,iWav) / maxAmp;
lineWidth = 0.5;
cmap = 0.5*[1, 1, 1];
end
YData = bsxfun(@plus, YData, siteYData');
XData = bsxfun(@plus, repmat(XBase, [1, size(YData, 2)]), siteXData');
hFigPos.addPlot(sprintf('neighbor%d%d', double(fSecondary) + 1, iWav), @line, XData(:), YData(:), ...
'Color', cmap, 'LineWidth', lineWidth);
end
hFigPos.axApply('default', @xlabel, 'X pos [pix]');
hFigPos.axApply('default', @ylabel, 'Z pos [pix]');
hFigPos.axApply('default', @grid, 'on');
hFigPos.axApply('default', @set, 'XLim', [min(siteXData), max(siteXData) + max(XBase)]);
hFigPos.axApply('default', @set, 'YLim', [floor(min(YData(:))-1), ceil(max(YData(:))+1)]);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
rescaleFigProj.m
|
.m
|
JRCLUST-main/+jrclust/+views/rescaleFigProj.m
| 4,444 |
utf_8
|
926ae507dda8b9082f199b3cd5d4e86e
|
function rescaleFigProj(hFigProj, projScale, hCfg)
%RESCALEFIGPROJ
rescaleUpdate(hFigProj, projScale, hCfg);
hFigProj.figData.boundScale = projScale;
if strcmp(hCfg.dispFeature, 'vpp')
XLabel = 'Site # (%0.0f \\muV; upper: V_{min}; lower: V_{max})';
YLabel = 'Site # (%0.0f \\muV_{min})';
elseif ~ismember(hCfg.dispFeature, {'kilosort', 'pca', 'gpca', 'ppca'})
XLabel = sprintf('Site # (%%0.0f %s; upper: %s1; lower: %s2)', hCfg.dispFeature, hCfg.dispFeature, hCfg.dispFeature);
YLabel = sprintf('Site # (%%0.0f %s)', hCfg.dispFeature);
end
if ~ismember(hCfg.dispFeature, {'kilosort', 'pca', 'gpca', 'ppca'})
hFigProj.axApply('default', @xlabel, sprintf(XLabel, projScale));
hFigProj.axApply('default', @ylabel, sprintf(YLabel, projScale));
end
end
%% LOCAL FUNCTIONS
function rescaleUpdate(hFigProj, projScale, hCfg)
% get ratio between plotted and stored values
s = hFigProj.figData.initialScale/projScale;
% rescale background features
bgXData = hFigProj.figData.background.XData(:);
xFloor = floor(bgXData);
if strcmp(hCfg.dispFeature, 'vpp')
bgXData = (bgXData - xFloor)*s;
else
% remap to [-1, 1] first, then scale, then map back to [0, 1]
bgXData = jrclust.utils.linmap(bgXData - xFloor, [0, 1], [-1, 1])*s;
bgXData = jrclust.utils.linmap(bgXData, [-1, 1], [0, 1]);
end
bgXData((bgXData <= 0 | bgXData >= 1)) = nan;
bgXData = bgXData + xFloor;
bgYData = hFigProj.figData.background.YData(:);
yFloor = floor(bgYData);
if strcmp(hCfg.dispFeature, 'vpp')
bgYData = (bgYData - yFloor)*s;
else
% remap to [-1, 1] first, then scale, then map back to [0, 1]
bgYData = jrclust.utils.linmap(bgYData - yFloor, [0, 1], [-1, 1])*s;
bgYData = jrclust.utils.linmap(bgYData, [-1, 1], [0, 1]);
end
bgYData((bgYData <= 0 | bgYData >= 1)) = nan;
bgYData = bgYData + yFloor;
hFigProj.updatePlot('background', bgXData, bgYData);
% rescale foreground features
subset = hFigProj.figData.foreground.subset; % just scale the plotted subset
fgXData = hFigProj.figData.foreground.XData(subset, :);
fgXData = fgXData(:);
xFloor = floor(fgXData);
if strcmp(hCfg.dispFeature, 'vpp')
fgXData = (fgXData - xFloor)*s;
else
% remap to [-1, 1] first, then scale, then map back to [0, 1]
fgXData = jrclust.utils.linmap(fgXData - xFloor, [0, 1], [-1, 1])*s;
fgXData = jrclust.utils.linmap(fgXData, [-1, 1], [0, 1]);
end
fgXData((fgXData <= 0 | fgXData >= 1)) = nan;
fgXData = fgXData + xFloor;
fgYData = hFigProj.figData.foreground.YData(subset, :);
fgYData = fgYData(:);
yFloor = floor(fgYData);
if strcmp(hCfg.dispFeature, 'vpp')
fgYData = (fgYData - yFloor)*s;
else
% remap to [-1, 1] first, then scale, then map back to [0, 1]
fgYData = jrclust.utils.linmap(fgYData - yFloor, [0, 1], [-1, 1])*s;
fgYData = jrclust.utils.linmap(fgYData, [-1, 1], [0, 1]);
end
fgYData((fgYData <= 0 | fgYData >= 1)) = nan;
fgYData = fgYData + yFloor;
hFigProj.updatePlot('foreground', fgXData, fgYData);
% rescale secondary foreground features
fg2XData = hFigProj.figData.foreground2.XData(:);
fg2YData = hFigProj.figData.foreground2.YData(:);
if ~all(isnan([fg2XData(:); fg2YData(:)]))
xFloor = floor(fg2XData);
if strcmp(hCfg.dispFeature, 'vpp')
fg2XData = (fg2XData - xFloor)*s;
else
% remap to [-1, 1] first, then scale, then map back to [0, 1]
fg2XData = jrclust.utils.linmap(fg2XData - xFloor, [0, 1], [-1, 1])*s;
fg2XData = jrclust.utils.linmap(fg2XData, [-1, 1], [0, 1]);
end
fg2XData((fg2XData <= 0 | fg2XData >= 1)) = nan;
fg2XData = fg2XData + xFloor;
yFloor = floor(fg2YData);
if strcmp(hCfg.dispFeature, 'vpp')
fg2YData = (fg2YData - yFloor)*s;
else
% remap to [-1, 1] first, then scale, then map back to [0, 1]
fg2YData = jrclust.utils.linmap(fg2YData - yFloor, [0, 1], [-1, 1])*s;
fg2YData = jrclust.utils.linmap(fg2YData, [-1, 1], [0, 1]);
end
fg2YData((fg2YData <= 0 | fg2YData >= 1)) = nan;
fg2YData = fg2YData + yFloor;
hFigProj.updatePlot('foreground2', fg2XData, fg2YData);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
plotFigPSD.m
|
.m
|
JRCLUST-main/+jrclust/+views/plotFigPSD.m
| 1,680 |
utf_8
|
20b31bccf1f950b9d64573bfa2911fe7
|
function hFigPSD = plotFigPSD(hFigPSD, tracesFilt, hCfg)
%PLOTFIGPSD Plot power spectrum density figure
nSmooth = 3;
ignoreSites = hCfg.ignoreSites;
sampleRate = hCfg.sampleRate/hCfg.nSkip;
%warning off;
tracesFilt = fft(tracesFilt');
tracesFilt = real(tracesFilt .* conj(tracesFilt)) / size(tracesFilt,1) / (sampleRate/2);
imid0 = ceil(size(tracesFilt, 1)/2);
vrFreq = (0:size(tracesFilt, 1) - 1)*(sampleRate/size(tracesFilt, 1));
vrFreq = vrFreq(2:imid0);
viChan = setdiff(1:size(tracesFilt,2), ignoreSites);
if size(tracesFilt, 2) > 1
vrPow = mean(tracesFilt(2:imid0,viChan), 2);
YLabel = 'Mean power across sites (dB uV^2/Hz)';
else
vrPow = tracesFilt(2:imid0, 1);
YLabel = 'Power on site (dB uV^2/Hz)';
end
vrPow = filterq_(ones([nSmooth, 1]), nSmooth, vrPow);
hFigPSD.addPlot('hFreq', vrFreq, jrclust.utils.pow2db(vrPow), 'k-');
% set(gca, 'YScale', 'log');
% set(gca, 'XScale', 'linear');
hFigPSD.axApply('default', @xlabel, 'Frequency (Hz)');
hFigPSD.axApply('default', @ylabel, YLabel);
% xlim_([0 sRateHz/2]);
hFigPSD.axApply('default', @grid, 'on');
try
hFigPSD.axApply('default', @xlim, vrFreq([1, end]));
hFigPSD.figApply(@set, 'Color', 'w');
catch
end
end
%% LOCAL FUNCTIONS
function mr = filterq_(vrA, vrB, mr)
% quick filter using single instead of filtfilt
% faster than filtfilt and takes care of the time shift
if numel(vrA) == 1
return;
end
if isempty(vrB)
vrB = sum(vrA);
end
mr = circshift(filter(vrA, vrB, mr, [], 1), -ceil(numel(vrA)/2), 1);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
multiplot.m
|
.m
|
JRCLUST-main/+jrclust/+views/@Figure/multiplot.m
| 2,480 |
utf_8
|
79bf8609e02fe4ad4d018dd3f78c7bde
|
function [plotKey, YOffsets] = multiplot(obj, plotKey, scale, XData, YData, YOffsets, doScatter)
% Create (nargin > 2) or rescale (nargin <= 2) a multi-line plot
% TODO: separate these (presumably multiple plots are passed in somewhere)
if nargin <= 2 % rescale
obj.rescalePlot(plotKey, scale);
% handle_fun_(@rescale_plot_, plotKey, scale);
YOffsets = [];
return;
end
if nargin < 7
doScatter = 0;
end
if isa(YData, 'gpuArray')
YData = gather(YData);
end
if isa(YData, 'int16')
YData = single(YData);
end
if nargin < 6
YOffsets = 1:size(YData, 2);
end
[plotKey, YOffsets] = doMultiplot(obj, plotKey, scale, XData, YData, YOffsets, doScatter);
end
%% LOCAL FUNCTIONS
function [plotKey, YOffsets] = doMultiplot(hFig, plotKey, scale, XData, YData, YOffsets, doScatter)
%DOMULTIPLOT Create a multi-line plot
shape = size(YData); % nSamples x nSites x (nSpikes)
userData = struct('scale', scale, ...
'shape', shape, ...
'yOffsets', YOffsets, ...
'fScatter', doScatter);
if doScatter % only for points that are not connected
XData = XData(:);
YData = YData(:)/scale + YOffsets(:);
elseif ismatrix(YData)
if isempty(XData)
XData = (1:shape(1))';
end
if isvector(XData)
XData = repmat(XData(:), [1, shape(2)]);
end
if size(XData,1) > 2
XData(end, :) = nan;
end
YData = bsxfun(@plus, YData/scale, YOffsets(:)');
else % 3D array
if isempty(XData)
XData = bsxfun(@plus, (1:shape(1))', shape(1)*(0:shape(3)-1));
elseif isvector(XData)
XData = repmat(XData(:), [1, shape(3)]);
end
if size(XData, 1) > 2
XData(end, :) = nan;
end
if isvector(YOffsets)
YOffsets = repmat(YOffsets(:), [1, shape(3)]);
end
XData = permute(repmat(XData, [1, 1, shape(2)]), [1,3,2]);
YData = YData / scale;
for iSpike = 1:shape(3)
YData(:, :, iSpike) = bsxfun(@plus, YData(:, :, iSpike), YOffsets(:, iSpike)');
end
end
if ~hFig.hasPlot(plotKey)
hFig.addPlot(plotKey, @line, XData(:), YData(:), 'UserData', userData);
else
hFig.updatePlot(plotKey, XData(:), YData(:), userData);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
getSpikeCov.m
|
.m
|
JRCLUST-main/+jrclust/+views/private/getSpikeCov.m
| 1,287 |
utf_8
|
12df2e13dc92edb948e83e1fe5999ba8
|
%function [mrVpp1, mrVpp2] = getSpikeCov(sampledSpikes, iSite)
function [mrVpp1, mrVpp2] = getSpikeCov(hClust, sampledSpikes, iSite)
%GETSPIKECOV Compute covariance feature for a subset of spikes
hCfg = hClust.hCfg;
spikeSites = hClust.spikeSites;
spikesFilt = hClust.spikesFilt;
nSpikes = numel(sampledSpikes);
sampledSites = spikeSites(sampledSpikes);
% nSamples x nSpikes x nSites
sampledWindows = single(permute(spikesFilt(:, :, sampledSpikes), [1, 3, 2]));
sampledWindows = jrclust.utils.tryGpuArray(sampledWindows, hCfg.useGPU);
[mrVpp1_, mrVpp2_] = jrclust.features.spikeCov(sampledWindows, hCfg);
mrVpp1_ = jrclust.utils.tryGather(abs(mrVpp1_));
mrVpp2_ = jrclust.utils.tryGather(abs(mrVpp2_));
% re-project to common basis
uniqueSites = unique(sampledSites);
[mrVpp1, mrVpp2] = deal(zeros([numel(iSite), nSpikes], 'like', mrVpp1_));
for jSite = 1:numel(uniqueSites)
site = uniqueSites(jSite);
neighbors = hCfg.siteNeighbors(:, site);
onSite = find(sampledSites == site);
[isNeigh, neighLocs] = ismember(neighbors, iSite);
mrVpp1(neighLocs(isNeigh), onSite) = mrVpp1_(isNeigh, onSite);
mrVpp2(neighLocs(isNeigh), onSite) = mrVpp2_(isNeigh, onSite);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
plotSpikeWaveforms.m
|
.m
|
JRCLUST-main/+jrclust/+views/private/plotSpikeWaveforms.m
| 2,829 |
utf_8
|
9aaea892f3aede5849ff38a799714028
|
function hFigWav = plotSpikeWaveforms(hFigWav, hClust, maxAmp, channel_idx)
%PLOTSPIKEWAVEFORMS Plot individual waveforms in the main view
showSubset = hFigWav.figData.showSubset;
[XData, YData, showSites] = deal(cell(numel(showSubset), 1));
hCfg = hClust.hCfg;
nSpikesCluster = zeros(numel(showSubset), 1);
siteNeighbors = hCfg.siteNeighbors(:, hClust.clusterSites);
for iiCluster = 1:numel(showSubset)
iCluster = showSubset(iiCluster);
try
iSpikes = jrclust.utils.subsample(hClust.getCenteredSpikes(iCluster), hCfg.nSpikesFigWav);
iSites = siteNeighbors(:, iCluster);
if hCfg.showRaw
if isempty(hClust.spikesRawVolt)
hClust.spikesRawVolt = jrclust.utils.rawTouV(hClust.spikesRaw, hCfg);
end
iWaveforms = hClust.spikesRawVolt(:, :, iSpikes);
iWaveforms = jrclust.filters.fftLowpass(iWaveforms, hCfg.getOr('fc_spkwav_show', []), hCfg.sampleRate);
else
if isempty(hClust.spikesFiltVolt)
hClust.spikesFiltVolt = jrclust.utils.filtTouV(hClust.spikesFilt, hCfg);
end
iWaveforms = hClust.spikesFiltVolt(:, :, iSpikes);
end
[YData{iiCluster}, XData{iiCluster}] = wfToPlot(iWaveforms, iiCluster, channel_idx(iSites), maxAmp, hCfg);
showSites{iiCluster} = iSites;
nSpikesCluster(iiCluster) = size(iWaveforms, 3);
catch ME
warning('Can''t plot cluster %d: %s', iCluster, ME.message);
end
end
userData = struct('showSites', showSites, 'nSpikesCluster', nSpikesCluster);
if hFigWav.hasPlot('hSpkAll')
hFigWav.updatePlot('hSpkAll', jrclust.utils.neCell2mat(XData), jrclust.utils.neCell2mat(YData), userData);
else
hFigWav.addPlot('hSpkAll', jrclust.utils.neCell2mat(XData), jrclust.utils.neCell2mat(YData), 'Color', [.5 .5 .5], 'LineWidth', .5, 'UserData', userData);
end
end
%% LOCAL FUNCTIONS
function [YData, XData] = wfToPlot(waveforms, iCluster, iSites, maxAmp, hCfg)
%WFTOPLOT Scale and translate waveforms by cluster ID and site
iCluster = double(iCluster);
if isempty(iSites)
iSites = 1:size(waveforms, 2);
end
nSpikes = size(waveforms, 3);
nSites = numel(iSites);
waveforms = single(waveforms) / maxAmp;
% orient waveforms in Y by which site they occur on
waveforms = waveforms + repmat(single(iSites(:)'), [size(waveforms, 1), 1, size(waveforms, 3)]);
waveforms([1, end], :, :) = nan;
YData = waveforms(:);
% x values are samples offset by cluster number
XData = jrclust.views.getXRange(iCluster, size(waveforms, 1), hCfg);
XData = repmat(XData(:), [1, nSites * nSpikes]);
XData = XData(:);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
plotMeanWaveforms.m
|
.m
|
JRCLUST-main/+jrclust/+views/private/plotMeanWaveforms.m
| 3,204 |
utf_8
|
439f9f8bfe5c1834ef41abbf66aaf8de
|
function hFigWav = plotMeanWaveforms(hFigWav, hClust, maxAmp, channel_idx)
%PLOTMEANWAVEFORMS Plot mean cluster waveforms in FigWav
hCfg = hClust.hCfg;
showSubset = hFigWav.figData.showSubset;
if hCfg.showRaw
waveforms = hClust.meanWfGlobalRaw;
else
waveforms = hClust.meanWfGlobal;
end
[nSamples, nSites, ~] = size(waveforms);
nClusters = numel(showSubset);
nSitesShow = size(hCfg.siteNeighbors, 1);
% determine x
if hCfg.showRaw
xOffset = hCfg.evtWindowRawSamp(2)/(diff(hCfg.evtWindowRawSamp) + 1);
else
xOffset = hCfg.evtWindowSamp(2)/(diff(hCfg.evtWindowSamp) + 1);
end
XData = (1:nSamples*nClusters)/nSamples + xOffset;
% breaks between clusters
XData(1:nSamples:end) = nan;
XData(nSamples:nSamples:end) = nan;
waveforms = waveforms/maxAmp;
XData = repmat(XData(:), [1, nSitesShow]);
XData = reshape(XData, [nSamples, nClusters, nSitesShow]);
XData = reshape(permute(XData, [1 3 2]), [nSamples*nSitesShow, nClusters]);
YData = zeros(nSamples * nSitesShow, nClusters, 'single');
for iiCluster = 1:nClusters
iCluster = showSubset(iiCluster);
iSites = hCfg.siteNeighbors(:, hClust.clusterSites(iCluster));
iWaveforms = waveforms(:, iSites, iCluster);
try
iWaveforms = bsxfun(@plus, iWaveforms, single(channel_idx(iSites)));
catch
iWaveforms = bsxfun(@plus, iWaveforms, single(channel_idx(iSites))');
end
YData(:, iiCluster) = iWaveforms(:);
end
if ~hFigWav.hasPlot('hGroup1')
plotGroup(hFigWav, XData, YData, 'LineWidth', hCfg.getOr('LineWidth', 1));
else
%updateGroup(hFigWav, XData, YData); % this is broken
plotKeys = keys(hFigWav.hPlots);
hGroup = plotKeys(startsWith(plotKeys, 'hGroup'));
if ~isempty(hGroup)
cellfun(@(plotKey) hFigWav.rmPlot(plotKey), hGroup);
end
plotGroup(hFigWav, XData, YData, 'LineWidth', hCfg.getOr('LineWidth', 1));
end
hFigWav.axApply('default', @set, 'YTick', 1:nSites, 'XTick', 1:nClusters);
end
%% LOCAL FUNCTIONS
function updateGroup(hFig, XData, YData)
%UPDATE Update group-plotted data
nGroups = sum(cellfun(@(c) ~isempty(c), regexp(keys(hFig.hPlots), '^hGroup\d')));
for iGroup = 1:numel(nGroups)
iXData = XData(:, iGroup:nGroups:end);
iYData = YData(:, iGroup:nGroups:end);
hFig.updatePlot(sprintf('hGroup%d', iGroup), iXData(:), iYData(:));
end
end
function plotGroup(hFig, XData, YData, varargin)
%PLOTGROUP Plot XData and YData colored by groups
colorMap = [0, 0.4470, 0.7410; 0.8500, 0.3250, 0.0980; 0.9290, 0.6940, 0.1250; 0.4940, 0.1840, 0.5560; 0.4660, 0.6740, 0.1880; 0.3010, 0.7450, 0.9330; 0.6350, 0.0780, 0.1840]';
nGroups = min(size(colorMap, 2), size(XData, 2));
colorMap = colorMap(:, 1:nGroups);
hFig.axApply('default', @hold, 'on');
for iGroup = 1:nGroups
iXData = XData(:, iGroup:nGroups:end);
iYData = YData(:, iGroup:nGroups:end);
hFig.addPlot(sprintf('hGroup%d', iGroup), iXData(:), iYData(:), varargin{:}, 'Color', colorMap(:, iGroup)');
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
getFigTimeFeatures.m
|
.m
|
JRCLUST-main/+jrclust/+views/private/getFigTimeFeatures.m
| 2,986 |
utf_8
|
39100e7576149d620cfe3faff4cc1187
|
function [dispFeatures, spikeTimesSecs, YLabel, dispSpikes] = getFigTimeFeatures(hClust, iSite, iCluster,channel_idx)
%GETFIGTIMEFEATURES Compute features to display in FigTime on iSite
if nargin < 3 % get features off of background spikes
iCluster = [];
channel_idx = 1:length(hClust.spikesBySite);
end
hCfg = hClust.hCfg;
[dispFeatures, dispSpikes] = getClusterFeaturesSite(hClust, iSite, iCluster);
spikeTimesSecs = double(hClust.spikeTimes(dispSpikes))/hCfg.sampleRate;
if nargout>2
if strcmp(hCfg.dispFeature, 'vpp')
YLabel = sprintf('Site %d (\\mu Vpp)', channel_idx(iSite));
else
YLabel = sprintf('Site %d (%s)', channel_idx(iSite), hCfg.dispFeature);
end
end
end
%% LOCAL FUNCTIONS
function [sampledFeatures, sampledSpikes] = getClusterFeaturesSite(hClust, iSite, iCluster)
%GETCLUSTERFEATURESSITE Get display features for a cluster or
%background spikes on iSite
MAX_SAMPLE = 10000; % max points to display
hCfg = hClust.hCfg;
spikeSites = hClust.spikeSites;
if isempty(iCluster) % select spikes based on sites
nSites = 1 + round(hCfg.nSiteDir);
neighbors = hCfg.siteNeighbors(1:nSites, iSite);
if isempty(hClust.spikesBySite)
sampledSpikes = find(ismember(spikeSites, neighbors));
else
sampledSpikes = jrclust.utils.neCell2mat(hClust.spikesBySite(neighbors)');
end
sampledSpikes = jrclust.utils.subsample(sampledSpikes, MAX_SAMPLE);
else % get all sites from the cluster
sampledSpikes = hClust.spikesByCluster{iCluster};
end
if strcmp(hCfg.dispFeature, 'vpp')
sampledWaveforms = squeeze(hClust.getSpikeWindows(sampledSpikes, iSite, 0, 1)); % use voltages
sampledFeatures = max(sampledWaveforms) - min(sampledWaveforms);
elseif strcmp(hCfg.dispFeature, 'cov')
sampledFeatures = getSpikeCov(hClust, sampledSpikes, iSite);
elseif strcmp(hCfg.dispFeature, 'pca') || (strcmp(hCfg.dispFeature, 'ppca') && isempty(iCluster)) % TODO: need a better mech for bg spikes
sampledWindows = permute(hClust.getSpikeWindows(sampledSpikes, iSite, 0, 0), [1, 3, 2]); % nSamples x nSpikes x nSites
prVecs1 = jrclust.features.getPVSpikes(sampledWindows);
sampledFeatures = jrclust.features.pcProjectSpikes(sampledWindows, prVecs1);
elseif strcmp(hCfg.dispFeature, 'ppca')
sampledWindows = permute(hClust.getSpikeWindows(sampledSpikes, iSite, 0, 0), [1, 3, 2]); % nSamples x nSpikes x nSites
prVecs1 = jrclust.features.getPVClusters(hClust, iSite, iCluster);
sampledFeatures = jrclust.features.pcProjectSpikes(sampledWindows, prVecs1);
elseif strcmp(hCfg.dispFeature, 'template')
sampledFeatures = hClust.templateFeaturesBySpike(sampledSpikes, iSite);
else
error('not implemented yet');
end
sampledFeatures = squeeze(abs(sampledFeatures));
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
doPlotFigPreview.m
|
.m
|
JRCLUST-main/+jrclust/+views/@PreviewController/private/doPlotFigPreview.m
| 7,560 |
utf_8
|
b060779a1e1a77b6bf1d99339da280f1
|
function hFigPreview = doPlotFigPreview(hFigPreview, figData, fKeepView, hCfg)
%DOPLOTFIGPREVIEW
hWait = jrclust.utils.qMsgBox('Plotting...', 0, 1);
nSites = size(figData.tracesFilt, 2);
XDataSamp = figData.windowBounds(1):figData.windowBounds(2);
XData = XDataSamp / hCfg.sampleRate;
tlimSecs = (figData.windowBounds + [-1 1]) / hCfg.sampleRate;
%% Mean plot
if ~hFigPreview.hasPlot('hPlotMean')
hFigPreview.addPlot('hPlotMean', @plot, hFigPreview.hAxes('hAxMean'), nan, nan, 'k');
hFigPreview.addPlot('hPlotMeanThresh', @plot, hFigPreview.hAxes('hAxMean'), nan, nan, 'r');
end
if strcmp(figData.refView, 'original')
YData = figData.tracesCAR(XDataSamp);
else % binned
YData = figData.channelMeansMAD(XDataSamp);
end
hFigPreview.plotApply('hPlotMean', @set, 'XData', XData, 'YData', YData);
hFigPreview.axApply('hAxMean', @set, 'YLim', [0, 100]);
hFigPreview.axApply('hAxMean', @xlabel, 'Time (sec)');
hFigPreview.axApply('hAxMean', @ylabel, sprintf('Common ref. (MAD, %s)', figData.refView));
fThreshRef = strcmpi(figData.refView, 'binned') && ~isempty(figData.blankThresh) && figData.blankThresh ~= 0;
if fThreshRef
hFigPreview.plotApply('hPlotMeanThresh', @set, 'XData', XData([1, end]), 'YData', repmat(figData.blankThresh, [1, 2]));
else
hFigPreview.clearPlot('hPlotMeanThresh');
end
hFigPreview.axApply('hAxMean', @grid, jrclust.utils.ifEq(figData.fGrid, 'on', 'off'));
%% Traces plot
if ~hFigPreview.hasPlot('hPlotTraces')
hFigPreview.addPlot('hPlotTraces', @plot, hFigPreview.hAxes('hAxTraces'), nan, nan, 'Color', [1 1 1]*.5);
hFigPreview.addPlot('hPlot_traces_spk', @plot, hFigPreview.hAxes('hAxTraces'), nan, nan, 'm.-', 'LineWidth', 1.5);
hFigPreview.addPlot('hPlot_traces_spk1', @plot, hFigPreview.hAxes('hAxTraces'), nan, nan, 'ro');
hFigPreview.addPlot('hPlotTracesThresh', @plot, hFigPreview.hAxes('hAxTraces'), nan, nan, 'm:');
hFigPreview.addPlot('hPlotTracesBad', @plot, hFigPreview.hAxes('hAxTraces'), nan, nan, 'r');
end
if figData.fFilter
hCfg.setTemporaryParams('filterType', figData.filterType);
traces = jrclust.utils.bit2uV(figData.tracesFilt(XDataSamp, :), hCfg);
hCfg.resetTemporaryParams();
else
traces = jrclust.utils.meanSubtract(single(figData.tracesClean(XDataSamp, :))*hCfg.bitScaling);
end
hFigPreview.multiplot('hPlotTraces', figData.maxAmp, XData, traces, 1:nSites);
% plot bad sites in red
if ~isempty(figData.ignoreSites)
hFigPreview.multiplot('hPlotTracesBad', figData.maxAmp, XData, traces(:, figData.ignoreSites), figData.ignoreSites);
else
hFigPreview.clearPlot('hPlotTracesBad');
end
if figData.fShowSpikes
inBounds = figData.spikeTimes >= figData.windowBounds(1) & figData.spikeTimes <= figData.windowBounds(end);
spikeTimes = single(figData.spikeTimes(inBounds) - figData.windowBounds(1)+1);
spikeTimesSec = single(figData.spikeTimes(inBounds)) / hCfg.sampleRate;
spikeSites = single(figData.spikeSites(inBounds));
else
spikeTimes = [];
end
if isempty(spikeTimes)
hFigPreview.clearPlot('hPlot_traces_spk1');
else
hFigPreview.multiplot('hPlot_traces_spk1', figData.maxAmp, spikeTimesSec, jrclust.utils.rowColSelect(traces, spikeTimes, spikeSites), spikeSites, 1);
end
hCfg.setTemporaryParams('filterType', figData.filterType);
siteThreshuV = jrclust.utils.bit2uV(-figData.siteThresh(:), hCfg);
hCfg.resetTemporaryParams();
siteThreshuV(figData.ignoreSites) = nan;
if figData.fShowThresh && figData.fFilter
hFigPreview.multiplot('hPlotTracesThresh', figData.maxAmp, XData([1,end,end])', repmat(siteThreshuV, [1, 3])');
hFigPreview.multiplot('hPlot_traces_spk', figData.maxAmp, XData, ...
mrSet(traces, ~figData.isThreshCrossing(XDataSamp, :), nan)); % show spikes
else
hFigPreview.clearPlot('hPlotTracesThresh');
hFigPreview.clearPlot('hPlot_traces_spk');
end
hFigPreview.axApply('hAxTraces', @ylabel, 'Site #');
filterLabel = jrclust.utils.ifEq(figData.fFilter, sprintf('Filter=%s', figData.filterType), 'Filter off');
hFigPreview.figApply(@set, 'Name', sprintf('%s; %s; CommonRef=%s', hCfg.configFile, filterLabel, figData.CARMode));
hFigPreview.axApply('hAxTraces', @title, sprintf('Scale: %0.1f uV', figData.maxAmp));
if ~fKeepView
hFigPreview.axApply('hAxTraces', @set, 'YTick', 1:nSites, 'YLim', figData.siteLim + [-1, 1], 'XLim', tlimSecs);
end
hFigPreview.axApply('hAxTraces', @grid, jrclust.utils.ifEq(figData.fGrid, 'on', 'off'));
%% Site plot
if ~hFigPreview.hasPlot('hPlotSite')
hFigPreview.addPlot('hPlotSite', @barh, hFigPreview.hAxes('hAxSites'), nan, nan, 1);
hFigPreview.addPlot('hPlotSiteBad', @barh, hFigPreview.hAxes('hAxSites'), nan, nan, 1, 'r');
hFigPreview.addPlot('hPlotSiteThresh', @plot, hFigPreview.hAxes('hAxSites'), nan, nan, 'r');
end
switch figData.siteView
case 'Site correlation'
YData = figData.maxCorrSite;
case 'Spike threshold'
YData = single(figData.siteThresh);
case 'Event rate (Hz)'
YData = figData.siteEventRate;
case 'Event SNR (median)'
YData = figData.siteEventSNR;
end % switch
hFigPreview.plotApply('hPlotSite', @set, 'XData', 1:nSites, 'YData', YData);
hFigPreview.axApply('hAxSites', @set, 'YLim', figData.siteLim + [-1,1]);
hFigPreview.axApply('hAxPSD', @grid, jrclust.utils.ifEq(figData.fGrid, 'on', 'off'));
if isempty(figData.siteCorrThresh) || ~strcmpi(figData.siteView, 'Site correlation')
hFigPreview.clearPlot('hPlotSiteThresh');
else
hFigPreview.plotApply('hPlotSiteThresh', @set, 'XData', figData.siteCorrThresh *[1,1], 'YData', [0, nSites+1]);
end
if ~isempty(figData.ignoreSites)
YData(~figData.ignoreMe) = 0;
hFigPreview.plotApply('hPlotSiteBad', @set, 'XData', 1:nSites, 'YData', YData); %switch statement
else
hFigPreview.clearPlot('hPlotSiteBad');
end
hFigPreview.axApply('hAxSites', @xlabel, figData.siteView);
hFigPreview.axApply('hAxSites', @ylabel, 'Site #');
hFigPreview.axApply('hAxSites', @title, sprintf('siteCorrThresh=%0.4f', figData.siteCorrThresh));
%% PSD plot
if ~hFigPreview.hasPlot('hPlotPSD')
hFigPreview.addPlot('hPlotPSD', @plot, hFigPreview.hAxes('hAxPSD'), nan, nan, 'k');
hFigPreview.addPlot('hPlotCleanPSD', @plot, hFigPreview.hAxes('hAxPSD'), nan, nan, 'g');
hFigPreview.addPlot('hPlotPSDThresh', @plot, hFigPreview.hAxes('hAxPSD'), nan, nan, 'r');
end
hFigPreview.plotApply('hPlotPSD', @set, 'XData', figData.psdFreq, 'YData', figData.psdPower);
hFigPreview.plotApply('hPlotCleanPSD', @set, 'XData', figData.psdFreq, 'YData', figData.psdPowerClean);
hFigPreview.axApply('hAxPSD', @set, 'XLim', [0, hCfg.sampleRate/2]);
hFigPreview.axApply('hAxPSD', @grid, jrclust.utils.ifEq(figData.fGrid, 'on', 'off'));
hFigPreview.axApply('hAxPSD', @xlabel, 'Frequency (Hz)');
hFigPreview.axApply('hAxPSD', @ylabel, 'Power [dB]');
hFigPreview.axApply('hAxPSD', @title, sprintf('fftThresh=%s', num2str(figData.fftThresh)));
%% finish up
hFigPreview.wait(0);
jrclust.utils.tryClose(hWait);
end
%% LOCAL FUNCTIONS
function mr = mrSet(mr, ml, val)
mr(ml) = val;
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
validateFigs.m
|
.m
|
JRCLUST-main/+jrclust/@Config/validateFigs.m
| 2,392 |
utf_8
|
31887f5f1d42704555bc87fa2f6bbf8d
|
function validateFigs(obj)
%% validates figure list and positions, and fills in with defaults if no positions specified
if ~isempty(obj.figPos)
if numel(obj.figList)~=numel(obj.figPos)
error('Error parsing params: size of figList does not match size of figPos in param file!');
end
else %% use default figure positions
obj.figPos = defaultFigPos(obj.figList);
end
%% add back in required figs if they are missing
requiredFigs = {'FigWav'};
if ~all(ismember(requiredFigs,obj.figList))
warnMsg = sprintf('"%s" will be used despite absence from user-defined figure list.\n',requiredFigs{:});
warndlg(warnMsg,'Missing required figure in "FigList" param');
for i = 1:length(requiredFigs)
if ~ismember(requiredFigs{i},obj.figList)
obj.figList = [obj.figList requiredFigs(i)];
obj.figPos = [obj.figPos defaultFigPos(requiredFigs{i})];
end
end
end
end
function figPos = defaultFigPos(figList)
figPos = cell(1, numel(figList));
hasFigRD = ismember('FigRD', figList);
for f=1:length(figList)
switch figList{f}
case 'FigCorr'
if hasFigRD
figPos{f} = [.85 .25 .15 .25];
else
figPos{f} = [.85 .2 .15 .27];
end
case 'FigHist'
if hasFigRD
figPos{f} = [.85 .75 .15 .25];
else
figPos{f} = [.85 .73 .15 .27];
end
case 'FigISI'
if hasFigRD
figPos{f} = [.85 .5 .15 .25];
else
figPos{f} = [.85 .47 .15 .26];
end
case 'FigMap'
figPos{f} = [0 .5 .15 .5];
case 'FigPos'
figPos{f} = [0 0 .15 .5];
case 'FigProj'
figPos{f} = [.5 .2 .35 .5];
case 'FigRD'
figPos{f} = [.85 0 .15 .25];
case 'FigSim'
figPos{f} = [.5 .7 .35 .3];
case 'FigTime'
if hasFigRD
figPos{f} = [.15 0 .7 .2];
else
figPos{f} = [.15 0 .85 .2];
end
case 'FigWav'
figPos{f} = [.15 .2 .35 .8];
end
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
readRawROI.m
|
.m
|
JRCLUST-main/+jrclust/+detect/@IntanRecording/readRawROI.m
| 2,990 |
utf_8
|
0920dff8a8582214747997d91b2eb85c
|
function roi = readRawROI(obj, rows, cols)
%READRAWROI Get a region of interest by rows/cols from the raw file
% How many data blocks remain in this file?
bytesRemaining = obj.fSizeBytes - obj.headerOffset;
dataPresent = (bytesRemaining > 0);
if (dataPresent)
if ~obj.rawIsOpen
obj.openRaw();
closeAfter = 1;
else
closeAfter = 0;
end
% Pre-allocate memory for data
roi = zeros(numel(rows), numel(cols), 'single');
blocks = floor((cols-1)/obj.nSamplesBlock) + 1;
uniqueBlocks = unique(blocks); % these will be sorted
blockOffsets = mod(cols, obj.nSamplesBlock);
blockOffsets(blockOffsets == 0) = obj.nSamplesBlock;
% go to just past the header
for iiBlock = 1:numel(uniqueBlocks)
iBlock = uniqueBlocks(iiBlock);
blockMask = (blocks == iBlock);
% seek to just past timestamps for this block
fseek(obj.rawFid, obj.headerOffset + (iBlock-1)*obj.nBytesBlock + 4*obj.nSamplesBlock, 'bof');
% read in all channels/samples for this block and subset
blockROI = fread(obj.rawFid, [obj.nSamplesBlock, obj.nChans], 'uint16')';
roi(:, blockMask) = 0.195 * (blockROI(rows, blockOffsets(blockMask)) - 32768);
end
if (obj.notchFilterFreq > 0)
for iChan = 1:obj.nChans
roi(iChan, :) = notchFilter(roi(iChan, :), obj.sampleRate, obj.notchFilterFreq, 10);
end
end
if closeAfter
obj.closeRaw();
end
else
roi = [];
end
end
function out = notchFilter(in, fSample, fNotch, Bandwidth)
% out = notch_filter(in, fSample, fNotch, Bandwidth)
%
% Implements a notch filter (e.g., for 50 or 60 Hz) on vector 'in'.
% fSample = sample rate of data (in Hz or Samples/sec)
% fNotch = filter notch frequency (in Hz)
% Bandwidth = notch 3-dB bandwidth (in Hz). A bandwidth of 10 Hz is
% recommended for 50 or 60 Hz notch filters; narrower bandwidths lead to
% poor time-domain properties with an extended ringing response to
% transient disturbances.
%
% Example: If neural data was sampled at 30 kSamples/sec
% and you wish to implement a 60 Hz notch filter:
%
% out = notch_filter(in, 30000, 60, 10);
tstep = 1/fSample;
Fc = fNotch*tstep;
L = length(in);
% Calculate IIR filter parameters
d = exp(-2*pi*(Bandwidth/2)*tstep);
b = (1 + d*d)*cos(2*pi*Fc);
a0 = 1;
a1 = -b;
a2 = d*d;
a = (1 + d*d)/2;
b0 = 1;
b1 = -2*cos(2*pi*Fc);
b2 = 1;
out = zeros(size(in));
out(1) = in(1);
out(2) = in(2);
% (If filtering a continuous data stream, change out(1) and out(2) to the
% previous final two values of out.)
% Run filter
for i=3:L
out(i) = (a*b2*in(i-2) + a*b1*in(i-1) + a*b0*in(i) - a2*out(i-2) - a1*out(i-1))/a0;
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
CARRealign.m
|
.m
|
JRCLUST-main/+jrclust/+detect/@DetectController/CARRealign.m
| 1,367 |
utf_8
|
cb6022177e6debe0e3fde9ae85ec13a2
|
function [spikeWindows, spikeTimes] = CARRealign(obj, spikeWindows, samplesIn, spikeTimes, neighbors)
%CARREALIGN Realign spike peaks after applying local CAR
if ~strcmpi(obj.hCfg.getOr('vcSpkRef', 'nmean'), 'nmean')
return;
end
% find where true peaks are not in the correct place after applying local CAR
spikeWindowsCAR = jrclust.utils.localCAR(single(spikeWindows), obj.hCfg);
[shiftMe, shiftBy] = findShifted(spikeWindowsCAR, obj.hCfg);
if isempty(shiftMe)
return;
end
% adjust spike times
shiftedTimes = spikeTimes(shiftMe) - int32(shiftBy(:));
spikeTimes(shiftMe) = shiftedTimes;
% extract windows at new shifted times
spikeWindows(:, shiftMe, :) = obj.extractWindows(samplesIn, shiftedTimes, neighbors, 0);
end
%% LOCAL FUNCTIONS
function [shiftMe, shiftBy] = findShifted(spikeWindows, hCfg)
%FINDSHIFTED
% spikeWindows: nSamples x nSpikes x nSites
peakLoc = 1 - hCfg.evtWindowSamp(1);
if hCfg.detectBipolar
[~, truePeakLoc] = max(abs(spikeWindows(:, :, 1)));
else
[~, truePeakLoc] = min(spikeWindows(:, :, 1));
end
shiftMe = find(truePeakLoc ~= peakLoc);
shiftBy = peakLoc - truePeakLoc(shiftMe);
shiftOkay = (abs(shiftBy) <= 2); % throw out drastic shifts
shiftMe = shiftMe(shiftOkay);
shiftBy = shiftBy(shiftOkay);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
cancelOverlap.m
|
.m
|
JRCLUST-main/+jrclust/+detect/@DetectController/cancelOverlap.m
| 3,671 |
utf_8
|
93eaafc502267ac1a0ffadd7c2b7b8d4
|
function [spikeWindowsOut, spikeWindows2Out] = cancelOverlap(obj, spikeWindows, spikeWindows2, spikeTimes, spikeSites, spikeSites2, siteThresh)
% Overlap detection. only return one stronger than other
[spikeTimes, spikeWindows, spikeWindows2] = jrclust.utils.tryGather(spikeTimes, spikeWindows, spikeWindows2);
[viSpk_ol_spk, vnDelay_ol_spk] = findPotentialOverlaps(spikeTimes, spikeSites, obj.hCfg);
[spikeWindowsOut, spikeWindows2Out] = deal(spikeWindows, spikeWindows2);
% find spike index that are larger and fit and deploy
viSpk_ol_a = find(viSpk_ol_spk>0); % later occuring
[viSpk_ol_b, vnDelay_ol_b] = deal(viSpk_ol_spk(viSpk_ol_a), vnDelay_ol_spk(viSpk_ol_a)); % first occuring
viTime_spk0 = int32(obj.hCfg.evtWindowSamp(1):obj.hCfg.evtWindowSamp(2));
siteThresh = jrclust.utils.tryGather(-abs(siteThresh(:))');
% for each pair identify time range where threshold crossing occurs and set to zero
% correct only first occuring (b)
nSpk_ol = numel(viSpk_ol_a);
nSpk = size(spikeWindows,2);
for iSpk_ol = 1:nSpk_ol
[iSpk_b, nDelay_b] = deal(viSpk_ol_b(iSpk_ol), vnDelay_ol_b(iSpk_ol));
viSite_b = obj.hCfg.siteNeighbors(:,spikeSites(iSpk_b));
mnWav_b = spikeWindowsOut(nDelay_b+1:end,:,iSpk_b);
mlWav_b = bsxfun(@le, mnWav_b, siteThresh(viSite_b));
mnWav_b(mlWav_b) = 0;
spikeWindowsOut(nDelay_b+1:end,:,iSpk_b) = mnWav_b;
if ~isempty(spikeWindows2)
viSite_b = obj.hCfg.siteNeighbors(:,spikeSites2(iSpk_b));
mnWav_b = spikeWindows2Out(nDelay_b+1:end,:,iSpk_b);
mlWav_b = bsxfun(@le, mnWav_b, siteThresh(viSite_b));
mnWav_b(mlWav_b) = 0;
spikeWindows2Out(nDelay_b+1:end,:,iSpk_b) = mnWav_b;
end
end
% set no overthreshold zone based on the delay, set it to half. only set superthreshold spikes to zero
end
%% LOCAL FUNCTIONS
function [viSpk_ol_spk, vnDelay_ol_spk] = findPotentialOverlaps(spikeTimes, spikeSites, hCfg)
%FINDPOTENTIALOVERLAPS
nSites = max(spikeSites);
spikesBySite = arrayfun(@(iSite) int32(find(spikeSites == iSite)), 1:nSites, 'UniformOutput', 0);
spikeTimes = jrclust.utils.tryGather(spikeTimes);
[viSpk_ol_spk, vnDelay_ol_spk] = deal(zeros(size(spikeSites), 'int32'));
for iSite = 1:nSites
spikesOnSite = spikesBySite{iSite}; % spikes occurring on this site
if isempty(spikesOnSite)
continue;
end
% get sites which are *near* iSite but not iSite
nearbySites = setdiff(jrclust.utils.findNearbySites(hCfg.siteLoc, iSite, hCfg.evtDetectRad), iSite);
nearbySpikes = jrclust.utils.neCell2mat(spikesBySite(nearbySites));
nSpikesOnSite = numel(spikesOnSite);
neighborSpikes = [spikesOnSite(:); nearbySpikes(:)]; % spikes in a neighborhood of iSite (includes iSite)
onSiteTimes = spikeTimes(spikesOnSite);
neighborTimes = spikeTimes(neighborSpikes);
% search over the event window for spikes occurring too close in
% space and time
for iDelay = 0:diff(hCfg.evtWindowSamp)
[isNearby, locNearby] = ismember(neighborTimes, onSiteTimes + iDelay);
if iDelay == 0
isNearby(1:nSpikesOnSite) = 0; % exclude same site comparison
end
isNearby = find(isNearby);
if isempty(isNearby)
continue;
end
viSpk1_ = spikesOnSite(locNearby(isNearby));
viSpk12_ = neighborSpikes(isNearby);
viSpk_ol_spk(viSpk12_) = viSpk1_;
vnDelay_ol_spk(viSpk12_) = iDelay;
end
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
detectOneRecording.m
|
.m
|
JRCLUST-main/+jrclust/+detect/@DetectController/detectOneRecording.m
| 11,552 |
utf_8
|
a78b2a2a8a35ba660050ef03e2014ee4
|
function recData = detectOneRecording(obj, hRec, fids, impTimes, impSites, siteThresh)
%DETECTONERECORDING Detect spikes in a single Recording
if nargin < 4
impTimes = [];
end
if nargin < 5
impSites = [];
end
if nargin < 6
siteThresh = [];
end
rawFid = fids(1);
filtFid = fids(2);
recData = struct('siteThresh', siteThresh(:), ...
'spikeTimes', int32([]), ...
'spikeAmps', cast([], obj.hCfg.dataType), ...
'spikeSites', int32([]), ...
'centerSites', int32([]), ...
'rawShape', [diff(obj.hCfg.evtWindowRawSamp) + 1, size(obj.hCfg.siteNeighbors, 1), 0], ...
'filtShape', [diff(obj.hCfg.evtWindowSamp) + 1, size(obj.hCfg.siteNeighbors, 1), 0], ...
'spikesFilt2', zeros(diff(obj.hCfg.evtWindowSamp) + 1, size(obj.hCfg.siteNeighbors, 1), 0), ...
'spikesFilt3', zeros(diff(obj.hCfg.evtWindowSamp) + 1, size(obj.hCfg.siteNeighbors, 1), 0), ...
'spikeFeatures', []);
% divide recording into many loads, samples are columns in data matrix
[nLoads, nSamplesLoad, nSamplesFinal] = obj.planLoad(hRec);
hRec.openRaw();
% precompute threshold for entire recording (requires 2 passes through data)
if obj.hCfg.getOr('precomputeThresh', 0)
samplesPre = [];
loadOffset = 0;
obj.hCfg.updateLog('precomputeThresh', 'Precomputing threshold', 1, 0);
for iLoad = 1:nLoads
obj.hCfg.updateLog('procLoad', sprintf('Processing load %d/%d', iLoad, nLoads), 1, 0);
if iLoad == nLoads
nSamples = nSamplesFinal;
else
nSamples = nSamplesLoad;
end
% load raw samples
iSamplesRaw = hRec.readRawROI(obj.hCfg.siteMap, 1+loadOffset:loadOffset+nSamples);
% convert samples to int16
iSamplesRaw = samplesToInt16(iSamplesRaw, obj.hCfg);
% load next N samples to ensure we don't miss any spikes at the boundary
if iLoad < nLoads && obj.hCfg.nSamplesPad > 0
leftBound = loadOffset + nSamples + 1;
rightBound = leftBound + obj.hCfg.nSamplesPad - 1;
samplesPost = hRec.readRawROI(obj.hCfg.siteMap, leftBound:rightBound);
samplesPost = samplesToInt16(samplesPost, obj.hCfg);
else
samplesPost = [];
end
% denoise and filter samples
obj.hCfg.updateLog('filtSamples', 'Filtering spikes', 1, 0);
iSamplesRaw = [samplesPre; iSamplesRaw; samplesPost];
if obj.hCfg.fftThresh > 0
iSamplesRaw = jrclust.filters.fftClean(iSamplesRaw, obj.hCfg.fftThresh, obj.hCfg);
end
% filter spikes; samples go in padded and come out padded
try
iSamplesFilt = jrclust.filters.filtCAR(iSamplesRaw, [], [], 0, obj.hCfg);
catch ME % GPU filtering failed, retry in CPU
obj.hCfg.updateLog('filtSamples', sprintf('GPU filtering failed: %s (retrying in CPU)', ME.message), 1, 0);
obj.hCfg.useGPU = 0;
iSamplesFilt = jrclust.filters.filtCAR(iSamplesRaw, [], [], 0, obj.hCfg);
end
% iSamplesFilt = obj.filterSamples(iSamplesRaw, samplesPre, samplesPost);
obj.hCfg.updateLog('filtSamples', 'Finished filtering spikes', 0, 1);
siteThresh = cat(1, siteThresh, obj.computeThreshold(iSamplesFilt));
nPadPre = size(samplesPre, 1);
nPadPost = size(samplesPost, 1);
bounds = [nPadPre + 1, size(iSamplesFilt, 1) - nPadPost]; % inclusive
success = hRec.writeFilt(iSamplesFilt(bounds(1):bounds(2), :));
if ~success % abort
siteThresh = [];
obj.hCfg.precomputeThresh = 0;
break;
end
if iLoad < nLoads
samplesPre = iSamplesRaw(end-2*obj.hCfg.nSamplesPad+1:end-obj.hCfg.nSamplesPad, :);
end
% increment sample offset
loadOffset = loadOffset + nSamples;
end
siteThresh = mean(siteThresh, 1);
if isempty(siteThresh)
obj.hCfg.updateLog('precomputeThresh', 'Failed to precompute threshold', 0, 1);
else % we made it, don't recompute filtered samples but read them in from disk
obj.hCfg.updateLog('precomputeThresh', 'Finished precomputing threshold', 0, 1);
hRec.closeFiltForWriting();
hRec.openFilt();
end
end
samplesPre = [];
loadOffset = 0;
for iLoad = 1:nLoads
obj.hCfg.updateLog('procLoad', sprintf('Processing load %d/%d', iLoad, nLoads), 1);
if iLoad == nLoads
nSamples = nSamplesFinal;
else
nSamples = nSamplesLoad;
end
% detect spikes in filtered samples
[iSpikeTimes, iSpikeSites] = deal([]);
if ~isempty(impTimes)
inInterval = (impTimes > loadOffset & impTimes <= loadOffset + nSamples);
iSpikeTimes = impTimes(inInterval) - loadOffset; % shift spike timing
% take sites assoc with times between limits
if ~isempty(impSites)
iSpikeSites = impSites(inInterval);
end
end
% if in import mode, only process loads where there are imported spikes.
if isempty(impTimes) || any(inInterval)
% load raw samples
iSamplesRaw = hRec.readRawROI(obj.hCfg.siteMap, 1+loadOffset:loadOffset+nSamples);
% convert samples to int16
iSamplesRaw = samplesToInt16(iSamplesRaw, obj.hCfg);
% load next N samples to ensure we don't miss any spikes at the boundary
if iLoad < nLoads && obj.hCfg.nSamplesPad > 0
leftBound = loadOffset + nSamples + 1;
rightBound = leftBound + obj.hCfg.nSamplesPad - 1;
samplesPost = hRec.readRawROI(obj.hCfg.siteMap, leftBound:rightBound);
samplesPost = samplesToInt16(samplesPost, obj.hCfg);
else
samplesPost = [];
end
nPadPre = size(samplesPre, 1);
nPadPost = size(samplesPost, 1);
% samples pre-filtered, read from disk
if obj.hCfg.getOr('precomputeThresh', 0)
obj.hCfg.updateLog('filtSamples', 'Reading filtered samples from disk', 1, 0);
iSamplesFilt = hRec.readFiltROI(1:obj.hCfg.nSites, 1+loadOffset-nPadPre:loadOffset+nSamples+nPadPost)';
obj.hCfg.updateLog('filtSamples', sprintf('Read %d filtered samples', size(iSamplesFilt, 1)), 0, 1);
% common mode rejection
if obj.hCfg.blankThresh > 0
channelMeans = jrclust.utils.getCAR(iSamplesFilt, obj.hCfg.CARMode, obj.hCfg.ignoreSites);
keepMe = jrclust.utils.carReject(channelMeans(:), obj.hCfg.blankPeriod, obj.hCfg.blankThresh, obj.hCfg.sampleRate);
obj.hCfg.updateLog('rejectMotion', sprintf('Rejecting %0.3f %% of time due to motion', (1 - mean(keepMe))*100), 0, 0);
else
keepMe = true(size(iSamplesFilt, 1), 1);
end
else
% denoise and filter samples
obj.hCfg.updateLog('filtSamples', 'Filtering samples', 1, 0);
[iSamplesFilt, keepMe] = obj.filterSamples(iSamplesRaw, samplesPre, samplesPost);
obj.hCfg.updateLog('filtSamples', 'Finished filtering samples', 0, 1);
end
%%% detect spikes
loadData = struct('samplesRaw', [samplesPre; iSamplesRaw; samplesPost], ...
'samplesFilt', iSamplesFilt, ...
'keepMe', keepMe, ...
'spikeTimes', iSpikeTimes, ...
'spikeSites', iSpikeSites, ...
'siteThresh', siteThresh, ...
'nPadPre', nPadPre, ...
'nPadPost', nPadPost);
% find peaks: adds spikeAmps, updates spikeTimes, spikeSites,
% siteThresh
loadData = obj.findPeaks(loadData);
if ~isempty(loadData.spikeTimes)
recData.spikeAmps = cat(1, recData.spikeAmps, loadData.spikeAmps);
recData.spikeSites = cat(1, recData.spikeSites, loadData.spikeSites);
recData.siteThresh = [recData.siteThresh, loadData.siteThresh];
% extract spike windows: adds centerSites, updates spikeTimes
loadData = obj.samplesToWindows(loadData);
recData.centerSites = cat(1, recData.centerSites, loadData.centerSites);
recData.spikeTimes = cat(1, recData.spikeTimes, loadData.spikeTimes + loadOffset - size(samplesPre, 1));
recData.spikesFilt2 = cat(3, recData.spikesFilt2, loadData.spikesFilt2);
recData.spikesFilt3 = cat(3, recData.spikesFilt3, loadData.spikesFilt3);
% write out spikesRaw and update shape
fwrite(rawFid, loadData.spikesRaw, '*int16');
if isempty(recData.rawShape)
recData.rawShape = size(loadData.spikesRaw);
else
recData.rawShape(3) = recData.rawShape(3) + size(loadData.spikesRaw, 3);
end
% write out spikesFilt and update shape
fwrite(filtFid, loadData.spikesFilt, '*int16');
if isempty(recData.filtShape)
recData.filtShape = size(loadData.spikesFilt);
else
recData.filtShape(3) = recData.filtShape(3) + size(loadData.spikesFilt, 3);
end
% compute features: adds spikeFeatures
if ~obj.hCfg.getOr('extractAfterDetect', 0)
loadData = obj.extractFeatures(loadData);
recData.spikeFeatures = cat(3, recData.spikeFeatures, loadData.spikeFeatures);
end
end
if iLoad < nLoads
samplesPre = iSamplesRaw(end-obj.hCfg.nSamplesPad+1:end, :);
end
jrclust.utils.tryGather(iSamplesFilt);
end
% increment sample offset
loadOffset = loadOffset + nSamples;
obj.hCfg.updateLog('procLoad', sprintf('Finished load %d/%d', iLoad, nLoads), 0, 1);
end % for
hRec.closeRaw();
hRec.closeFilt();
end
%% LOCAL FUNCTIONS
function samplesRaw = samplesToInt16(samplesRaw, hCfg)
%SAMPLESTOINT16 Convert samplesRaw to int16
switch(hCfg.dataType)
case 'uint16'
samplesRaw = int16(single(samplesRaw) - 2^15);
case {'single', 'double'}
samplesRaw = int16(samplesRaw / hCfg.bitScaling);
end
% flip the polarity
if hCfg.getOr('fInverse_file', 0)
samplesRaw = -samplesRaw;
end
if hCfg.tallSkinny
samplesRaw = samplesRaw';
else % Catalin's format (samples x channels)
if ~isempty(hCfg.loadTimeLimits)
nSamples = size(samplesRaw, 1);
lims = min(max(round(hCfg.loadTimeLimits * hCfg.sampleRate), 1), nSamples);
samplesRaw = samplesRaw(lims(1):lims(end), :);
end
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
planLoad.m
|
.m
|
JRCLUST-main/+jrclust/+detect/@DetectController/planLoad.m
| 1,885 |
utf_8
|
491d207b8c382accf6a037b00ccc6f4b
|
function [nLoads, nSamplesLoad, nSamplesFinal] = planLoad(obj, hRec)
%PLANLOAD Get number of samples to load in each chunk of a file
nBytesSubset = subsetBytes(hRec, obj.hCfg.loadTimeLimits*obj.hCfg.sampleRate);
bps = jrclust.utils.typeBytes(obj.hCfg.dataType);
% nColumns in data matrix
nSamples = floor(nBytesSubset / bps / obj.hCfg.nChans);
% if not constrained by user, try to compute maximum bytes/load
if isempty(obj.hCfg.maxBytesLoad)
if obj.hCfg.useGPU
S = gpuDevice(); % select first GPU device
nBytes = floor(S(1).TotalMemory/2); % take half of total memory
elseif ispc()
S = memory();
nBytes = floor(S.MaxPossibleArrayBytes);
else % no hints given, assume 8 GiB
nBytes = 2^33;
end
obj.hCfg.maxBytesLoad = floor(nBytes / obj.hCfg.gpuLoadFactor);
end
% if not constrained by user, try to compute maximum samples/load
if isempty(obj.hCfg.maxSecLoad)
nSamplesMax = floor(obj.hCfg.maxBytesLoad / obj.hCfg.nChans / bps);
else
nSamplesMax = floor(obj.hCfg.sampleRate * obj.hCfg.maxSecLoad);
end
if ~obj.hCfg.tallSkinny % load entire file, Catalin's format
[nLoads, nSamplesLoad, nSamplesFinal] = deal(1, nSamples, nSamples);
else
[nLoads, nSamplesLoad, nSamplesFinal] = jrclust.utils.partitionLoad(nSamples, nSamplesMax);
end
end
%% LOCAL FUNCTIONS
function nBytesLoad = subsetBytes(hRec, loadTimeLimits)
%SUBSETBYTES Get number of bytes to load from file, given time limits
nBytesLoad = hRec.fSizeBytes - hRec.headerOffset;
if isempty(loadTimeLimits)
return;
end
loadLimits = min(max(loadTimeLimits, 1), hRec.nSamples);
nSamplesLoad = diff(loadLimits) + 1;
nBytesLoad = nSamplesLoad * jrclust.utils.typeBytes(hRec.dataType) * hRec.nChans;
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
samplesToWindows.m
|
.m
|
JRCLUST-main/+jrclust/+detect/@DetectController/samplesToWindows.m
| 4,752 |
utf_8
|
abe22f3e7035a046248fb2c3c3130ebf
|
function spikeData = samplesToWindows(obj, spikeData)
%SAMPLESTOWINDOWS Get spatiotemporal windows around spiking events as 3D arrays
% returns spikesRaw nSamples x nSites x nSpikes
samplesRaw = spikeData.samplesRaw;
samplesFilt = spikeData.samplesFilt;
spikeTimes = spikeData.spikeTimes;
spikeSites = spikeData.spikeSites;
nSpikes = numel(spikeTimes);
nSitesEvt = 1 + obj.hCfg.nSiteDir*2; % includes ref sites
% tensors, nSamples{Raw, Filt} x nSites x nSpikes
spikesRaw = zeros(diff(obj.hCfg.evtWindowRawSamp) + 1, nSitesEvt, nSpikes, 'like', samplesRaw);
spikesFilt = zeros(diff(obj.hCfg.evtWindowSamp) + 1, nSitesEvt, nSpikes, 'like', samplesFilt);
% Realignment parameters
realignTraces = obj.hCfg.getOr('realignTraces', 0); % 0, 1, 2
spikeTimes = jrclust.utils.tryGpuArray(spikeTimes, obj.hCfg.useGPU);
spikeSites = jrclust.utils.tryGpuArray(spikeSites, obj.hCfg.useGPU);
% extractWindows returns nSamples x nSpikes x nSites
if isempty(spikeSites)
spikesRaw = permute(obj.extractWindows(samplesRaw, spikeTimes, [], 1), [1, 3, 2]);
spikesFilt = permute(obj.extractWindows(samplesFilt, spikeTimes, [], 0), [1, 3, 2]);
else
for iSite = 1:obj.hCfg.nSites
siteSpikes = find(spikeSites == iSite);
if isempty(siteSpikes)
continue;
end
siteTimes = spikeTimes(siteSpikes); % already sorted by time
neighbors = obj.hCfg.siteNeighbors(:, iSite);
try
spikeWindows = obj.extractWindows(samplesFilt, siteTimes, neighbors, 0);
if realignTraces == 1
[spikeWindows, siteTimes] = obj.CARRealign(spikeWindows, samplesFilt, siteTimes, neighbors);
spikeTimes(siteSpikes) = siteTimes;
elseif realignTraces == 2
spikeWindows = interpPeaks(spikeWindows, obj.hCfg);
end
spikesFilt(:, :, siteSpikes) = permute(spikeWindows, [1, 3, 2]);
spikesRaw(:, :, siteSpikes) = permute(obj.extractWindows(samplesRaw, siteTimes, neighbors, 1), [1, 3, 2]);
catch ME
obj.errMsg = ME.message;
obj.isError = 1;
end
end
end
% get windows around secondary/tertiary peaks as well
centerSites = spikeSites(:);
if obj.hCfg.nPeaksFeatures >= 2
[spikeSites2, spikeSites3] = obj.findSecondaryPeaks(spikesFilt, spikeSites);
spikesFilt2 = obj.samplesToWindows2(samplesFilt, spikeSites2, spikeTimes);
centerSites = [spikeSites(:) spikeSites2(:)];
else
spikesFilt2 = [];
end
if obj.hCfg.nPeaksFeatures == 3
spikesFilt3 = obj.samplesToWindows2(samplesFilt, spikeSites3, spikeTimes);
centerSites = [centerSites spikeSites3(:)];
else
spikesFilt3 = [];
end
if obj.hCfg.getOr('fCancel_overlap', 0)
try
[spikesFilt, spikesFilt2] = obj.cancelOverlap(spikesFilt, spikesFilt2, spikeTimes, spikeSites, spikeSites2, siteThresh);
catch ME
warning('Cancel overlap failed: %s', ME.message);
end
end
spikeData.spikesRaw = spikesRaw;
spikeData.spikesFilt = spikesFilt;
spikeData.spikeTimes = jrclust.utils.tryGather(spikeTimes);
spikeData.centerSites = jrclust.utils.tryGather(centerSites);
spikeData.spikesFilt2 = spikesFilt2;
spikeData.spikesFilt3 = spikesFilt3;
end
%% LOCAL FUNCTIONS
function spikeWindows = interpPeaks(spikeWindows, hCfg)
%INTERPPEAKS Interpolate waveforms to determine if true peaks are at subpixel locations
nInterp = 2; % interpolate at midpoint between each sample
% interpolate on just the primary site
spikeWindowsInterp = jrclust.utils.interpWindows(spikeWindows(:, :, 1), nInterp);
[~, interpPeaks] = min(spikeWindowsInterp);
peakLoc = 1 - hCfg.evtWindowSamp(1)*nInterp; % peak loc of waveform before interpolation
isRightShifted = find(interpPeaks == peakLoc + 1); % peak is subpixel right of given loc
isLeftShifted = find(interpPeaks == peakLoc - 1); % peak is subpixel left of given loc
% replace right-shifted peaks with their interpolated values
if ~isempty(isRightShifted)
rightShifted = jrclust.utils.interpWindows(spikeWindows(:, isRightShifted, :), nInterp);
spikeWindows(1:end-1, isRightShifted, :) = rightShifted(2:nInterp:end, :, :);
end
% replace left-shifted peaks with their interpolated values
if ~isempty(isLeftShifted)
leftShifted = jrclust.utils.interpWindows(spikeWindows(:, isLeftShifted, :), nInterp);
spikeWindows(2:end, isLeftShifted, :) = leftShifted(2:nInterp:end, :, :);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
bandpassFilter.m
|
.m
|
JRCLUST-main/+jrclust/+filters/bandpassFilter.m
| 4,286 |
utf_8
|
a4c38c6e1fcb0145d283a7999cf482fb
|
function samplesOut = bandpassFilter(samplesIn, hCfg)
%BANDPASSFILTER Summary of this function goes here
try
hCfg.updateLog('bpFilt', sprintf('Applying bandpass filter to %d samples', size(samplesIn, 1)), 1, 0);
samplesOut = filtfiltChain(single(samplesIn), hCfg);
catch ME
hCfg.updateLog('bpFilt', sprintf('GPU filtering failed: %s (retrying on CPU)', ME.message), 1, 0);
hCfg.useGPUFilt = 0;
samplesOut = filtfiltChain(single(samplesIn), hCfg);
end
hCfg.updateLog('bpFilt', 'Finished filtering', 0, 1);
samplesOut = int16(samplesOut);
end
%% LOCAL FUNCTIONS
function samplesIn = filtfiltChain(samplesIn, filtOpts)
%FILTFILTCHAIN Construct a filter chain
[cvrA, cvrB] = deal({});
if ~isempty(filtOpts.freqLimBP)
[cvrB{end+1}, cvrA{end+1}] = makeFilt_(filtOpts.freqLimBP, 'bandpass', filtOpts);
end
if ~isempty(filtOpts.freqLimStop)
[cvrB{end+1}, cvrA{end+1}] = makeFilt_(filtOpts.freqLimStop, 'stop', filtOpts);
end
if ~isempty(filtOpts.freqLimNotch)
if ~iscell(filtOpts.freqLimNotch)
[cvrB{end+1}, cvrA{end+1}] = makeFilt_(filtOpts.freqLimNotch, 'notch', filtOpts);
else
for iCell=1:numel(filtOpts.freqLimNotch)
[cvrB{end+1}, cvrA{end+1}] = makeFilt_(filtOpts.freqLimNotch{iCell}, 'notch', filtOpts);
end
end
end
%----------------
% Run the filter chain
fInt16 = isa(samplesIn, 'int16');
if filtOpts.useGPUFilt
samplesIn = gpuArray(samplesIn);
end
samplesIn = filt_pad_('add', samplesIn, filtOpts.nSamplesPad); % slow
if fInt16
samplesIn = single(samplesIn); % double for long data?
end
% first pass
for iFilt=1:numel(cvrA)
samplesIn = flipud(filter(cvrB{iFilt}, cvrA{iFilt}, ...
flipud(filter(cvrB{iFilt}, cvrA{iFilt}, samplesIn))));
end
if filtOpts.gainBoost ~= 1
samplesIn = samplesIn * filtOpts.gainBoost;
end
if fInt16
samplesIn = int16(samplesIn);
end
samplesIn = filt_pad_('remove', samplesIn, filtOpts.nSamplesPad); % slow
end
function [vrFiltB, vrFiltA] = makeFilt_(freqLimBP, vcType, filtOpts)
if nargin < 2
vcType = 'bandpass';
end
freqLimBP = freqLimBP / filtOpts.sampleRate * 2;
if ~strcmpi(vcType, 'notch')
if filtOpts.useElliptic % copied from wave_clus
if isinf(freqLimBP(1)) || freqLimBP(1) <= 0
[vrFiltB, vrFiltA]=ellip(filtOpts.filtOrder,0.1,40, freqLimBP(2), 'low');
elseif isinf(freqLimBP(2))
[vrFiltB, vrFiltA]=ellip(filtOpts.filtOrder,0.1,40, freqLimBP(1), 'high');
else
[vrFiltB, vrFiltA]=ellip(filtOpts.filtOrder,0.1,40, freqLimBP, vcType);
end
else
if isinf(freqLimBP(1)) || freqLimBP(1) <= 0
[vrFiltB, vrFiltA] = butter(filtOpts.filtOrder, freqLimBP(2),'low');
elseif isinf(freqLimBP(2))
[vrFiltB, vrFiltA] = butter(filtOpts.filtOrder, freqLimBP(1),'high');
else
[vrFiltB, vrFiltA] = butter(filtOpts.filtOrder, freqLimBP, vcType);
end
end
else
[vrFiltB, vrFiltA] = iirNotch(mean(freqLimBP), diff(freqLimBP));
end
if filtOpts.useGPUFilt
vrFiltB = gpuArray(vrFiltB);
vrFiltA = gpuArray(vrFiltA);
end
end
function mrWav = filt_pad_(vcMode, mrWav, nPad)
% add padding by reflection. removes artifact at the end
if isempty(nPad), return; end
if nPad==0, return; end
nPad = min(nPad, size(mrWav,1));
switch lower(vcMode)
case 'add'
mrWav = [flipud(mrWav(1:nPad,:)); mrWav; flipud(mrWav(end-nPad+1:end,:))];
case 'remove'
mrWav = mrWav(nPad+1:end-nPad,:);
end %switch
end
function [num,den] = iirNotch(Wo, BW)
% Define default values.
Ab = abs(10*log10(.5)); % 3-dB width
% Design a 2nd-order notch digital filter.
% Inputs are normalized by pi.
BW = BW*pi;
Wo = Wo*pi;
Gb = 10^(-Ab/20);
beta = (sqrt(1-Gb.^2)/Gb)*tan(BW/2);
gain = 1/(1+beta);
num = gain*[1 -2*cos(Wo) 1];
den = [1 -2*gain*cos(Wo) (2*gain-1)];
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
fftClean.m
|
.m
|
JRCLUST-main/+jrclust/+filters/fftClean.m
| 3,724 |
utf_8
|
3c1e907bb96551454cff286d2468d779
|
function samplesOut = fftClean(samplesIn, fftThresh, hCfg)
%FFTCLEAN Remove high-frequency noise from samples
if fftThresh == 0 || isempty(samplesIn)
samplesOut = samplesIn;
return;
end
hCfg.updateLog('fftClean', 'Applying FFT-based cleanup', 1, 0);
nSamples = size(samplesIn, 1); % total number of samples (rows) in array
[nLoads, nSamplesLoad, nSamplesFinal] = jrclust.utils.partitionLoad(nSamples, round(nSamples/hCfg.ramToGPUFactor));
samplesOut = zeros(size(samplesIn), 'like', samplesIn);
for iLoad = 1:nLoads
offset = (iLoad - 1)*nSamplesLoad;
if iLoad < nLoads
rows = offset + (1:nSamplesLoad);
else
rows = offset + (1:nSamplesFinal);
end
samplesOut_ = samplesIn(rows, :);
if hCfg.useGPU
try
samplesOut(rows, :) = doFFTClean(samplesOut_, fftThresh, 1);
catch ME
hCfg.updateLog('fftClean', sprintf('GPU FFT-based cleanup failed: %s (retrying in CPU)', ME.message), 1, 0);
samplesOut(rows, :) = doFFTClean(samplesOut_, fftThresh, 0);
end
else
samplesOut(rows, :) = doFFTClean(samplesOut_, fftThresh, 0);
end
end % for
hCfg.updateLog('fftClean', 'Finished FFT-based cleanup', 0, 1);
end
%% LOCAL FUNCTIONS
function samplesOut = doFFTClean(samplesIn, fftThresh, useGPU)
%DOFFTCLEAN Actually perform the FFT clean
nBins = 20;
nSkipMed = 4; % skip this many samples when estimating median
nw = 3; % frequency neighbors to set to zero
if fftThresh == 0 || isempty(fftThresh)
samplesOut = samplesIn;
return;
end
samplesIn = jrclust.utils.tryGpuArray(samplesIn, useGPU);
% get the next-largest power of 2 after nSamples (for padding)
nSamples = size(samplesIn, 1);
nSamplesPad = 2^nextpow2(nSamples);
samplesOut = single(samplesIn);
sampleMeans = mean(samplesOut, 1);
samplesOut = bsxfun(@minus, samplesOut, sampleMeans); % center the samples
if nSamples < nSamplesPad
samplesOut = fft(samplesOut, nSamplesPad);
else
samplesOut = fft(samplesOut);
end
% find frequency outliers
n1 = nSamplesPad/2; % previous power of 2
viFreq = (1:n1)';
vrFft = mean(bsxfun(@times, abs(samplesOut(1+viFreq,:)), viFreq), 2);
n2 = round(n1/nBins);
for iBin = 1:nBins
vi1 = (n2*(iBin - 1):n2*iBin) + 1;
if iBin == nBins
vi1(vi1 > n1) = [];
end
% MAD transform
vrFftMad = vrFft(vi1);
vrFftMad = vrFftMad - median(vrFftMad(1:nSkipMed:end));
vrFft(vi1) = vrFftMad / median(abs(vrFftMad(1:nSkipMed:end)));
end
% broaden spectrum
vrFft = jrclust.utils.tryGather(vrFft);
isNoise = vrFft > fftThresh;
vi_noise = find(isNoise);
for i_nw = 1:nw
viA = vi_noise - i_nw;
viA(viA < 1)=[];
viB = vi_noise + i_nw;
viB(viB > n1)=[];
isNoise(viA) = 1;
isNoise(viB) = 1;
end
vi_noise = find(isNoise);
samplesOut(1 + vi_noise, :) = 0;
samplesOut(end - vi_noise + 1, :) = 0;
% inverse transform back to the time domain
samplesOut = real(ifft(samplesOut, nSamplesPad, 'symmetric'));
if nSamples < nSamplesPad
samplesOut = samplesOut(1:nSamples,:);
end
samplesOut = bsxfun(@plus, samplesOut, sampleMeans); % add mean back in
% clean up GPU memory
[samplesIn, samplesOut, sampleMeans, vrFftMad] = jrclust.utils.tryGather(samplesIn, samplesOut, sampleMeans, vrFftMad); %#ok<ASGLU>
samplesOut = cast(samplesOut, jrclust.utils.trueClass(samplesIn)); % cast back to the original type
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
filtCAR.m
|
.m
|
JRCLUST-main/+jrclust/+filters/filtCAR.m
| 3,103 |
utf_8
|
e93c2eebae063b8fe89c0fe146e3e6b2
|
function [samplesOut, channelMeans] = filtCAR(samplesIn, windowPre, windowPost, trimPad, hCfg)
%FILTCAR Apply user-specified filter and common-average referencing
if nargin < 3
windowPre = [];
end
if nargin < 4
windowPost = [];
end
if nargin < 5
trimPad = 1;
end
nPadPre = size(windowPre, 1);
nPadPost = size(windowPost, 1);
samplesOut = [windowPre; samplesIn; windowPost];
if hCfg.useGPU
samplesOut = jrclust.utils.tryGpuArray(samplesOut, hCfg.useGPU);
end
% apply filter
if strcmp(hCfg.filterType, 'user')
samplesOut = jrclust.filters.userFilter(samplesOut, hCfg.userFiltKernel);
elseif strcmp(hCfg.filterType, 'fir1')
samplesOut = jrclust.filters.fir1Filter(samplesOut, ceil(5*hCfg.sampleRate/1000), 2*hCfg.freqLimBP/hCfg.sampleRate);
elseif strcmp(hCfg.filterType, 'ndiff')
samplesOut = jrclust.filters.ndiffFilter(samplesOut, hCfg.nDiffOrder);
elseif strcmp(hCfg.filterType, 'sgdiff')
samplesOut = jrclust.filters.sgFilter(samplesOut, hCfg.nDiffOrder);
elseif strcmp(hCfg.filterType, 'bandpass')
hCfg.useGPUFilt = hCfg.useGPU;
samplesOut = jrclust.filters.bandpassFilter(samplesOut, hCfg);
end
% trim padding
if trimPad && (nPadPre > 0 || nPadPost > 0)
samplesOut = samplesOut(nPadPre+1:end-nPadPost, :);
end
% global subtraction before
[samplesOut, channelMeans] = applyCAR(samplesOut, hCfg);
[samplesOut, channelMeans] = jrclust.utils.tryGather(samplesOut, channelMeans);
end
%% LOCAL FUNCTIONS
function [samplesIn, channelMeans] = applyCAR(samplesIn, hCfg)
%APPLYCAR Perform common average referencing (CAR) on filtered traces
channelMeans = [];
if strcmp(hCfg.CARMode, 'mean')
channelMeans = meanExcluding(samplesIn, hCfg.ignoreSites);
samplesIn = bsxfun(@minus, samplesIn, channelMeans);
elseif strcmp(hCfg.CARMode, 'median')
channelMeans = medianExcluding(samplesIn, hCfg.ignoreSites);
samplesIn = bsxfun(@minus, samplesIn, channelMeans);
end
samplesIn(:, hCfg.ignoreSites) = 0; % TW do not repair with fMeanSite_drift
end
function means = meanExcluding(samplesIn, ignoreSites)
%MEANEXCLUDING Calculate mean after excluding ignoreSites
if isempty(ignoreSites)
means = cast(mean(samplesIn, 2), 'like', samplesIn);
else
nSites = size(samplesIn, 2) - numel(ignoreSites);
means = cast((sum(samplesIn, 2) - sum(samplesIn(:, ignoreSites), 2)) / nSites, 'like', samplesIn); % TW BUGFIX
end
end
function medians = medianExcluding(samplesIn, ignoreSites)
%MEDIANEXCLUDING Calculate median after excluding ignoreSites
useGPU = isa(samplesIn, 'gpuArray');
if useGPU
samplesIn = jrclust.utils.tryGather(samplesIn);
end
if isempty(ignoreSites)
medians = median(samplesIn, 2);
else
goodSites = setdiff(1:size(samplesIn, 2), ignoreSites);
medians = median(samplesIn(:, goodSites), 2);
end
medians = jrclust.utils.tryGpuArray(medians, useGPU);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
sgFilter.m
|
.m
|
JRCLUST-main/+jrclust/+filters/sgFilter.m
| 1,863 |
utf_8
|
57c6f39308c6cc9dbc40ec77edf578f1
|
function samplesOut = sgFilter(samplesIn, nDiffOrder)
%SGFILTER Savitzky-Golay filter
% works for a vector, matrix and tensor
fInvert_filter = 0;
useGPU = isa(samplesIn, 'gpuArray');
n1 = size(samplesIn,1);
if n1 == 1
n1 = size(samplesIn,2);
end
if nDiffOrder == 0
samplesOut = samplesIn;
return;
end
[miA, miB] = sgfilt_init_(n1, nDiffOrder, useGPU);
if isvector(samplesIn)
samplesOut = samplesIn(miA(:,1)) - samplesIn(miB(:,1));
for i = 2:nDiffOrder
samplesOut = samplesOut + i * (samplesIn(miA(:,i)) - samplesIn(miB(:,i)));
end
elseif ismatrix(samplesIn)
samplesOut = samplesIn(miA(:,1),:) - samplesIn(miB(:,1),:);
for i = 2:nDiffOrder
samplesOut = samplesOut + i * (samplesIn(miA(:,i),:) - samplesIn(miB(:,i),:));
end
else
samplesOut = samplesIn(miA(:,1),:,:) - samplesIn(miB(:,1),:,:);
for i = 2:nDiffOrder
samplesOut = samplesOut + i * (samplesIn(miA(:,i),:,:) - samplesIn(miB(:,i),:,:));
end
end
end
%% LOCAL FUNCTIONS
function [miA, miB, viC] = sgfilt_init_(nData, nFilt, useGPU)
persistent miA_ miB_ viC_ nData_ nFilt_
if nargin<2, useGPU=0; end
% Build filter coeff
if isempty(nData_), nData_ = 0; end
try a = size(miA_); catch, nData_ = 0; end
if nData_ == nData && nFilt_ == nFilt
[miA, miB, viC] = deal(miA_, miB_, viC_);
else
vi0 = jrclust.utils.tryGpuArray(int32(1):int32(nData), useGPU)';
vi1 = int32(1):int32(nFilt);
miA = min(max(bsxfun(@plus, vi0, vi1),1),nData);
miB = min(max(bsxfun(@plus, vi0, -vi1),1),nData);
viC = jrclust.utils.tryGpuArray(int32(-nFilt:nFilt), useGPU);
[nData_, nFilt_, miA_, miB_, viC_] = deal(nData, nFilt, miA, miB, viC);
end
end %func
|
github
|
JaneliaSciComp/JRCLUST-main
|
computeSelfSim.m
|
.m
|
JRCLUST-main/+jrclust/+interfaces/@Clustering/computeSelfSim.m
| 1,963 |
utf_8
|
c0ec76440bed5c89992c760f91c4aeef
|
function selfSim = computeSelfSim(obj, iCluster)
%COMPUTESELFSIM Get similarity between bottom and top half (vpp-wise) of cluster
if nargin < 2
iCluster = [];
end
if isempty(iCluster)
obj.hCfg.updateLog('selfSim', 'Computing cluster self-similarity', 1, 0);
selfSim = zeros(1, obj.nClusters);
for iCluster = 1:obj.nClusters
selfSim(iCluster) = iSelfSim(obj, iCluster);
end
obj.hCfg.updateLog('selfSim', 'Finished computing cluster self-similarity', 0, 1);
else
selfSim = iSelfSim(obj, iCluster);
end
end
%% LOCAL FUNCTIONS
function selfSim = iSelfSim(hClust, iCluster)
%ISELFSIM Kernel of the self-similarity method (for a given cluster)
% low means bad. return 1-corr score
MAX_SAMPLE = 4000;
clusterSpikes_ = hClust.getCenteredSpikes(iCluster);
clusterSpikes_ = jrclust.utils.subsample(clusterSpikes_, MAX_SAMPLE);
centeredWf = hClust.spikesRaw(:, :, clusterSpikes_);
centeredVpp = squeeze(squeeze(max(centeredWf(:, 1, :)) - min(centeredWf(:, 1, :))));
[~, argsort] = sort(centeredVpp);
imid = round(numel(argsort)/2);
% compute correlation between low-vpp waveforms and high-vpp waveforms
% only on spikes occurring on the center site
lowHalf = jrclust.utils.meanSubtract(mean(centeredWf(:, :, argsort(1:imid)), 3));
highHalf = jrclust.utils.meanSubtract(mean(centeredWf(:, :, argsort(imid+1:end)), 3));
selfSim = colZScore(lowHalf(:), highHalf(:));
end
function C = colZScore(X, Y)
% https://stackoverflow.com/questions/9262933/what-is-a-fast-way-to-compute-column-by-column-correlation-in-matlab
% compute Z-scores for columns of X and Y
X = bsxfun(@minus, X, mean(X)); % zero-mean
X = bsxfun(@times, X, 1./sqrt(sum(X.^2))); %% L2-normalization
Y = bsxfun(@minus, Y, mean(Y)); % zero-mean
Y = bsxfun(@times, Y, 1./sqrt(sum(Y.^2))); %% L2-normalization
C = X' * Y;
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
computeCentroids.m
|
.m
|
JRCLUST-main/+jrclust/+interfaces/@Clustering/computeCentroids.m
| 2,238 |
utf_8
|
0bd8fad34dc0910e79a27ed64624e352
|
function computeCentroids(obj, updateMe)
%COMPUTEPOSITIONS determine cluster position from spike position
if nargin < 2 || isempty(obj.clusterCentroids)
updateMe = [];
end
if isempty(updateMe)
centroids = zeros(obj.nClusters, 2);
clusters_ = 1:obj.nClusters;
else % selective update
centroids = obj.clusterCentroids;
clusters_ = updateMe(:)';
end
featureSites = 1:obj.hCfg.nSitesEvt;
for iCluster = clusters_
[clusterSpikes, neighbors] = subsampleCenteredSpikes(obj, iCluster);
if isempty(clusterSpikes)
continue;
end
neighbors = neighbors(1:end-obj.hCfg.nSitesExcl);
featureWeights = squeeze(obj.spikeFeatures(featureSites, 1, clusterSpikes));
neighborLoc = single(obj.hCfg.siteLoc(neighbors, :)); % position on probe
centroids(iCluster, 1) = median(getWeightedLoc(featureWeights, neighborLoc(:, 1)));
centroids(iCluster, 2) = median(getWeightedLoc(featureWeights, neighborLoc(:, 2)));
end
obj.clusterCentroids = centroids;
end
%% LOCAL FUNCTIONS
function [clusterSpikes, neighbors] = subsampleCenteredSpikes(hClust, iCluster)
%SUBSAMPLECENTEREDSPIKES Subsample spikes from the requested cluster centered at the center site and mid-time range (drift)
nSamplesMax = 1000;
% subselect based on the center site
clusterSpikes = hClust.spikesByCluster{iCluster};
if isempty(clusterSpikes)
neighbors = [];
return;
end
iClusterSite = hClust.clusterSites(iCluster);
centeredSpikes = (hClust.spikeSites(clusterSpikes) == iClusterSite);
neighbors = hClust.hCfg.siteNeighbors(:, iClusterSite);
clusterSpikes = clusterSpikes(centeredSpikes);
if isempty(clusterSpikes)
return;
end
clusterSpikes = jrclust.utils.subsample(clusterSpikes, nSamplesMax);
end
function weightedLoc = getWeightedLoc(featureWeights, positions)
%GETWEIGHTEDLOC Get feature-weighted location of clusters from positions
if isrow(positions)
positions = positions';
end
featureWeights = featureWeights.^2;
sos = sum(featureWeights);
weightedLoc = sum(bsxfun(@times, featureWeights, positions))./sos;
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
syncHistFile.m
|
.m
|
JRCLUST-main/+jrclust/+interfaces/@Clustering/syncHistFile.m
| 2,931 |
utf_8
|
c02defe25fbf50b4e2b9a81a3af53162
|
function syncHistFile(obj)
%SYNCHISTFILE Sync up history file with current history
d = dir(obj.hCfg.histFile);
if isempty(d) || obj.nSpikes == 0 % file does not exist
fclose(fopen(obj.hCfg.histFile, 'w')); % truncate history file
d = dir(obj.hCfg.histFile);
end
if obj.nSpikes == 0
return;
end
nEntries = d.bytes / 4 / (obj.nSpikes + 1); % int32 spike table plus header
if nEntries ~= ceil(nEntries) % non-integer number of "entries", likely corrupt file
obj.history = resetHistFile(obj.hCfg.histFile, obj.initialClustering, obj.spikeClusters, obj.nEdits);
elseif nEntries > obj.nEdits % more edits in file than in stored history, pare file down to match history
keepMe = cell2mat(keys(obj.history));
mm = memmapfile(obj.hCfg.histFile, 'Format', {'int32', [obj.nSpikes + 1 nEntries], 'Data'}, 'Writable', true);
editKeys = mm.Data.Data(1, :);
iKeepMe = ismember(editKeys, keepMe);
if ~jrclust.utils.isEqual(find(iKeepMe), 1:sum(iKeepMe))
% take the subset of entries we want to keep...
mm.Data.Data(:, 1:obj.nEdits) = mm.Data.Data(:, iKeepMe);
end
clear mm; % flush changes and close
% ...and truncate the file after this
java.io.RandomAccessFile(obj.hCfg.histFile, 'rw').setLength(4 * obj.nEdits * (obj.nSpikes + 1));
elseif nEntries < obj.nEdits % more edits in stored history than in file, consolidate edits
obj.history = resetHistFile(obj.hCfg.histFile, obj.initialClustering, obj.spikeClusters, obj.nEdits);
elseif nEntries > 0
fidHist = fopen(obj.hCfg.histFile, 'r');
fRes = 0;
while fRes > -1
checkInt = fread(fidHist, 1, 'int32');
if isempty(checkInt) % EOF
fRes = -1;
break
elseif ~isKey(obj.history, checkInt)
break;
end
fRes = fseek(fidHist, 4*obj.nSpikes, 'cof');
end
fclose(fidHist);
if fRes == 0 % checkInt failed
obj.history = resetHistFile(obj.hCfg.histFile, obj.initialClustering, obj.spikeClusters, obj.nEdits);
end
end
obj.editPos = obj.nEdits;
end
%% LOCAL FUNCTIONS
function history = resetHistFile(histFile, initialClustering, spikeClusters, nEdits)
history = containers.Map('KeyType', 'int32', 'ValueType', 'char');
fidHist = fopen(histFile, 'w');
if nEdits > 0
% write initial clustering
history(1) = 'initial commit';
fwrite(fidHist, int32(1), 'int32');
fwrite(fidHist, int32(initialClustering), 'int32');
if any(spikeClusters ~= initialClustering)
history(2) = 'update clustering';
fwrite(fidHist, int32(2), 'int32');
fwrite(fidHist, int32(spikeClusters), 'int32');
end
end % otherwise truncate file
fclose(fidHist);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
computeWaveformSim.m
|
.m
|
JRCLUST-main/+jrclust/+interfaces/@Clustering/computeWaveformSim.m
| 6,092 |
utf_8
|
dd9869f7e8cc0a044e267181d0040c28
|
function computeWaveformSim(obj, updateMe)
%COMPUTWAVEFORMSIM Compute waveform-based similarity scores for all clusters
if nargin < 2 || isempty(obj.waveformSim)
updateMe = [];
end
if isempty(obj.meanWfGlobal)
return;
end
% these guys are not in the default param set, but can be overridden if you really want
usePeak2 = obj.hCfg.getOr('fUsePeak2', 1);
useRaw = obj.hCfg.getOr('fWavRaw_merge', 0); % TW
fZeroStart_raw = obj.hCfg.getOr('fZeroStart_raw', 0);
fRankCorr_merge = obj.hCfg.getOr('fRankCorr_merge', 0);
fMode_cor = obj.hCfg.getOr('fMode_cor', 1); % 0: Pearson, 1: non mean-subtracted Pearson
obj.hCfg.updateLog('wfCorr', 'Computing waveform correlation', 1, 0);
if useRaw
meanWfGlobal_ = trimRawWaveforms(obj.meanWfGlobalRaw, obj.hCfg);
else
meanWfGlobal_ = obj.meanWfGlobal;
end
if obj.hCfg.driftMerge && useRaw % only works on raw
meanWfRawLow_ = trimRawWaveforms(obj.meanWfRawLow, obj.hCfg);
meanWfRawHigh_ = trimRawWaveforms(obj.meanWfRawHigh, obj.hCfg);
meanWfSet = {meanWfGlobal_, meanWfRawLow_, meanWfRawHigh_};
else
meanWfSet = {meanWfGlobal_};
end
if fZeroStart_raw
meanWfSet = cellfun(@(x) zeroStart(x), meanWfSet, 'UniformOutput', 0);
end
if fRankCorr_merge
meanWfSet = cellfun(@(x) rankorderMatrix(x), meanWfSet, 'UniformOutput', 0);
end
if obj.hCfg.meanInterpFactor > 1
meanWfSet = cellfun(@(x) jrclust.utils.interpWindows(x, obj.hCfg.meanInterpFactor), meanWfSet, 'UniformOutput', 0);
end
if usePeak2
[peaks1, peaks2, peaks3] = obj.getSecondaryPeaks();
clusterSites_ = {peaks1, peaks2, peaks3};
else
clusterSites_ = {obj.clusterSites};
end
waveformSim = zeros(size(meanWfGlobal_, 3), 'like', obj.waveformSim);
% shift waveforms up to some multiple (meanInterpFactor) of the refractory period
nShifts = ceil(obj.hCfg.meanInterpFactor*obj.hCfg.refracInt*obj.hCfg.sampleRate/1000);
[cviShift1, cviShift2] = jrclust.utils.shiftRange(int32(size(meanWfGlobal_, 1)), nShifts);
scoreData = struct('cviShift1', {cviShift1}, ...
'cviShift2', {cviShift2}, ...
'fMode_cor', fMode_cor);
if isempty(updateMe) % update everything
useParfor = 1;
scoreData.updateMe = true(obj.nClusters, 1);
scoreData.simScoreOld = [];
else
useParfor = 0;
scoreData.updateMe = false(obj.nClusters, 1);
scoreData.updateMe(updateMe) = 1;
scoreData.simScoreOld = obj.waveformSim;
scoreData.updateMe((1:obj.nClusters) > size(scoreData.simScoreOld, 1)) = 1;
end
if useParfor
% avoid sending the entire hCfg object out to workers
cfgSub = struct('siteNeighbors', obj.hCfg.siteNeighbors, ...
'siteLoc', obj.hCfg.siteLoc, ...
'evtMergeRad', obj.hCfg.evtMergeRad, ...
'autoMergeBy', obj.hCfg.autoMergeBy);
nClusters_ = obj.nClusters;
try
parfor iCluster = 1:nClusters_
pwCor = unitWaveformSim(meanWfSet, clusterSites_, cfgSub, scoreData, iCluster);
if ~isempty(pwCor)
waveformSim(:, iCluster) = pwCor;
end
end
catch ME
warning('computeWaveformSim: parfor failed');
useParfor = 0;
end
end
if ~useParfor
for iCluster = 1:obj.nClusters
pwCor = unitWaveformSim(meanWfSet, clusterSites_, obj.hCfg, scoreData, iCluster);
if ~isempty(pwCor)
waveformSim(:, iCluster) = pwCor;
end
end
end
waveformSim = max(waveformSim, waveformSim'); % make it symmetric
obj.hCfg.updateLog('wfCorr', 'Finished computing waveform correlation', 0, 1);
if isempty(updateMe)
waveformSim = jrclust.utils.setDiag(waveformSim, obj.computeSelfSim());
else
% carry over the old diagonal
waveformSim = jrclust.utils.setDiag(waveformSim, diag(obj.waveformSim));
for ii = 1:numel(updateMe)
iCluster = updateMe(ii);
waveformSim(iCluster, iCluster) = obj.computeSelfSim(iCluster);
end
end
%waveformSim(waveformSim == 0) = nan;
obj.waveformSim = waveformSim;
end
%% LOCAL FUNCTIONS
function mi = rankorderMatrix(meanWf)
%RANKORDERMATRIX
if isrow(meanWf)
meanWf = meanWf';
end
shape = size(meanWf);
if numel(shape) == 3
meanWf = meanWf(:); % global order
end
mi = zeros(size(meanWf));
for iCol = 1:size(meanWf, 2)
col = meanWf(:, iCol);
pos = find(col > 0);
if ~isempty(pos)
[~, argsort] = sort(col(pos), 'ascend');
mi(pos(argsort), iCol) = 1:numel(pos);
end
neg = find(col < 0);
if ~isempty(neg)
[~, argsort] = sort(col(neg), 'descend');
mi(neg(argsort), iCol) = -(1:numel(neg));
end
end
if numel(shape) == 3
mi = reshape(mi, shape);
end
end
function meanWf = trimRawWaveforms(meanWf, hCfg)
%TRIMRAWWAVEFORMS Pare raw waveforms down to the size of filtered waveforms
nSamplesRaw = diff(hCfg.evtWindowRawSamp) + 1;
spkLimMerge = round(hCfg.evtWindowSamp * hCfg.evtWindowMergeFactor);
nSamplesRawMerge = diff(spkLimMerge) + 1;
if size(meanWf, 1) <= nSamplesRawMerge
return;
end
limits = [spkLimMerge(1) - hCfg.evtWindowRawSamp(1) + 1, ...
nSamplesRaw - (hCfg.evtWindowRawSamp(2) - spkLimMerge(2))];
meanWf = meanWf(limits(1):limits(2), :, :);
meanWf = jrclust.utils.meanSubtract(meanWf);
end
function meanWf = zeroStart(meanWf)
%ZEROSTART Subtract the first row from all rows
shape = size(meanWf);
if numel(shape) ~= 2
meanWf = reshape(meanWf, shape(1), []);
end
meanWf = bsxfun(@minus, meanWf, meanWf(1, :));
if numel(shape) ~= 2
meanWf = reshape(meanWf, shape);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
revert.m
|
.m
|
JRCLUST-main/+jrclust/+interfaces/@Clustering/revert.m
| 6,515 |
utf_8
|
2f6f0ecc9198a33ffd725eb971dd4e17
|
function success = revert(obj, revertTo)
%REVERT Delete history
success = 0;
if revertTo < 0 || revertTo > obj.nEdits
return;
end
% load history from file
if exist(obj.hCfg.histFile, 'file') ~= 2
error('history file %s not found!', obj.hCfg.histFile);
end
fidHist = fopen(obj.hCfg.histFile, 'r');
checkInt = fread(fidHist, 1, 'int32');
fRes = -isempty(checkInt); % -1 if no checkInt read, 0 if okay
while fRes > -1 && ~isempty(checkInt) && checkInt ~= revertTo
fRes = fseek(fidHist, 4*obj.nSpikes, 'cof');
checkInt = fread(fidHist, 1, 'int32');
end
if isempty(checkInt) || checkInt ~= revertTo
fclose(fidHist);
warning('failed to revert: entry %d not found in history file', revertTo);
end
spikeClusters = fread(fidHist, obj.nSpikes, 'int32');
fclose(fidHist);
spikesByCluster = arrayfun(@(iC) find(spikeClusters == iC), 1:max(spikeClusters), 'UniformOutput', 0);
flagged = 1:numel(spikesByCluster);
metadata = struct();
isConsistent = 1;
vectorFields = obj.unitFields.vectorFields;
hFunConsistent = @(vals) numel(vals) == numel(spikesByCluster); % ensure we have the expected number of clusters after a deletion
for i = 1:numel(vectorFields)
fn = vectorFields{i};
metadata.(fn) = obj.(fn);
if ~isempty(metadata.(fn))
if numel(spikesByCluster) < obj.nClusters % losing clusters
hFun = @(vals, indices) vals(indices);
metadata.(fn) = hFun(metadata.(fn), flagged);
elseif numel(spikesByCluster) > obj.nClusters && isrow(metadata.(fn)) % gaining clusters
hFun = @(vals, nAugs) [vals empty(vals, [1 nAugs])];
metadata.(fn) = hFun(metadata.(fn), numel(spikesByCluster) - obj.nClusters);
elseif numel(spikesByCluster) > obj.nClusters
hFun = @(vals, nAugs) [vals; empty(vals, [nAugs 1])];
metadata.(fn) = hFun(metadata.(fn), numel(spikesByCluster) - obj.nClusters);
end
if ~hFunConsistent(metadata.(fn))
isConsistent = 0;
break;
end
end
end
if isConsistent
otherFields = obj.unitFields.otherFields;
otherFieldNames = fieldnames(otherFields);
for i = 1:numel(otherFieldNames)
fn = otherFieldNames{i};
metadata.(fn) = obj.(fn);
if ~isempty(metadata.(fn))
if numel(spikesByCluster) < obj.nClusters % losing clusters
hFunSubset = eval(otherFields.(fn).subset);
metadata.(fn) = hFunSubset(metadata.(fn), flagged);
elseif numel(spikesByCluster) > obj.nClusters
nExtra = numel(spikesByCluster) - obj.nClusters;
switch fn
case {'templateSim', 'waveformSim'}
augShape = [numel(spikesByCluster), nExtra];
case 'clusterCentroids'
augShape = [nExtra, 2];
otherwise
clusterDims = otherFields.(fn).cluster_dims;
% get remaining (non-cluster-indexed) dimensions
shape = size(metadata.(fn));
augShape = [shape(1:clusterDims-1) nExtra shape(clusterDims+1:end)];
end
filler = empty(metadata.(fn), augShape);
hFunAug = eval(otherFields.(fn).augment);
metadata.(fn) = hFunAug(metadata.(fn), 0, filler);
end
hFunConsistent = eval(otherFields.(fn).consistent); % see /json/Clustering.json for subsetting functions for non-vector fields
if ~hFunConsistent(metadata.(fn), numel(spikesByCluster))
isConsistent = 0;
break;
end
end
end
end
if ~isConsistent
warning('failed to revert: inconsistent fields');
return;
end
% create a backup of changed fields
backup = struct('spikeClusters', obj.spikeClusters);
fieldNames = fieldnames(metadata);
for i = 1:numel(fieldNames)
fn = fieldNames{i};
if isprop(obj, fn)
backup.(fn) = obj.(fn);
end
end
try
obj.spikeClusters = spikeClusters;
for i = 1:numel(fieldNames)
fn = fieldNames{i};
if isprop(obj, fn)
obj.(fn) = metadata.(fn);
end
end
histkeys = keys(obj.history);
remove(obj.history, num2cell(setdiff([histkeys{:}], 1:revertTo))); %% FIXME
obj.syncHistFile();
catch ME
% restore spike table and metadata entries from backup
fieldNames = fieldnames(backup);
for i = 1:numel(fieldNames)
fn = fieldNames{i};
obj.(fn) = backup.(fn);
end
warning('failed to revert: %s', ME.message);
return;
end
obj.editPos = revertTo;
if ~isempty(flagged)
obj.spikesByCluster(flagged) = arrayfun(@(iC) find(obj.spikeClusters == iC), flagged, 'UniformOutput', 0);
% update count of spikes per unit
obj.unitCount(flagged) = cellfun(@numel, obj.spikesByCluster(flagged));
% update cluster sites
% if ~isempty(obj.spikeSites)
obj.clusterSites(flagged) = double(arrayfun(@(iC) mode(obj.spikeSites(obj.spikesByCluster{iC})), flagged));
% end
% don't recompute mean waveforms (and their consequences) if we didn't have them already
% if ~isempty(obj.meanWfGlobal)
% update mean waveforms for flagged units
obj.updateWaveforms(flagged);
% update unit positions
obj.computeCentroids(flagged);
% compute quality scores for altered units
obj.computeQualityScores(flagged);
% end
end
success = 1;
end
%% LOCAL FUNCTIONS
function filler = empty(vals, shape)
cls = class(vals);
switch cls
case 'cell' % expecting a homogeneous cell array, e.g., of char
filler = cell(shape);
if ~isempty(vals)
filler = cellfun(@(x) cast(x, 'like', vals{1}), filler, 'UniformOutput', 0);
end
case 'char'
filler = char(shape);
otherwise
filler = zeros(shape, cls);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
undeleteUnit.m
|
.m
|
JRCLUST-main/+jrclust/+interfaces/@Clustering/undeleteUnit.m
| 4,094 |
utf_8
|
82282d0edfab25f6de1da21cc48fc9a6
|
function res = undeleteUnit(obj, spikeClusters, unitID, indices, metadata)
%UNDELETEUNITS Speculatively undelete a unit, returning a snapshot of
%the spike table and metadata fields.
if nargin < 5
metadata = struct();
end
res = struct('spikeClusters', [], ...
'metadata', []);
if isempty(indices)
return;
end
goodUnits = unique(spikeClusters(spikeClusters > 0));
nClusters = numel(goodUnits);
% ensure all indices are in bounds
if any((indices < 1) | (indices > numel(spikeClusters)))
error('indices exceed bounds');
end
% check for spikes which haven't actually been deleted
if any(spikeClusters(indices) > 0)
error('non-deleted spikes in deleted unit');
end
% augment fields
isConsistent = 1;
vectorFields = obj.unitFields.vectorFields;
hFunConsistent = @(vals) numel(vals) == nClusters + 1; % ensure we have the expected number of clusters after an augment
for i = 1:numel(vectorFields)
fn = vectorFields{i};
if ~isfield(metadata, fn)
metadata.(fn) = obj.(fn);
end
if ~isempty(metadata.(fn))
if isrow(metadata.(fn))
hFunAug = @(vals, augmentAfter) [vals(1:augmentAfter) empty(vals, 1) vals(augmentAfter+1:end)];
else
hFunAug = @(vals, augmentAfter) [vals(1:augmentAfter); empty(vals, 1); vals(augmentAfter+1:end)];
end
metadata.(fn) = hFunAug(metadata.(fn), unitID-1);
if ~hFunConsistent(metadata.(fn))
isConsistent = 0;
break;
end
end
end
if isConsistent
otherFields = obj.unitFields.otherFields;
otherFieldNames = fieldnames(otherFields);
for i = 1:numel(otherFieldNames)
fn = otherFieldNames{i};
if ~isfield(metadata, fn)
metadata.(fn) = obj.(fn);
end
if ~isempty(metadata.(fn))
switch fn
case {'templateSim', 'waveformSim'}
augShape = [nClusters + 1, 1];
case 'clusterCentroids'
augShape = [1, 2];
otherwise
clusterDims = otherFields.(fn).cluster_dims;
% get remaining (non-cluster-indexed) dimensions
shape = size(metadata.(fn));
augShape = [shape(1:clusterDims-1) 1 shape(clusterDims+1:end)];
end
filler = empty(metadata.(fn), augShape);
hFunAug = eval(otherFields.(fn).augment);
hFunConsistent = eval(otherFields.(fn).consistent); % see /json/Clustering.json for subsetting functions for non-vector fields
metadata.(fn) = hFunAug(metadata.(fn), unitID-1, filler);
if ~hFunConsistent(metadata.(fn), nClusters + 1)
isConsistent = 0;
break;
end
end
end
end
if isConsistent
spikeClusters = spikeClusters(:);
% flag this unit to update later
metadata.unitCount(unitID) = nan;
% side effect: shift all larger units up by unity
mask = (spikeClusters >= unitID);
spikeClusters(mask) = spikeClusters(mask) + 1;
% AFTER making room for new units, assign split off spikes to their
% new units
spikeClusters(indices) = unitID;
res.spikeClusters = spikeClusters;
res.metadata = metadata;
end
end
function filler = empty(vals, shape)
cls = class(vals);
switch cls
case 'cell' % expecting a homogeneous cell array, e.g., of char
filler = cell(shape);
if ~isempty(vals)
filler = cellfun(@(x) cast(x, 'like', vals{1}), filler, 'UniformOutput', 0);
end
case 'char'
filler = char(shape);
otherwise
filler = zeros(shape, cls);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
splitUnit.m
|
.m
|
JRCLUST-main/+jrclust/+interfaces/@Clustering/splitUnit.m
| 4,962 |
utf_8
|
f2e92bc7d8b9d97eac4f2997b63082b5
|
function res = splitUnit(obj, spikeClusters, unitID, unitPart, metadata)
%SPLITUNIT Speculatively split a unit, returning a snapshot of the
%spike table and metadata fields.
if nargin < 5
metadata = struct();
end
res = struct('spikeClusters', [], ...
'metadata', []);
nSplits = numel(unitPart); % number of *new* units created after a split
unitIndices = find(spikeClusters == unitID);
goodUnits = unique(spikeClusters(spikeClusters > 0));
nClusters = numel(goodUnits);
if isempty(unitIndices)
return;
end
unitPart = cellfun(@(x) x(:)', unitPart, 'UniformOutput', 0);
% check for duplicates
for i = 1:numel(unitPart)
iPart = unitPart{i};
if numel(unique(iPart)) < numel(iPart)
error('duplicate indices in partition %d', i);
end
for j = i+1:numel(unitPart)
jPart = unitPart{j};
if ~isempty(intersect(iPart, jPart))
error('duplicate indices between partition %d and partition %d', i, j);
end
end
end
% replace local (in-unit) indices with global (spike-table) indices
splitOff = [unitPart{:}]';
if max(splitOff) > numel(unitIndices) || min(splitOff) < 1
error('split indices exceed bounds');
end
unitPart = cellfun(@(i) unitIndices(i)', unitPart, 'UniformOutput', 0);
% augment fields
isConsistent = 1;
vectorFields = obj.unitFields.vectorFields;
hFunConsistent = @(vals) numel(vals) == nClusters + nSplits; % ensure we have the expected number of clusters after a deletion
for i = 1:numel(vectorFields)
fn = vectorFields{i};
if ~isfield(metadata, fn)
metadata.(fn) = obj.(fn);
end
if ~isempty(metadata.(fn))
if isrow(metadata.(fn))
hFunAug = @(vals, augmentAfter) [vals(1:augmentAfter) empty(vals, [1 nSplits]) vals(augmentAfter+1:end)];
else
hFunAug = @(vals, augmentAfter) [vals(1:augmentAfter); empty(vals, [nSplits 1]); vals(augmentAfter+1:end)];
end
metadata.(fn) = hFunAug(metadata.(fn), unitID);
if ~hFunConsistent(metadata.(fn))
isConsistent = 0;
break;
end
end
end
if isConsistent
otherFields = obj.unitFields.otherFields;
otherFieldNames = fieldnames(otherFields);
for i = 1:numel(otherFieldNames)
fn = otherFieldNames{i};
if ~isfield(metadata, fn)
metadata.(fn) = obj.(fn);
end
if ~isempty(metadata.(fn))
switch fn
case {'templateSim', 'waveformSim'}
augShape = [nClusters + nSplits, nSplits];
case 'clusterCentroids'
augShape = [nSplits, 2];
otherwise
clusterDims = otherFields.(fn).cluster_dims;
% get remaining (non-cluster-indexed) dimensions
shape = size(metadata.(fn));
augShape = [shape(1:clusterDims-1) nSplits shape(clusterDims+1:end)];
end
filler = empty(metadata.(fn), augShape);
hFunAug = eval(otherFields.(fn).augment);
hFunConsistent = eval(otherFields.(fn).consistent); % see /json/Clustering.json for subsetting functions for non-vector fields
metadata.(fn) = hFunAug(metadata.(fn), unitID, filler);
if ~hFunConsistent(metadata.(fn), nClusters + nSplits)
isConsistent = 0;
break;
end
end
end
end
if isConsistent
indices = [unitPart{:}];
newUnits = arrayfun(@(i) zeros(1, numel(unitPart{i}))+unitID+i, 1:nSplits, ...
'UniformOutput', 0);
newUnits = [newUnits{:}];
% flag these units to update later
metadata.unitCount(unitID:unitID+nSplits) = nan;
% side effect: shift all larger units up by unity
mask = (spikeClusters > unitID);
spikeClusters(mask) = spikeClusters(mask) + nSplits;
% AFTER making room for new units, assign split off spikes to their
% new units
spikeClusters(indices) = newUnits;
res.spikeClusters = spikeClusters;
res.metadata = metadata;
end
end
function filler = empty(vals, shape)
cls = class(vals);
switch cls
case 'cell' % expecting a homogeneous cell array, e.g., of char
filler = cell(shape);
if ~isempty(vals)
filler = cellfun(@(x) cast(x, 'like', vals{1}), filler, 'UniformOutput', 0);
end
case 'char'
filler = char(shape);
otherwise
filler = zeros(shape, cls);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
unitWaveformSim.m
|
.m
|
JRCLUST-main/+jrclust/+interfaces/@Clustering/private/unitWaveformSim.m
| 5,276 |
utf_8
|
45b1683e7baf448cb6c405407bdfb359
|
function unitSims = unitWaveformSim(meanWfSet, clusterSites, hCfg, scoreData, iCluster)
%UNITWAVEFORMSIM Mean waveform similarity scores for one cluster against all others
updateMe = scoreData.updateMe;
cviShift1 = scoreData.cviShift1;
cviShift2 = scoreData.cviShift2;
simScoreOld = scoreData.simScoreOld;
fMode_cor = scoreData.fMode_cor;
if numel(clusterSites) == 1
sites = clusterSites{1};
fUsePeak2 = 0;
else
sites = clusterSites{1};
sites2 = clusterSites{2};
sites3 = clusterSites{3};
fUsePeak2 = 1;
end
nClusters = numel(sites);
iSite = sites(iCluster);
if iSite == 0 || isnan(iSite)
unitSims = [];
return;
end
iNeighbors = hCfg.siteNeighbors(:, iSite);
if fUsePeak2
compClusters = find(sites == iSite | sites2 == iSite | sites3 == iSite | sites == sites2(iCluster) | sites == sites3(iCluster));
else
compClusters = find(ismember(sites, jrclust.utils.findNearbySites(hCfg.siteLoc, iSite, hCfg.evtMergeRad)));
end
unitSims = zeros(nClusters, 1, 'single');
compClusters(compClusters >= iCluster) = []; % symmetric matrix comparison
if isempty(compClusters)
return;
end
iWaveforms = cellfun(@(x) x(:, iNeighbors, iCluster), meanWfSet, 'UniformOutput', 0);
jWaveforms = cellfun(@(x) x(:, iNeighbors, compClusters), meanWfSet, 'UniformOutput', 0);
for j = 1:numel(compClusters)
jCluster = compClusters(j);
if ~updateMe(jCluster) && ~updateMe(iCluster)
unitSims(jCluster) = simScoreOld(jCluster, iCluster);
else
jSite = sites(jCluster);
if jSite == 0 || isnan(jSite)
continue;
end
if jSite == iSite % neighbors are the same, can compare all sites
iWaveforms_ = iWaveforms;
jWaveforms_ = cellfun(@(x) x(:, :, j), jWaveforms, 'UniformOutput', 0);
else % find overlap of neighbors and compare these
jNeighbors = hCfg.siteNeighbors(:, jSite);
ijOverlap = find(ismember(iNeighbors, jNeighbors));
if isempty(ijOverlap) % nothing to compare
continue;
end
iWaveforms_ = cellfun(@(x) x(:, ijOverlap), iWaveforms, 'UniformOutput', 0);
jWaveforms_ = cellfun(@(x) x(:, ijOverlap, j), jWaveforms, 'UniformOutput', 0);
end
if strcmp(hCfg.autoMergeBy, 'pearson')
unitSims(jCluster) = maxCorPearson(iWaveforms_, jWaveforms_, cviShift1, cviShift2, fMode_cor);
else % dist
unitSims(jCluster) = minNormDist(iWaveforms_, jWaveforms_);
end
end
end
end
%% LOCAL FUNCTIONS
function maxCor = maxCorPearson(iWaveforms, jWaveforms, shifts1, shifts2, fMode_cor)
assert(numel(iWaveforms) == numel(jWaveforms), 'maxCorPearson: numel must be the same');
if numel(iWaveforms) == 1
maxCor = max(shiftPearson(iWaveforms{1}, jWaveforms{1}, shifts1, shifts2));
else
tr1 = cat(3, iWaveforms{:}); %nT x nC x nDrifts
tr2 = cat(3, jWaveforms{:});
nDrifts = numel(iWaveforms);
nShifts = numel(shifts1);
corScores = zeros(1, nShifts);
for iShift = 1:nShifts
mr1_ = reshape(tr1(shifts1{iShift}, :, :), [], nDrifts);
mr2_ = reshape(tr2(shifts2{iShift}, :, :), [], nDrifts);
if fMode_cor == 0 % center the waveforms
mr1_ = bsxfun(@minus, mr1_, mean(mr1_));
mr2_ = bsxfun(@minus, mr2_, mean(mr2_));
mr1_ = bsxfun(@rdivide, mr1_, sqrt(sum(mr1_.^2)));
mr2_ = bsxfun(@rdivide, mr2_, sqrt(sum(mr2_.^2)));
corScores(iShift) = max(max(mr1_' * mr2_));
else
mr12_ = (mr1_' * mr2_) ./ sqrt(sum(mr1_.^2)' * sum(mr2_.^2));
corScores(iShift) = max(mr12_(:));
end
end
maxCor = max(corScores);
end
end
function minDist = minNormDist(iWaveforms, jWaveforms) % TW
jrclust.utils.dlgAssert(numel(iWaveforms) == numel(jWaveforms), 'minNormDist: numel must be the same');
if numel(iWaveforms) == 1
x = reshape(iWaveforms{1}, [], 1);
y = reshape(jWaveforms{1}, [], 1);
minDist = 1 - norm(x - y)/max(norm(x), norm(y));
else
tr1 = cat(3, iWaveforms{:}); %nT x nC x nDrifts
tr2 = cat(3, jWaveforms{:});
dists = zeros(size(tr1, 3), 1);
for j = 1:size(tr1, 3)
x = reshape(tr1(:, :, j), [], 1);
y = reshape(tr2(:, :, j), [], 1);
dists(j) = 1 - norm(x - y)/max(norm(x), norm(y));
end
minDist = max(dists);
end
end
function scores = shiftPearson(X, Y, shift1, shift2)
% TODO: use shift matrix? (https://en.wikipedia.org/wiki/Shift_matrix)
% maybe just use shifted indices
scores = zeros(size(shift1), 'like', X);
for iShift = 1:numel(scores)
vX = X(shift1{iShift}, :);
vY = Y(shift2{iShift}, :);
% Pearson correlation coefficient for shifted X and Y
r = corrcoef(vX(:), vY(:)); % TODO: get p-values?
scores(iShift) = r(1, 2);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
autoSplit.m
|
.m
|
JRCLUST-main/+jrclust/+curate/@CurateController/autoSplit.m
| 24,797 |
utf_8
|
a22990f93c51f86b5a0953795fbb15f0
|
function autoSplit(obj, multisite)
%AUTOSPLIT
if numel(obj.selected) > 1
return;
end
if obj.isWorking
jrclust.utils.qMsgBox('An operation is in progress.');
return;
end
if obj.hClust.unitCount(obj.selected) < 2
msgbox('At least two spikes required for splitting');
return;
end
iCluster = obj.selected(1);
iSite = obj.hClust.clusterSites(iCluster);
if multisite
spikeSites = obj.hCfg.siteNeighbors(1:end - obj.hCfg.nSitesExcl, iSite);
else
spikeSites = iSite;
end
iSpikes = obj.hClust.spikesByCluster{iCluster};
sampledTraces = obj.hClust.getSpikeWindows(iSpikes, spikeSites, 0, 1);
sampledTraces = reshape(sampledTraces, [], size(sampledTraces, 3));
% get Vpp of cluster spikes on current site (in FigTime)
localSpikes = squeeze(obj.hClust.getSpikeWindows(iSpikes, obj.currentSite, 0, 1));
localVpp = max(localSpikes) - min(localSpikes); % TW calculate amplitudes on the fly
clusterTimes = obj.hClust.spikeTimes(iSpikes);
% create split figure
hFigSplit = jrclust.views.Figure('FigSplit', [0.05 0.05 0.8 0.8], sprintf('Split cluster %d', iCluster), 0, 0);
hFigSplit.figApply(@set, 'Visible', 'off');
hFigSplit.figData.nSplits = 0;
% create a dialog
splitDlg = dialog('Name', 'Split cluster', ...
'Units', 'Normalized', ...
'Position', [0.4, 0.5, 0.2, 0.15]);
uicontrol('Parent', splitDlg, 'Style', 'text', ...
'String', 'Number of splits', ...
'Units', 'Normalized', ...
'Position', [0.4 0.4 0.2 0.07]);
nsplit = uicontrol('Parent', splitDlg, 'Style', 'edit', ...
'String', 2, ...
'Units', 'Normalized', ...
'Position', [0.4 0.25 0.2 0.15]);
% button group: K-means, K-medoids, Hierarchical clustering
btngrp = uibuttongroup('Parent', splitDlg, 'Units', 'Normalized', ...
'Position', [0.1 0.1 0.3 0.8]);
uicontrol('Parent', btngrp, 'Style', 'radiobutton', 'String', 'Hierarchical (Ward)', ...
'Units', 'Normalized', 'Position', [0.1, 0.1, 1, 0.15]);
uicontrol('Parent', btngrp, 'Style', 'radiobutton', 'String', 'K-means', ...
'Units', 'Normalized', 'Position', [0.1, 0.7, 1, 0.15]);
uicontrol('Parent', btngrp, 'Style', 'radiobutton', 'String', 'K-medoids', ...
'Units', 'Normalized', 'Position', [0.1, 0.4, 1, 0.15]);
uicontrol('Parent', splitDlg, 'Style', 'pushbutton', ...
'String', 'Split', ...
'Units', 'Normalized', ...
'Position', [0.4 0.1 0.2 0.15], ...
'Callback', @(hO, hE) preSplit(splitDlg, nsplit.String, btngrp, hFigSplit));
uicontrol('Parent', splitDlg, 'Style', 'pushbutton', ...
'String', 'Cancel', ...
'Units', 'Normalized', ...
'Position', [0.6 0.1 0.2 0.15], ...
'Callback', @(hO, hE) doCancel(splitDlg, hFigSplit));
uicontrol('Parent', splitDlg, 'Style', 'text', ...
'String', 'How to recluster this unit?', ...
'Units', 'Normalized', ...
'Position', [0.1 0.9 0.3 0.07]);
uiwait(splitDlg);
if hFigSplit.figData.nSplits <= 1
return;
else
nSplits = hFigSplit.figData.nSplits;
end
hBox = jrclust.utils.qMsgBox('Splitting... (this closes automatically)', 0, 1);
% add plots
hFigSplit.addAxes('vppTime', 'Units', 'Normalized', 'OuterPosition', [0 0 0.7 0.5]);
hFigSplit.addAxes('pc12', 'Units', 'Normalized', 'OuterPosition', [0 0.5 0.2333 0.5]);
hFigSplit.addAxes('pc13', 'Units', 'Normalized', 'OuterPosition', [0.2333 0.5 0.2333 0.5]);
hFigSplit.addAxes('pc23', 'Units', 'Normalized', 'OuterPosition', [0.4667 0.5 0.2333 0.5]);
hFigSplit.addAxes('isi', 'Units', 'Normalized', 'OuterPosition', [0.7 0.65 0.3 0.35]);
hFigSplit.addAxes('meanwf', 'Units', 'Normalized', 'OuterPosition', [0.7 0.4 0.3 0.25]);
% add controls
hFigSplit.figData.clustList = hFigSplit.figApply(@uicontrol, 'Style', 'listbox', ...
'Units', 'normalized', ...
'Position', [0.7 0.05 0.1 0.25], ...
'String', num2str((1:nSplits)'), ...
'Value', 1, 'BackgroundColor', [1 1 1], ...
'Max', 3, 'Min', 1, ...
'Callback', @(hO, hE) updateSplitPlots(hFigSplit));
hFigSplit.figData.doneButton = hFigSplit.figApply(@uicontrol, 'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.84 0.25 0.12 0.05], ...
'String', 'Keep splits', ...
'FontWeight','Normal', ...
'Callback', @(hO, hE) finishSplit(hFigSplit, 0));
hFigSplit.figData.quitButton = hFigSplit.figApply(@uicontrol, 'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.84 0.2 0.12 0.05], ...
'String', 'Discard splits', ...
'FontWeight','Normal', ...
'Callback', @(hO, hE) finishSplit(hFigSplit, 1));
hFigSplit.figData.mergeButton = hFigSplit.figApply(@uicontrol, 'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.84 0.1 0.12 0.05], ...
'String', 'Merge selected', ...
'FontWeight','Normal', ...
'Callback', @(hO, hE) mergeSelected(hFigSplit));
hFigSplit.figData.button12 = hFigSplit.figApply(@uicontrol, 'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.84 0.05 0.04 0.05], ...
'String', 'Manual 2 vs. 1', ...
'FontWeight','Normal', ...
'Callback', @(hO, hE) manualSplit(hFigSplit, [1 2]));
hFigSplit.figData.button13 = hFigSplit.figApply(@uicontrol, 'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.88 0.05 0.04 0.05], ...
'String', 'Manual 3 vs. 1', ...
'FontWeight','Normal', ...
'Callback', @(hO, hE) manualSplit(hFigSplit, [1 3]));
hFigSplit.figData.button23 = hFigSplit.figApply(@uicontrol, 'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.92 0.05 0.04 0.05], ...
'String', 'Manual 3 vs. 2', ...
'FontWeight','Normal', ...
'Callback', @(hO, hE) manualSplit(hFigSplit, [2 3]));
hFigSplit.figData.finished = 0;
hFigSplit.figData.currentSite = obj.currentSite;
hFigSplit.figData.refracInt = obj.hCfg.refracInt/1000;
while 1
[assigns, pcaFeatures] = doAutoSplit(sampledTraces, [double(clusterTimes) double(localVpp')], hFigSplit); %TW
hFigSplit.figData.pcaFeatures = pcaFeatures;
hFigSplit.figData.clusterTimes = double(clusterTimes)/obj.hCfg.sampleRate;
hFigSplit.figData.localVpp = double(localVpp');
hFigSplit.figData.assignPart = arrayfun(@(i) find(assigns == i)', 1:max(assigns), 'UniformOutput', 0);
hFigSplit.figData.localSpikes = localSpikes;
jrclust.utils.tryClose(hBox);
updateSplitPlots(hFigSplit);
hFigSplit.figApply(@uiwait);
if ~hFigSplit.isReady % user closed the window
assignPart = [];
break;
elseif hFigSplit.figData.finished
assignPart = hFigSplit.figData.assignPart;
break;
end
end
hFigSplit.close();
obj.isWorking = 0;
if numel(assignPart) > 1
obj.splitCluster(iCluster, assignPart(2:end));
end
end
%% LOCAL FUNCTIONS
function [assigns, pcaFeatures] = doAutoSplit(sampledSpikes, spikeFeatures, hFigSplit)
%DOAUTOSPLIT
% TODO: ask users number of clusters and split multi-way
%Make automatic split of clusters using PCA + hierarchical clustering
[~, pcaFeatures, ~] = pca(double(sampledSpikes'), 'Centered', 1, ...
'NumComponents', 3);
combinedFeatures = [spikeFeatures pcaFeatures];
nSpikes = size(sampledSpikes, 2);
% ask how many clusters there are
try
combinedFeatures = (combinedFeatures - mean(combinedFeatures, 1)) ./ std(combinedFeatures, 1);
assigns = hFigSplit.figData.hFunSplit(combinedFeatures);
catch % not enough features to automatically split or some other failure
assigns = ones(nSpikes, 1);
end
end
function doCancel(splitDlg, hFigSplit)
delete(splitDlg);
hFigSplit.figData.nSplits = 0;
end
function preSplit(splitDlg, nsplit, btngrp, hFigSplit)
whichSelected = logical(arrayfun(@(child) child.Value, btngrp.Children));
selected = btngrp.Children(whichSelected);
nsplit = floor(str2double(nsplit));
if isnan(nsplit)
nsplit = 2;
end
switch selected.String
case 'K-means'
hFigSplit.figData.hFunSplit = @(X) kmeans(X, nsplit);
case 'K-medoids'
hFigSplit.figData.hFunSplit = @(X) kmedoids(X, nsplit);
otherwise
hFigSplit.figData.hFunSplit = @(X) clusterdata(X, ...
'maxclust', nsplit, ...
'linkage', 'ward', ...
'distance', 'euclidean', ...
'savememory', 'on');
end
delete(splitDlg)
hFigSplit.figData.nSplits = nsplit;
end
function updateSplitPlots(hFigSplit)
clustList = hFigSplit.figData.clustList;
assignPart = hFigSplit.figData.assignPart;
clusterTimes = hFigSplit.figData.clusterTimes;
localVpp = hFigSplit.figData.localVpp;
pcaFeatures = hFigSplit.figData.pcaFeatures;
localSpikes = hFigSplit.figData.localSpikes;
refracInt = hFigSplit.figData.refracInt;
nSplits = numel(assignPart);
selectedClusters = get(clustList, 'Value');
selectedSpikes = sort([assignPart{selectedClusters}]);
cmap = [0, 0.4470, 0.7410; 0.8500, 0.3250, 0.0980; 0.9290, 0.6940, 0.1250; 0.4940, 0.1840, 0.5560; 0.4660, 0.6740, 0.1880; 0.3010, 0.7450, 0.9330; 0.6350, 0.0780, 0.1840];
legends = cell(nSplits, 1);
% plot split features
hFigSplit.axApply('vppTime', @cla);
for i = 1:nSplits
partSpikes = assignPart{i};
skip = ceil(numel(partSpikes) / 1e4);
XData = clusterTimes(partSpikes);
YData = localVpp(partSpikes);
hFigSplit.addPlot(sprintf('plot1%d', i), @plot, ...
hFigSplit.hAxes('vppTime'), ...
XData(1:skip:end), YData(1:skip:end), ...
'.', 'Color', cmap(mod(i-1, size(cmap, 1)) + 1, :), ...
'MarkerSize', jrclust.utils.ifEq(ismember(i, selectedClusters), 10, 5));
hFigSplit.axApply('vppTime', @hold, 'on');
legends{i} = sprintf('Split %d (%d spikes)', i, numel(partSpikes));
end
hFigSplit.axApply('vppTime', @legend, legends, 'Location', 'Best');
hFigSplit.axApply('vppTime', @set, 'YDir', 'Reverse');
hFigSplit.axApply('vppTime', @view, 0, 90);
hFigSplit.axApply('vppTime', @xlim, [min(clusterTimes) max(clusterTimes)]);
hFigSplit.axApply('vppTime', @ylim, [min(localVpp) max(localVpp)]);
hFigSplit.axApply('vppTime', @xlabel, 'Spike times (s)');
hFigSplit.axApply('vppTime', @ylabel, 'Vpp (\muV)');
hFigSplit.axApply('pc12', @cla);
hFigSplit.axApply('pc13', @cla);
hFigSplit.axApply('pc23', @cla);
for i = 1:nSplits
partSpikes = assignPart{i};
skip = ceil(numel(partSpikes) / 1e4);
% PC1vs2
XData = pcaFeatures(partSpikes, 2);
YData = pcaFeatures(partSpikes, 1);
hFigSplit.addPlot(sprintf('pc12-%d', i), @plot, ...
hFigSplit.hAxes('pc12'), ...
XData(1:skip:end), YData(1:skip:end), ...
'.', 'Color', cmap(mod(i-1, size(cmap, 1)) + 1, :), ...
'MarkerSize', jrclust.utils.ifEq(ismember(i, selectedClusters), 10, 5));
hFigSplit.axApply('pc12', @hold, 'on');
% PC1vs3
XData = pcaFeatures(partSpikes, 3);
YData = pcaFeatures(partSpikes, 1);
hFigSplit.addPlot(sprintf('pc13-%d', i), @plot, ...
hFigSplit.hAxes('pc13'), ...
XData(1:skip:end), YData(1:skip:end), ...
'.', 'Color', cmap(mod(i-1, size(cmap, 1)) + 1, :), ...
'MarkerSize', jrclust.utils.ifEq(ismember(i, selectedClusters), 10, 5));
hFigSplit.axApply('pc13', @hold, 'on');
% PC2vs3
XData = pcaFeatures(partSpikes, 3);
YData = pcaFeatures(partSpikes, 2);
hFigSplit.addPlot(sprintf('pc23-%d', i), @plot, ...
hFigSplit.hAxes('pc23'), ...
XData(1:skip:end), YData(1:skip:end), ...
'.', 'Color', cmap(mod(i-1, size(cmap, 1)) + 1, :), ...
'MarkerSize', jrclust.utils.ifEq(ismember(i, selectedClusters), 10, 5));
hFigSplit.axApply('pc23', @hold, 'on');
end
hFigSplit.axApply('pc12', @hold, 'off');
hFigSplit.axApply('pc12', @xlabel, 'PC 2 (AU)');
hFigSplit.axApply('pc12', @ylabel, 'PC 1 (AU)');
hFigSplit.axApply('pc13', @hold, 'off');
hFigSplit.axApply('pc13', @xlabel, 'PC 3 (AU)');
hFigSplit.axApply('pc13', @ylabel, 'PC 1 (AU)');
hFigSplit.axApply('pc23', @hold, 'off');
hFigSplit.axApply('pc23', @xlabel, 'PC 3 (AU)');
hFigSplit.axApply('pc23', @ylabel, 'PC 2 (AU)');
% plot ISI
selectedTimes = clusterTimes(selectedSpikes);
selectedISI = diff([selectedTimes; inf]);
if isempty(selectedISI)
selectedISI = 1;
end
ISIedges = -0.02:0.0005:0.02;
nISI = histc([selectedISI; -selectedISI], ISIedges);
mx = 1.05 .* max(nISI);
if ~hFigSplit.hasPlot('isiHist')
% plot ISI region (region in hCfg.refracInt)
hFigSplit.addPlot('isiRegion', @fill, ...
hFigSplit.hAxes('isi'), ...
[-refracInt refracInt refracInt -refracInt], [0 0 mx mx], 'r');
hFigSplit.plotApply('isiRegion', @set, 'LineStyle', 'none');
% plot histogram of ISIs in cluster
hFigSplit.addPlot('isiHist', @bar, ...
hFigSplit.hAxes('isi'), ISIedges + mean(diff(ISIedges))./2, ...
nISI, 'BarWidth', 1, 'FaceAlpha', 0.75);
hFigSplit.axApply('isi', @xlim, [-0.02 0.02]);
hFigSplit.axApply('isi', @xlabel, 'ISI (s)');
hFigSplit.axApply('isi', @ylabel, 'Counts');
hFigSplit.axApply('isi', @title, 'ISI histogram (refractory interval in red)');
else
hFigSplit.updatePlot('isiRegion', [-refracInt refracInt refracInt -refracInt], [0 0 mx mx]);
hFigSplit.updatePlot('isiHist', ISIedges + mean(diff(ISIedges))./2, nISI);
end
violations = false(size(selectedISI));
violations(1:end-1) = selectedISI(1:end-1) < refracInt;
violations(2:end) = violations(2:end) | selectedISI(1:end - 1) < refracInt;
violAll = false(size(selectedSpikes));
violAll(selectedSpikes) = violations;
% highlight violations on feature plot
if any(violAll)
violAll = find(violAll);
hFigSplit.addPlot(sprintf('plot1%d-viol', i), @plot, ...
hFigSplit.hAxes('vppTime'), ...
clusterTimes(violAll), ...
localVpp(violAll), ...
'ko', 'LineWidth', 2);
legends{end+1} = 'ISI violations';
end
hFigSplit.axApply('vppTime', @hold, 'off');
hFigSplit.axApply('vppTime', @legend, legends, 'Location', 'Best');
% plot mean traces
unselectedClusters = setdiff(1:nSplits, selectedClusters);
hFigSplit.axApply('meanwf', @cla);
nSpikesPlot = 50;
% plot unselected traces first...
for ii = 1:numel(unselectedClusters)
i = unselectedClusters(ii);
partSpikes = assignPart{i};
hFigSplit.addPlot(sprintf('traces-%d', i), @plot, ...
hFigSplit.hAxes('meanwf'), ...
localSpikes(:, randsample(partSpikes, min(numel(partSpikes), nSpikesPlot))), ...
'Color', [0.75 0.75 0.75], 'LineWidth', 0.5);
hFigSplit.axApply('meanwf', @hold, 'on');
end
% ...plot selected traces on top of these...
for ii = 1:numel(selectedClusters)
i = selectedClusters(ii);
iColor = cmap(mod(i-1, size(cmap,1))+1, :)+(1-cmap(mod(i-1, size(cmap,1))+1, :))./2;
partSpikes = assignPart{i};
hFigSplit.addPlot(sprintf('traces-%d', i), @plot, ...
hFigSplit.hAxes('meanwf'), ...
localSpikes(:, randsample(partSpikes, min(numel(partSpikes), nSpikesPlot))), ...
'Color', iColor, 'LineWidth', 0.5);
hFigSplit.axApply('meanwf', @hold, 'on');
end
% ...plot unselected mean waveforms here...
for ii = 1:numel(unselectedClusters)
i = unselectedClusters(ii);
partSpikes = assignPart{i};
hFigSplit.addPlot(sprintf('mean-%d', i), @plot, ...
hFigSplit.hAxes('meanwf'), ...
mean(localSpikes(:, partSpikes), 2), ...
'Color', [0.5 0.5 0.5], 'LineWidth', 2);
end
for ii = 1:numel(selectedClusters)
i = selectedClusters(ii);
iColor = cmap(mod(i-1, size(cmap, 1))+1, :);
partSpikes = assignPart{i};
hFigSplit.addPlot(sprintf('mean-%d', i), @plot, ...
hFigSplit.hAxes('meanwf'), ...
mean(localSpikes(:, partSpikes), 2), ...
'Color', iColor, 'LineWidth', 2);
end
hFigSplit.axApply('meanwf', @hold, 'off');
hFigSplit.axApply('meanwf', @xlabel, 'Sample');
hFigSplit.axApply('meanwf', @ylabel, 'Amplitude (\muV)');
hFigSplit.axApply('meanwf', @title, sprintf('Mean waveform on site %d', hFigSplit.figData.currentSite));
end
function manualSplit(hFigSplit, pcPair)
clusterTimes = hFigSplit.figData.clusterTimes;
localVpp = hFigSplit.figData.localVpp;
pcaFeatures = hFigSplit.figData.pcaFeatures;
% clear out all axes
hFigSplit.axApply('pc12', @cla);
hFigSplit.axApply('pc13', @cla);
hFigSplit.axApply('pc23', @cla);
hFigSplit.axApply('vppTime', @cla);
hFigSplit.axApply('isi', @cla);
hFigSplit.axApply('meanwf', @cla);
nSpikes = numel(clusterTimes);
skip = ceil(numel(nSpikes) / 1e4);
% PC1vs2
XData = pcaFeatures(:, 2);
YData = pcaFeatures(:, 1);
hFigSplit.addPlot('pc12', @plot, ...
hFigSplit.hAxes('pc12'), ...
XData(1:skip:end), YData(1:skip:end), ...
'.', 'Color', 'k');
hFigSplit.axApply('pc12', @hold, 'off');
% PC1vs3
XData = pcaFeatures(:, 3);
YData = pcaFeatures(:, 1);
hFigSplit.addPlot('pc13', @plot, ...
hFigSplit.hAxes('pc13'), ...
XData(1:skip:end), YData(1:skip:end), ...
'.', 'Color', 'k');
hFigSplit.axApply('pc13', @hold, 'off');
% PC2vs3
XData = pcaFeatures(:, 3);
YData = pcaFeatures(:, 2);
hFigSplit.addPlot('pc23', @plot, ...
hFigSplit.hAxes('pc23'), ...
XData(1:skip:end), YData(1:skip:end), ...
'.', 'Color', 'k');
hFigSplit.axApply('pc13', @hold, 'off');
% vpp vs time
hFigSplit.addPlot('vppTime', @plot, ...
hFigSplit.hAxes('vppTime'), ...
clusterTimes(1:skip:end), localVpp(1:skip:end), ...
'.', 'Color', 'k');
hFigSplit.axApply('vppTime', @hold, 'off');
if all(pcPair == [1 2])
axKey = 'pc12';
featuresX = pcaFeatures(1:skip:end, 2);
featuresY = pcaFeatures(1:skip:end, 1);
elseif all(pcPair == [1 3])
axKey = 'pc13';
featuresX = pcaFeatures(1:skip:end, 3);
featuresY = pcaFeatures(1:skip:end, 1);
else % all(pcPair == [2 3])
axKey = 'pc23';
featuresX = pcaFeatures(1:skip:end, 3);
featuresY = pcaFeatures(1:skip:end, 2);
end
hFigSplit.axApply(axKey, @hold, 'on');
% clear axes
hPoly = hFigSplit.axApply(axKey, @impoly);
polyPos = getPosition(hPoly);
try
delete(hPoly);
catch
end
% partition spikes by polygon
assigns = inpolygon(featuresX, featuresY, polyPos(:, 1), polyPos(:, 2));
assignPart = {find(assigns), find(~assigns)};
assignPartOld = hFigSplit.figData.assignPart;
% update plots
nSplits = 2;
hFigSplit.figData.assignPart = assignPart;
set(hFigSplit.figData.clustList, 'String', num2str((1:nSplits)'), 'Value', 1);
updateSplitPlots(hFigSplit);
dlgAns = questdlg('Keep?', 'Manual split', 'No');
switch dlgAns
case {'No', 'Cancel'}
nSplits = numel(assignPartOld);
hFigSplit.figData.assignPart = assignPartOld;
set(hFigSplit.figData.clustList, 'String', num2str((1:nSplits)'), 'Value', 1);
updateSplitPlots(hFigSplit);
end
hFigSplit.figApply(@uiwait);
end
function mergeSelected(hFigSplit)
clustList = hFigSplit.figData.clustList;
selectedClusters = get(clustList, 'Value');
nSplits = numel(hFigSplit.figData.assignPart);
if numel(selectedClusters) > 1
unselectedClusters = setdiff(1:nSplits, selectedClusters);
unmerged = hFigSplit.figData.assignPart(unselectedClusters);
merged = {sort([hFigSplit.figData.assignPart{selectedClusters}])};
hFigSplit.figData.assignPart = cat(2, merged, unmerged);
nSplits = 1 + numel(unmerged);
set(hFigSplit.figData.clustList, 'String', num2str((1:nSplits)'), 'Value', 1);
updateSplitPlots(hFigSplit);
end
end
function finishSplit(hFigSplit, fAbort)
if fAbort
% confirm
dlgAns = questdlg('Really cancel?', 'Confirm', 'No');
if strcmp(dlgAns, 'Yes')
hFigSplit.figData.finished = 1;
hFigSplit.figData.assignPart = [];
hFigSplit.figApply(@uiresume);
end
else
% confirm
dlgAns = questdlg('Finished splitting?', 'Confirm', 'No');
if strcmp(dlgAns, 'Yes')
hFigSplit.figData.finished = 1;
hFigSplit.figApply(@uiresume);
end
end
end
% function d12 = madDist(features1, features2)
% % distance between two clusters
% if ~ismatrix(features1)
% features1 = reshape(features1, [], size(features1, 3));
% end
% if ~ismatrix(features2)
% features2 = reshape(features2, [], size(features2, 3));
% end
%
% med1 = median(features1, 2);
% med2 = median(features2, 2);
%
% medDiffs = med1 - med2;
% norm12 = norm(medDiffs, 2);
% vrFet12_med1 = medDiffs/norm12;
%
% mad1 = median(abs(vrFet12_med1' * bsxfun(@minus, features1, med1)));
% mad2 = median(abs(vrFet12_med1' * bsxfun(@minus, features2, med2)));
%
% d12 = norm12 / norm([mad1, mad2], 2);
% end
|
github
|
JaneliaSciComp/JRCLUST-main
|
updateFigISI.m
|
.m
|
JRCLUST-main/+jrclust/+curate/@CurateController/updateFigISI.m
| 2,942 |
utf_8
|
2108d80e13a644aec27716e53e93be02
|
function updateFigISI(obj)
%UPDATEFIGISI Plot return map
if isempty(obj.selected) || ~obj.hasFig('FigISI')
return;
end
nSpikes(1) = numel(obj.hClust.spikesByCluster{obj.selected(1)});
if numel(obj.selected)>1
nSpikes(2) = numel(obj.hClust.spikesByCluster{obj.selected(2)});
end
if all(nSpikes>1)
plotFigISI(obj.hFigs('FigISI'), obj.hClust, obj.hCfg, obj.selected);
else
clf(obj.hFigs('FigISI'));
end
end
%% LOCAL FUNCTIONS
function hFigISI = plotFigISI(hFigISI, hClust, hCfg, selected)
%DOPLOTFIGISI Plot return map (ISI vs. previous ISI)
if numel(selected) == 1
iCluster = selected(1);
jCluster = iCluster;
else
iCluster = selected(1);
jCluster = selected(2);
end
[iIsiK, iIsiK1] = getReturnMap(iCluster, hClust, hCfg);
if ~hFigISI.hasAxes('default')
hFigISI.addAxes('default');
hFigISI.addPlot('foreground', nan, nan, 'Color', hCfg.colorMap(2, :), 'Marker', 'o', 'LineStyle', 'none');
hFigISI.addPlot('foreground2', nan, nan, 'Color', hCfg.colorMap(3, :), 'Marker', 'o', 'LineStyle', 'none');
hFigISI.axApply('default', @set, 'XScale','log', 'YScale','log');
hFigISI.axApply('default', @xlabel, 'ISI_{k} (ms)');
hFigISI.axApply('default', @ylabel, 'ISI_{k+1} (ms)');
%axis_(S_fig.hAx, [1 10000 1 10000]);
hFigISI.axApply('default', @axis, [1 10000 1 10000]);
hFigISI.axApply('default', @grid, 'on');
% show refractory line
hFigISI.addPlot('refracLine1', @line, hFigISI.axApply('default', @get, 'XLim'), hCfg.refracInt*[1 1], 'Color', [1 0 0]);
hFigISI.addPlot('refracLine2', @line, hCfg.refracInt*[1 1], hFigISI.axApply('default', @get, 'YLim'), 'Color', [1 0 0]);
end
hFigISI.updatePlot('foreground', iIsiK, iIsiK1);
if iCluster ~= jCluster
[jIsiK, jIsiK1] = getReturnMap(jCluster, hClust, hCfg);
hFigISI.axApply('default', @title, sprintf('Unit %d (black) vs. Unit %d (red)', iCluster, jCluster));
hFigISI.updatePlot('foreground2', jIsiK, jIsiK1);
else
hFigISI.axApply('default', @title, sprintf('Unit %d', iCluster));
hFigISI.clearPlot('foreground2');
end
end
function [isiK, isiK1] = getReturnMap(iCluster, hClust, hCfg)
%GETRETURNMAP subset
clusterTimes = double(hClust.spikeTimes(hClust.spikesByCluster{iCluster}))/hCfg.sampleRate;
if numel(clusterTimes) < 3
isiK = 0;
isiK1 = 0;
return;
end
clusterISI = diff(clusterTimes * 1000); % in msec
%isiK = clusterISIMs(1:end-1);
%isiK1 = clusterISIMs(2:end);
%subset = randperm(numel(isiK), min(hCfg.nShow, numel(isiK)));
subset = randperm(numel(clusterISI) - 1, min(hCfg.nSpikesFigISI, numel(clusterISI) - 1));
%isiK = isiK(subset);
isiK = clusterISI(subset);
%isiK1 = isiK1(subset);
isiK1 = clusterISI(subset+1);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
updateCursorFigWav.m
|
.m
|
JRCLUST-main/+jrclust/+curate/@CurateController/updateCursorFigWav.m
| 1,654 |
utf_8
|
3de8f7f14f0e634d9e7d232cc955a732
|
function updateCursorFigWav(obj)
%UPDATECURSORFIGWAV Plot mean waveforms on top of selected cluster(s)
if isempty(obj.selected) || ~obj.hasFig('FigWav')
return;
end
hFigWav = obj.hFigs('FigWav');
plotSelectedMeansFun = @(x,y)plotSelectedMeans(hFigWav, obj.hClust, x, y, obj.maxAmp, obj.hCfg, obj.spatial_idx);
if numel(obj.selected) == 1 % we've selected just one cluster (primary)
hFigWav.rmPlot('selected2'); % if already selected, hide it
plotSelectedMeansFun(obj.selected,'selected1');
else % just plot #2 for now
plotSelectedMeansFun(obj.selected(1),'selected1');
plotSelectedMeansFun(obj.selected(2),'selected2');
end
end
%% LOCAL FUNCTIONS
function iCluster = plotSelectedMeans(hFigWav, hClust, iCluster, plotKey, maxAmp, hCfg, spatial_idx)
%PLOTSELECTEDMEANS Plot an overlay on selected cluster's mean traces
showSubset = hFigWav.figData.showSubset;
if strcmp(plotKey, 'selected2')
colorMap = hCfg.colorMap(3, :); % red
elseif strcmp(plotKey, 'selected1')
colorMap = hCfg.colorMap(2, :); % black
else
return; % maybe some day we support selected3, 4, ...
end
if ~hFigWav.hasPlot(plotKey)
hFigWav.addPlot(plotKey, nan, nan, 'Color', colorMap, 'LineWidth', 2);
end
if hCfg.showRaw
meanWf = hClust.meanWfGlobalRaw(:, :, iCluster);
else
meanWf = hClust.meanWfGlobal(:, :, iCluster);
end
hFigWav.multiplot(plotKey, maxAmp, jrclust.views.getXRange(find(iCluster == showSubset), size(meanWf, 1), hCfg), meanWf(:,spatial_idx));
hFigWav.plotApply(plotKey, @uistack, 'top');
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
updateFigSim.m
|
.m
|
JRCLUST-main/+jrclust/+curate/@CurateController/updateFigSim.m
| 3,992 |
utf_8
|
97b46cf0c08acc49e11e53ec26725d0d
|
function updateFigSim(obj)
%UPDATEFIGSIM Update similarity score figure
if ~obj.hasFig('FigSim')
return;
end
plotFigSim(obj.hFigs('FigSim'), obj.hClust, obj.hCfg, obj.selected, obj.showSubset);
end
%% LOCAL FUNCTIONS
function hFigSim = plotFigSim(hFigSim, hClust, hCfg, selected, showSubset)
%PLOTFIGSIM Display cluster similarity scores
if ~isfield(hFigSim.figData, 'showSubset')
hFigSim.figData.showSubset = showSubset;
end
hFigSim.wait(1);
xyLabels = arrayfun(@num2str, showSubset, 'UniformOutput', 0);
nClusters = numel(showSubset);
if ~hFigSim.hasAxes('default') || ~jrclust.utils.isEqual(showSubset, hFigSim.figData.showSubset) % create from scratch
hFigSim.addAxes('default');
hFigSim.axApply('default', @set, 'Position', [.1 .1 .8 .8], ...
'XLimMode', 'manual', ...
'YLimMode', 'manual', ...
'Layer', 'top', ...
'XTick', 1:nClusters, ...
'XTickLabel', xyLabels, ...
'YTick', 1:nClusters, ...
'YTickLabel', xyLabels);
if ~isfield(hFigSim.figData,'figView')
if isa(hClust, 'jrclust.sort.TemplateClustering')
hFigSim.figData.figView = 'template'; % start out showing template sim scores
else
hFigSim.figData.figView = 'waveform';
end
end
hFigSim.axApply('default', @axis, [0 nClusters 0 nClusters] + .5);
hFigSim.axApply('default', @axis, 'xy')
hFigSim.axApply('default', @grid, 'on');
hFigSim.axApply('default', @xlabel, 'Unit #');
hFigSim.axApply('default', @ylabel, 'Unit #');
if strcmp(hFigSim.figData.figView, 'template') && isprop(hClust, 'templateSim')
hFigSim.addPlot('hImSim', @imagesc, 'CData', hClust.templateSim(showSubset, showSubset), hCfg.corrRange);
hFigSim.figApply(@set, 'Name', ['Template-based similarity score: ', hCfg.sessionName], 'NumberTitle', 'off', 'Color', 'w');
else
hFigSim.addPlot('hImSim', @imagesc, 'CData', hClust.waveformSim(showSubset, showSubset), hCfg.corrRange);
end
% selected cluster pair cursors
hFigSim.addPlot('hCursorV', @line, [1 1], [.5 nClusters + .5], 'Color', hCfg.colorMap(2, :), 'LineWidth', 1.5);
hFigSim.addPlot('hCursorH', @line, [.5 nClusters + .5], [1 1], 'Color', hCfg.colorMap(3, :), 'LineWidth', 1.5);
hFigSim.axApply('default', @colorbar);
hFigSim.addDiag('hDiag', [0, nClusters, 0.5], 'Color', [0 0 0], 'LineWidth', 1.5);
else
if strcmp(hFigSim.figData.figView, 'template') && isprop(hClust, 'templateSim')
hFigSim.plotApply('hImSim', @set, 'CData', hClust.templateSim(showSubset, showSubset));
hFigSim.figApply(@set, 'Name', ['Template-based similarity score: ', hCfg.sessionName], 'NumberTitle', 'off', 'Color', 'w')
else
hFigSim.plotApply('hImSim', @set, 'CData', hClust.waveformSim(showSubset, showSubset));
hFigSim.figApply(@set, 'Name', ['Waveform-based similarity score: ', hCfg.sessionName], 'NumberTitle', 'off', 'Color', 'w')
end
hFigSim.axApply('default', @set, {'XTick', 'YTick'}, {1:nClusters, 1:nClusters});
hFigSim.addDiag('hDiag', [0, nClusters, 0.5], 'Color', [0 0 0], 'LineWidth', 1.5); % overwrites previous diag plot
end
iCluster = selected(1);
if numel(selected) > 1
jCluster = selected(2);
else
jCluster = iCluster;
end
if strcmp(hFigSim.figData.figView, 'template')
scoreij = hClust.templateSim(iCluster, jCluster);
elseif strcmp(hFigSim.figData.figView, 'waveform')
scoreij = hClust.waveformSim(iCluster, jCluster);
end
hFigSim.axApply('default', @title, sprintf('Unit %d vs. Unit %d: %0.3f', iCluster, jCluster, scoreij));
hFigSim.wait(0);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
updateFigHist.m
|
.m
|
JRCLUST-main/+jrclust/+curate/@CurateController/updateFigHist.m
| 2,077 |
utf_8
|
0a09440d927c6cbf7e21d39c2d54e367
|
function updateFigHist(obj)
%UPDATEFIGHIST Plot ISI histogram
if isempty(obj.selected) || ~obj.hasFig('FigHist')
return;
end
plotFigHist(obj.hFigs('FigHist'), obj.hClust, obj.hCfg, obj.selected);
end
%% LOCAL FUNCTIONS
function hFigHist = plotFigHist(hFigHist, hClust, hCfg, selected)
%PLOTFIGHIST Plot ISI histogram
if numel(selected) == 1
iCluster = selected(1);
jCluster = iCluster;
else
iCluster = selected(1);
jCluster = selected(2);
end
nBinsHist = 50; %TODO: put this in param file (maybe)
XData = logspace(-1, 4, nBinsHist); % logarithmic scale from 0.1ms to 10s
YData1 = getISIHistogram(iCluster, XData, hClust, hCfg);
% draw the plot
if ~hFigHist.hasAxes('default')
hFigHist.addAxes('default');
hFigHist.addPlot('hPlot1', @stairs, nan, nan, 'Color', hCfg.colorMap(2, :));
hFigHist.addPlot('hPlot2', @stairs, nan, nan, 'Color', hCfg.colorMap(3, :));
hFigHist.axApply('default', @set, 'XLim', [min(XData) max(XData)], 'XScale', 'log'); % ms
hFigHist.axApply('default', @grid, 'on');
hFigHist.axApply('default', @xlabel, 'ISI (ms)');
hFigHist.axApply('default', @ylabel, 'Prob. Density');
end
hFigHist.updatePlot('hPlot1', XData, YData1);
if iCluster ~= jCluster
YData2 = getISIHistogram(jCluster, XData, hClust, hCfg);
hFigHist.axApply('default', @title, sprintf('Unit %d (black) vs. Unit %d (red)', iCluster, jCluster));
hFigHist.updatePlot('hPlot2', XData, YData2);
else
hFigHist.axApply('default', @title, sprintf('Unit %d', iCluster));
hFigHist.clearPlot('hPlot2');
end
end
function YData = getISIHistogram(iCluster, XData, hClust, hCfg)
%GETISIHISTOGRAM Get a histogram of ISI values
% TODO: replace hist call with histogram
clusterTimes = double(hClust.spikeTimes(hClust.spikesByCluster{iCluster}))/hCfg.sampleRate;
YData = hist(diff(clusterTimes)*1000, XData);
YData(end) = 0;
YData = YData./sum(YData); % normalize
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
updateFigCorr.m
|
.m
|
JRCLUST-main/+jrclust/+curate/@CurateController/updateFigCorr.m
| 2,120 |
utf_8
|
c9afa1424b1996d4860e33d224df19d1
|
function updateFigCorr(obj)
%UPDATEFIGCORR Plot cross correlation
if isempty(obj.selected) || ~obj.hasFig('FigCorr')
return;
end
plotFigCorr(obj.hFigs('FigCorr'), obj.hClust, obj.hCfg, obj.selected);
end
%% LOCAL FUNCTIONS
function hFigCorr = plotFigCorr(hFigCorr, hClust, hCfg, selected)
%DOPLOTFIGCORR Plot timestep cross correlation
if numel(selected) == 1
iCluster = selected(1);
jCluster = iCluster;
else
iCluster = selected(1);
jCluster = selected(2);
end
jitterMs = 0.5; % bin size for correlation plot
nLagsMs = 25; % show 25 msec
jitterSamp = round(jitterMs*hCfg.sampleRate/1000); % 0.5 ms
nLags = round(nLagsMs/jitterMs);
iTimes = int32(double(hClust.spikeTimes(hClust.spikesByCluster{iCluster}))/jitterSamp);
if iCluster ~= jCluster
iTimes = [iTimes, iTimes - 1, iTimes + 1]; % check for off-by-one
end
jTimes = int32(double(hClust.spikeTimes(hClust.spikesByCluster{jCluster}))/jitterSamp);
% count agreements of jTimes + lag with iTimes
lagSamp = -nLags:nLags;
intCount = zeros(size(lagSamp));
for iLag = 1:numel(lagSamp)
if iCluster == jCluster && lagSamp(iLag)==0
continue;
end
intCount(iLag) = numel(intersect(iTimes, jTimes + lagSamp(iLag)));
end
lagTime = lagSamp*jitterMs;
% draw the plot
if ~hFigCorr.hasAxes('default')
hFigCorr.addAxes('default');
hFigCorr.addPlot('hBar', @bar, lagTime, intCount, 1);
hFigCorr.axApply('default', @xlabel, 'Time (ms)');
hFigCorr.axApply('default', @ylabel, 'Counts');
hFigCorr.axApply('default', @grid, 'on');
hFigCorr.axApply('default', @set, 'YScale', 'log');
else
hFigCorr.updatePlot('hBar', lagTime, intCount);
end
if iCluster ~= jCluster
hFigCorr.axApply('default', @title, sprintf('Unit %d vs. Unit %d', iCluster, jCluster));
else
hFigCorr.axApply('default', @title, sprintf('Unit %d', iCluster));
end
hFigCorr.axApply('default', @set, 'XLim', jitterMs*[-nLags, nLags]);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
updateFigPSTH.m
|
.m
|
JRCLUST-main/+jrclust/+curate/@CurateController/updateFigPSTH.m
| 6,955 |
utf_8
|
f0738a893240f71aad9cc5d5b067854e
|
function updateFigPSTH(obj, doCreate)
%UPDATEFIGPSTH
if ~doCreate && (~obj.hasFig('FigTrial1') || ~obj.hasFig('FigTrial2'))
return;
end
if doCreate
[hFigTrial1, hFigTrial2] = doPlotFigPSTH(obj.hClust, [], [], obj.selected);
else
hFigTrial1 = obj.hFigs('FigTrial1');
if ~hFigTrial1.isReady % plot is closed
return;
end
hFigTrial2 = obj.hFigs('FigTrial2');
[hFigTrial1, hFigTrial2] = doPlotFigPSTH(obj.hClust, hFigTrial1, hFigTrial2, obj.selected);
end
obj.hFigs('FigTrial1') = hFigTrial1;
obj.hFigs('FigTrial2') = hFigTrial2;
end
%% LOCAL FUNCTIONS
function [hFigTrial1, hFigTrial2] = doPlotFigPSTH(hClust, hFigTrial1, hFigTrial2, selected)
%DOPLOTFIGPSTH Plot PSTH figures
hCfg = hClust.hCfg;
% begin TW block
if isempty(hCfg.trialFile)
if exist(jrclust.utils.subsExt(hCfg.configFile, '.starts.mat'), 'file')
hCfg.trialFile = jrclust.utils.subsExt(hCfg.configFile, '.starts.mat');
elseif exist(jrclust.utils.subsExt(hCfg.configFile, '.mat'), 'file')
hCfg.trialFile = jrclust.utils.subsExt(hCfg.configFile, '.mat');
else
jrclust.utils.qMsgBox('''trialFile'' not set. Reload .prm file after setting (under "File menu")');
return;
end
end
% end TW block
% import trial times
trialTimes = jrclust.utils.loadTrialFile(hCfg.trialFile);
if ~iscell(trialTimes)
trialTimes = {trialTimes};
end
if isempty(trialTimes) % failed to load
jrclust.utils.qMsgBox('Trial file does not exist', 0, 1);
return;
end
nStims = numel(trialTimes);
% plot primary/secondary figures
axOffset = 0.08;
axLen = 1/nStims;
if ~jrclust.utils.isvalid(hFigTrial1) || ~hFigTrial1.isReady
hFigTrial1 = jrclust.views.Figure('FigTrial1', [.5 .5 .5 .5], hCfg.trialFile, 0, 0);
for iStim = 1:nStims
iOffset = axOffset + (iStim-1) * axLen;
hFigTrial1.addAxes(sprintf('stim%d1', iStim), 'Position', [axOffset iOffset .9 axLen*.68]);
hFigTrial1.addAxes(sprintf('stim%d2', iStim), 'Position', [axOffset iOffset + axLen*.68 .9 axLen*.2]);
end
hFigTrial1.figData.color = 'k';
end
plot_figure_psth_(hFigTrial1, selected(1), trialTimes, hClust, hCfg);
if ~jrclust.utils.isvalid(hFigTrial2) || ~hFigTrial2.isReady
hFigTrial2 = jrclust.views.Figure('FigTrial2', [.5 0 .5 .5], hCfg.trialFile, 0, 0);
hFigTrial2.figApply(@set, 'Visible', 'off');
for iStim = 1:nStims
iOffset = axOffset + (iStim-1) * axLen;
hFigTrial2.addAxes(sprintf('stim%d1', iStim), 'Position', [axOffset iOffset .9 axLen*.68]);
hFigTrial2.addAxes(sprintf('stim%d2', iStim), 'Position', [axOffset iOffset + axLen*.68 .9 axLen*.2]);
end
hFigTrial2.figData.color = 'r';
end
% show this plot iff we have a second selected cluster
if numel(selected) == 2
hFigTrial2.figApply(@set, 'Visible', 'on');
plot_figure_psth_(hFigTrial2, selected(2), trialTimes, hClust, hCfg);
else
hFigTrial2.figApply(@set, 'Visible', 'off');
end
end
function plot_figure_psth_(hFigTrial, iCluster, trialTimes, hClust, hCfg)
% [vhAx1, vhAx2] = deal(S_fig.vhAx1, S_fig.vhAx2, S_fig.vcColor);
hAxes = keys(hFigTrial.hAxes);
nStims = numel(hAxes)/2;
for iStim = 1:nStims
axKey1 = sprintf('stim%d1', iStim); hAx1 = hFigTrial.hAxes(axKey1); cla(hAx1);
axKey2 = sprintf('stim%d2', iStim); hAx2 = hFigTrial.hAxes(axKey2); cla(hAx2);
iTrialTimes = trialTimes{iStim}; %(:,1);
nTrials = numel(iTrialTimes);
clusterTimes = hClust.spikeTimes(hClust.spikesByCluster{iCluster});
plot_raster_clu_(clusterTimes, iTrialTimes, hCfg, hAx1);
plot_psth_clu_(clusterTimes, iTrialTimes, hCfg, hAx2, hFigTrial.figData.color);
hFigTrial.axApply(axKey2, @title, sprintf('Unit %d; %d trials', iCluster, nTrials));
end
if nStims > 1
arrayfun(@(i) hFigTrial.axApply(sprintf('stim%d1', i), @set, 'XTickLabel', {}), 2:nStims);
arrayfun(@(i) hFigTrial.axApply(sprintf('stim%d1', i), @xlabel, ''), 2:nStims);
end
end
function plot_raster_clu_(clusterTimes, trialTimes, hCfg, hAx)
trialLength = diff(hCfg.psthTimeLimits); % seconds
nTrials = numel(trialTimes);
spikeTimes = cell(nTrials, 1);
t0 = -hCfg.psthTimeLimits(1);
for iTrial = 1:nTrials
rTime_trial1 = trialTimes(iTrial);
vrTime_lim1 = rTime_trial1 + hCfg.psthTimeLimits;
vrTime_clu1 = double(clusterTimes) / hCfg.sampleRate;
vrTime_clu1 = vrTime_clu1(vrTime_clu1>=vrTime_lim1(1) & vrTime_clu1<vrTime_lim1(2));
vrTime_clu1 = (vrTime_clu1 - rTime_trial1 + t0) / trialLength;
spikeTimes{iTrial} = vrTime_clu1';
end
% Plot
plotSpikeRaster(spikeTimes,'PlotType','vertline','RelSpikeStartTime',0,'XLimForCell',[0 1], ...
'LineFormat', struct('LineWidth', 1.5), 'hAx', hAx);
ylabel(hAx, 'Trial #')
% title('Vertical Lines With Spike Offset of 10ms (Not Typical; for Demo Purposes)');
vrXTickLabel = hCfg.psthTimeLimits(1):(hCfg.psthXTick):hCfg.psthTimeLimits(2);
vrXTick = linspace(0,1,numel(vrXTickLabel));
set(hAx, {'XTick', 'XTickLabel'}, {vrXTick, vrXTickLabel});
grid(hAx, 'on');
hold(hAx, 'on');
plot(hAx, [t0,t0]/trialLength, get(hAx,'YLim'), 'r-');
xlabel(hAx, 'Time (s)');
end
function plot_psth_clu_(clusterTimes, trialTimes, hCfg, hAx, vcColor)
tbin = hCfg.psthTimeBin;
nbin = round(tbin * hCfg.sampleRate);
nlim = round(hCfg.psthTimeLimits/tbin);
viTime_Trial = round(trialTimes / tbin);
vlTime1 = zeros(0);
vlTime1(ceil(double(clusterTimes)/nbin)) = 1;
mr1 = vr2mr2_(double(vlTime1), viTime_Trial, nlim);
vnRate = mean(mr1,2) / tbin;
vrTimePlot = (nlim(1):nlim(end))*tbin + tbin/2;
bar(hAx, vrTimePlot, vnRate, 1, 'EdgeColor', 'none', 'FaceColor', vcColor);
vrXTick = hCfg.psthTimeLimits(1):(hCfg.psthXTick):hCfg.psthTimeLimits(2);
set(hAx, 'XTick', vrXTick, 'XTickLabel', []);
grid(hAx, 'on');
hold(hAx, 'on');
plot(hAx, [0 0], get(hAx, 'YLim'), 'r-');
ylabel(hAx, 'Rate (Hz)');
xlim(hAx, hCfg.psthTimeLimits);
end
function mr = vr2mr2_(vr, viRow, spkLim, viCol)
if nargin<4, viCol = []; end
% JJJ 2015 Dec 24
% vr2mr2: quick version and doesn't kill index out of range
% assumes vi is within range and tolerates spkLim part of being outside
% works for any datatype
% prepare indices
if size(viRow,2)==1, viRow=viRow'; end %row
viSpk = int32(spkLim(1):spkLim(end))';
miRange = bsxfun(@plus, viSpk, int32(viRow));
miRange = min(max(miRange, 1), numel(vr));
if isempty(viCol)
mr = vr(miRange); %2x faster
else
mr = vr(miRange, viCol); %matrix passed to save time
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
plotSpikeRaster.m
|
.m
|
JRCLUST-main/+jrclust/+curate/@CurateController/private/plotSpikeRaster.m
| 22,307 |
utf_8
|
b29427c15f3ba89c49569d15d619f12a
|
function [xPoints, yPoints] = plotSpikeRaster(spikes,varargin)
% PLOTSPIKERASTER Create raster plot from binary spike data or spike times
% Efficiently creates raster plots with formatting support. Faster than
% common implementations. Multiple plot types and parameters available!
% Look at Parameters section below.
%
% Inputs:
% M x N logical array (binary spike data):
% where M is the number of trials and N is the number of time
% bins with maximum of 1 spike per bin. Assumes time starts at 0.
% M x 1 cell of spike times:
% M is the number of trials and each cell contains a 1 x N vector
% of spike times. Units should be in seconds.
%
% Output:
% xPoints - vector of x points used for the plot.
% yPoints - vector of y points used for the plot.
%
% Parameters:
% PlotType - default 'horzline'. Several types of plots available:
% 1. 'horzline' - plots spikes as gray horizontal lines.
% 2. 'vertline' - plots spikes as vertical lines, centered
% vertically on the trial number.
% 3. 'scatter' - plots spikes as gray dots.
%
% ONLY FOR BINARY SPIKE DATA:
% 4. 'imagesc' - plots using imagesc. Flips colormap so
% black indicates a spike. Not affected by SpikeDuration,
% RelSpikeStartTime, and similar timing parameters.
% 5. 'horzline2' - more efficient plotting than horzline if
% you have many timebins, few trials, and high spike density.
% Note: SpikeDuration parameter DOES NOT WORK IF LESS THAN
% TIME PER BIN.
% 6. 'vertline2' - more efficient plotting than vertline if
% you have few timebins, many trials, and high spike density.
% Note: Horzline and vertline should be fine for most tasks.
%
% FigHandle - default gcf (get current figure).
% Specify a specific figure or subplot to plot in. If no figure
% is specified, plotting will occur on the current figure. If no
% figure is available, a new figure will be created.
%
% LineFormat - default line is gray. Used for 'horzline' and
% 'vertline' plots only. Usage example:
% LineFormat = struct()
% LineFormat.Color = [0.3 0.3 0.3];
% LineFormat.LineWidth = 0.35;
% LineFormat.LineStyle = ':';
% plotSpikeRaster(spikes,'LineFormat',LineFormat)
%
% MarkerFormat - default marker is a gray dot with size 1. Used for
% scatter type plots only. Usage is the same as LineFormat.
%
% AutoLabel - default 0.
% Automatically labels x-axis as 'Time (ms)' or 'Time (s)' and
% y-axis as 'Trial'.
%
% XLimForCell - default [NaN NaN].
% Sets x-axis window limits if using cell spike time data. If
% unchanged, the default limits will be 0.05% of the range. For
% better performance, this parameter should be set.
%
% TimePerBin - default 0.001 (1 millisecond).
% Sets the duration of each timebin for binary spike train data.
%
% SpikeDuration - default 0.001 (1 millisecond).
% Sets the horizontal spike length for cell spike time data.
%
% RelSpikeStartTime - default 0 seconds.
% Determines the starting point of the spike relative to the time
% indicated by spike times or time bins. For example, a relative
% spike start time of -0.0005 would center 1ms spikes for a
% horzline plot of binary spike data.
%
% rasterWindowOffset - default NaN
% Exactly the same as relSpikeStartTime, but unlike
% relSpikeStartTime, the name implies that it can be used to make
% x-axis start at a certain time. If set, takes precedence over
% relSpikeStartTime.
%
% VertSpikePosition - default 0 (centered on trial).
% Determines where the spike position is relative to the trial. A
% value of 0 is centered on the trial number - so a spike on
% trial 3 would have its y-center on 3. Example: A common type of
% spike raster plots vertical spikes from previous trial to
% current trial. Set VertSpikePosition to -0.5 to center the
% spike between trials.
%
% VertSpikeHeight - default 1 (spans 1 trial).
% Determines height of spike for 'vertline' plots. Decrease to
% separate trials with a gap.
%
% Examples:
% plotSpikeRaster(spikeTimes);
% Plots raster plot with horizontal lines.
%
% plotSpikeRaster(spikeTimes,'PlotType','vertline');
% Plots raster plot with vertical lines.
%
% plotSpikeRaster(spikeTimes,'FigHandle',h,'AutoLabel',1,...
% 'XLimForCell',[0 10],'HorzSpikeLength',0.002,);
% Plots raster plot on figure with handle h using horizontal
% lines of length 0.002, with a window from 0 to 10 seconds,
% and automatic labeling.
%
% plotSpikeRaster(spikeTimes,'PlotType','scatter',...
% 'MarkerFormat',MarkerFormat);
% Plots raster plot using dots with a format specified by
% MarkerFormat.
%% AUTHOR : Jeffrey Chiou
%% $DATE : 07-Feb-2014 12:15:47 $
%% $Revision : 1.2 $
%% DEVELOPED : 8.1.0.604 (R2013a)
%% FILENAME : plotSpikeRaster.m
%% Set Defaults and Load optional arguments
LineFormat.Color = [0.2 0.2 0.2];
MarkerFormat.MarkerSize = 1;
MarkerFormat.Color = [0.2 0.2 0.2];
MarkerFormat.LineStyle = 'none';
p = inputParser;
p.addRequired('spikes',@(x) islogical(x) || iscell(x));
p.addParamValue('FigHandle',gcf,@isinteger);
p.addParamValue('PlotType','horzLine',@ischar);
p.addParamValue('LineFormat',LineFormat,@isstruct)
p.addParamValue('MarkerFormat',MarkerFormat,@isstruct);
p.addParamValue('AutoLabel',0, @islogical);
p.addParamValue('XLimForCell',[NaN NaN],@(x) isnumeric(x) && isvector(x));
p.addParamValue('TimePerBin',0.001,@(x) isnumeric(x) && isscalar(x));
p.addParamValue('SpikeDuration',0.001,@(x) isnumeric(x) && isscalar(x));
p.addParamValue('RelSpikeStartTime',0,@(x) isnumeric(x) && isscalar(x));
p.addParamValue('RasterWindowOffset',NaN,@(x) isnumeric(x) && isscalar(x));
p.addParamValue('VertSpikePosition',0,@(x) isnumeric(x) && isscalar(x));
p.addParamValue('VertSpikeHeight',1,@(x) isnumeric(x) && isscalar(x));
p.addParamValue('hAx',gca,@ishandle); % 122917 JJJ: axes handle
p.parse(spikes,varargin{:});
spikes = p.Results.spikes;
figH = p.Results.FigHandle;
plotType = lower(p.Results.PlotType);
lineFormat = struct2opt(p.Results.LineFormat);
markerFormat = struct2opt(p.Results.MarkerFormat);
autoLabel = p.Results.AutoLabel;
xLimForCell = p.Results.XLimForCell;
timePerBin = p.Results.TimePerBin;
spikeDuration = p.Results.SpikeDuration;
relSpikeStartTime = p.Results.RelSpikeStartTime;
rasterWindowOffset = p.Results.RasterWindowOffset;
vertSpikePosition = p.Results.VertSpikePosition;
vertSpikeHeight = p.Results.VertSpikeHeight;
hAx = p.Results.hAx; % 122917 JJJ: axes handle
if ~isnan(rasterWindowOffset) && relSpikeStartTime==0
relSpikeStartTime = rasterWindowOffset;
elseif ~isnan(rasterWindowOffset) && relSpikeStartTime~=0
disp(['Warning: RasterWindoWOffset and RelSpikeStartTime perform the same function. '...
'The value set in RasterWindowOffset will be used over RelSpikesStartTime']);
relSpikeStartTime = rasterWindowOffset;
end
%% Initialize figure and begin plotting logic
% figure(figH);
hold(hAx, 'on');
if islogical(spikes)
%% Binary spike train matrix case. Initialize variables and set axes.
nTrials = size(spikes,1);
nTimes = size(spikes,2);
% Convert Parameters to correct units using TimePerBin. Default is 1 ms
% per bin (0.001s)
spikeDuration = spikeDuration/timePerBin;
relSpikeStartTime = relSpikeStartTime/timePerBin;
% Note: xlim and ylim are much, much faster than axis or set(gca,...).
xlim(hAx, [0+relSpikeStartTime nTimes+1+relSpikeStartTime]);
ylim(hAx, [0 nTrials+1]);
switch plotType
case 'horzline'
%% Horizontal Lines
% Find the trial (yPoints) and timebin (xPoints) of each spike
[trials,timebins] = find(spikes);
trials = trials';
timebins = timebins';
xPoints = [ timebins + relSpikeStartTime;
timebins + relSpikeStartTime + spikeDuration;
NaN(size(timebins)) ];
yPoints = [ trials + vertSpikePosition;
trials + vertSpikePosition;
NaN(size(trials)) ];
xPoints = xPoints(:);
yPoints = yPoints(:);
plot(hAx, xPoints,yPoints,'k',lineFormat{:});
case 'vertline'
%% Vertical Lines
% Find the trial (yPoints) and timebin (xPoints) of each spike
[trials,timebins] = find(spikes);
trials = trials';
timebins = timebins';
halfSpikeHeight = vertSpikeHeight/2;
xPoints = [ timebins + relSpikeStartTime;
timebins + relSpikeStartTime;
NaN(size(timebins)) ];
yPoints = [ trials - halfSpikeHeight + vertSpikePosition;
trials + halfSpikeHeight + vertSpikePosition;
NaN(size(trials)) ];
xPoints = xPoints(:);
yPoints = yPoints(:);
plot(hAx, xPoints,yPoints,'k',lineFormat{:});
case 'horzline2'
%% Horizontal lines, for many timebins
% Plots a horizontal line the width of a time bin for each
% spike. Efficient for fewer trials and many timebins.
xPoints = [];
yPoints = [];
for trials = 1:nTrials
% If there are spikes, plot a line. Otherwise, do nothing.
if sum(spikes(trials,:)) > 0
% Find the difference in spike times. Padding at the
% front and back with a zero accounts for spikes in
% the first and last indices, and keeps startY and endY
% the same size
spikeDiff = diff([0 spikes(trials,:) 0]);
% Ex. [0 1 1] -> [0 0 1 1 0]. diff(...) -> [0 1 0 -1]
% Find line segments to plot (line segments longer than
% one trial are for spikes on consecutive trials)
startX = find(spikeDiff > 0);
% Ex. cont. from above: find(...) -> 2
endX = find(spikeDiff < 0);
% Ex. cont. from above: find(...) -> 4. Thus a line
% segment will be defined from 2 to 4 (x-axis)
% Combine x points and adjust x points according to
% parameters. Add Add NaNs to break up line segments.
trialXPoints = [startX + relSpikeStartTime;...
endX + relSpikeStartTime + (spikeDuration - 1);...
NaN(size(startX)) ];
% Explanation for 'spikeDuration - 1': spikeDuration
% has been converted already using timePerBin, so the
% offset at the end is simply duration - one timeBin,
% since 1 timebin's worth of spikes has passed. Only
% affects last spike if less than time per bin.
% Convert x points array to vector
trialXPoints = trialXPoints(:)';
% Add y points centered on the trial by default
% (adjustable with vertSpikePosition parameter)
trialYPoints = trials*ones(size(trialXPoints)) + vertSpikePosition;
% Store this trial's x and y points. Unfortunately,
% preallocating and trimming may actually be slower,
% depending on data.
xPoints = [xPoints trialXPoints];
yPoints = [yPoints trialYPoints];
end
end
plot(hAx, xPoints, yPoints,'k', lineFormat{:});
case 'vertline2'
%% Vertical lines, for many trials
% Plot one long line for each timebin. Reduces the number of
% objects to plot. Efficient for many trials and fewer timebins
xPoints = [];
yPoints = [];
for time = 1:nTimes
if sum(spikes(:,time)) > 0
% Find the difference in spike times. Same principle as
% horzline2. See comments above for explanation.
spikeDiff = diff([0 spikes(:,time)' 0]);
% Find line segments to plot (line segments longer than
% one trial are for spikes on consecutive trials)
startY = find(spikeDiff > 0);
endY = find(spikeDiff < 0);
% Add NaNs to break up line segments
timeBinYPoints = [startY + vertSpikePosition;...
endY + vertSpikePosition; NaN(size(startY))];
% Convert to vector
timeBinYPoints = timeBinYPoints(:)';
timeBinXPoints = time*ones(size(timeBinYPoints));
% Store this timebin's x and y points.
xPoints = [xPoints timeBinXPoints];
% Subtract 0.5 from each y point so spikes are centered
% by default (adjustable with vertSpikePosition)
yPoints = [yPoints timeBinYPoints-0.5];
end
end
plot(hAx, xPoints, yPoints, 'k', lineFormat{:});
case 'scatter'
%% Dots or other markers (scatterplot style)
% Find the trial (yPoints) and timebin (xPoints) of each
% spike
[yPoints,xPoints] = find(spikes==1);
xPoints = xPoints + relSpikeStartTime;
plot(hAx, xPoints,yPoints,'.k',markerFormat{:});
case 'imagesc'
%% Imagesc
imagesc(spikes);
% Flip the colormap since the default is white for 1, black for
% 0.
colormap(flipud(colormap('gray')));
otherwise
error('Invalid plot type. Must be horzline, vertline, horzline2, vertline2, scatter, or imagesc');
end % switch
set(hAx,'YDir','reverse');
%% Label
if autoLabel
xlabel(hAx, 'Time (ms)');
ylabel(hAx, 'Trial');
end
else % Equivalent to elseif iscell(spikes).
%% Cell case
% Validation: First check to see if cell array is a vector, and each
% trial within is a vector.
if ~isvector(spikes)
error('Spike cell array must be an M x 1 vector.')
end
trialIsVector = cellfun(@isvector,spikes);
if sum(trialIsVector) < length(spikes)
error('Cells must contain 1 x N vectors of spike times.');
end
% Now make sure cell array is M x 1 and not 1 x M.
if size(spikes,2) > 1 && size(spikes,1) == 1
spikes = spikes';
end
% Make sure each trial is 1 x N and not N x 1
nRowsInTrial = cellfun(@(x) size(x,1),spikes);
% If there is more than 1 row in any trial, add a warning, and
% transpose those trials. Allows for empty trials/cells (nRows > 1
% instead of > 0).
if sum(nRowsInTrial > 1) > 0
trialsToReformat = find(nRowsInTrial > 1);
disp('Warning - some cells (trials) have more than 1 row. Those trials will be transposed.');
for t = trialsToReformat
spikes{trialsToReformat} = spikes{trialsToReformat}';
end
end
nTrials = length(spikes);
% Find x-axis limits that aren't manually set (default [NaN NaN]), and
% automatically set them. This is because we don't assume spikes start
% at 0 - we can have negative spike times.
limitsToSet = isnan(xLimForCell);
if sum(limitsToSet) > 0
% First find range of spike times
minTimes = cellfun(@min,spikes,'UniformOutput',0);
minTime = min( [ minTimes{:} ] );
maxTimes = cellfun(@max,spikes,'UniformOutput',0);
maxTime = max( [ maxTimes{:} ] );
timeRange = maxTime - minTime;
% Find 0.05% of the range.
xStartOffset = relSpikeStartTime - 0.0005*timeRange;
xEndOffset = relSpikeStartTime + 0.0005*timeRange + spikeDuration;
newLim = [ minTime+xStartOffset, maxTime+xEndOffset ];
xLimForCell(limitsToSet) = newLim(limitsToSet);
% End result, if both limits are automatically set, is that the x
% axis is expanded 0.1%, so you can see initial and final spikes.
end
xlim(hAx, xLimForCell);
ylim(hAx, [0 nTrials+1]);
if strcmpi(plotType,'vertline') || strcmpi(plotType,'horzline')
%% Vertical or horizontal line logic
nTotalSpikes = sum(cellfun(@length,spikes));
% Preallocation is possible since we know how many points to
% plot, unlike discrete case. 3 points per spike - the top pt,
% bottom pt, and NaN.
xPoints = NaN(nTotalSpikes*3,1);
yPoints = xPoints;
currentInd = 1;
if strcmpi(plotType,'vertline')
%% Vertical Lines
halfSpikeHeight = vertSpikeHeight/2;
for trials = 1:nTrials
nSpikes = length(spikes{trials});
nanSeparator = NaN(1,nSpikes);
trialXPoints = [ spikes{trials} + relSpikeStartTime;...
spikes{trials} + relSpikeStartTime; nanSeparator ];
trialXPoints = trialXPoints(:);
trialYPoints = [ (trials-halfSpikeHeight)*ones(1,nSpikes);...
(trials+halfSpikeHeight)*ones(1,nSpikes); nanSeparator ];
trialYPoints = trialYPoints(:);
% Save points and update current index
xPoints(currentInd:currentInd+nSpikes*3-1) = trialXPoints;
yPoints(currentInd:currentInd+nSpikes*3-1) = trialYPoints;
currentInd = currentInd + nSpikes*3;
end
else % (if plotType is 'horzline')
%% Horizontal Lines
for trials = 1:nTrials
nSpikes = length(spikes{trials});
nanSeparator = NaN(1,nSpikes);
trialXPoints = [ spikes{trials} + relSpikeStartTime;...
spikes{trials} + relSpikeStartTime + spikeDuration;...
nanSeparator ];
trialXPoints = trialXPoints(:);
trialYPoints = [ trials*ones(1,nSpikes);...
trials*ones(1,nSpikes); nanSeparator ];
trialYPoints = trialYPoints(:);
% Save points and update current index
xPoints(currentInd:currentInd+nSpikes*3-1) = trialXPoints;
yPoints(currentInd:currentInd+nSpikes*3-1) = trialYPoints;
currentInd = currentInd + nSpikes*3;
end
end
% Plot everything at once! We will reverse y-axis direction later.
plot(hAx, xPoints, yPoints, 'k', lineFormat{:});
elseif strcmpi(plotType,'scatter')
%% Dots or other markers (scatterplot style)
% Combine all spike times into one vector
xPoints = [ spikes{:} ];
% Getting the trials is trickier. 3 steps:
% 1. First convert all the spike times into ones.
trials = cellfun( @(x) {ones(size(x))}, spikes );
% 2. Then multiply by trial number.
for trialNum = 1:length(spikes)
trials{trialNum} = trialNum*trials{trialNum};
end
% 3. Finally convert into a vector
yPoints = [ trials{:} ];
% Now we can plot! We will reverse y-axis direction later.
plot(hAx, xPoints,yPoints,'.k',markerFormat{:});
elseif strcmpi(plotType,'imagesc') || strcmpi(plotType,'vertline2') || strcmpi(plotType,'horzline2')
error('Can''t use imagesc/horzline2/vertline2 with cell array. Use with logical array of binary spike train data.');
else
error('Invalid plot type. With cell array of spike times, plot type must be horzline, vertline, or scatter.');
end % plot type switching
%% Reverse y-axis direction and label
set(hAx,'YDir','reverse');
if autoLabel
xlabel(hAx, 'Time (s)');
ylabel(hAx, 'Trial');
end
end % logical vs cell switching
%% Figure formatting
% Draw the tick marks on the outside
set(hAx,'TickDir','out')
% Use special formatting if there is only a single trial.
% Source - http://labrigger.com/blog/2011/12/05/raster-plots-and-matlab/
if size(spikes,1) == 1
set(hAx,'YTick', []) % don't draw y-axis ticks
set(hAx,'PlotBoxAspectRatio',[1 0.05 1]) % short and wide
set(hAx,'YColor',get(gcf,'Color')) % hide the y axis
ylim(hAx, [0.5 1.5])
end
hold(hAx, 'off');
end % main function
function paramCell = struct2opt(paramStruct)
% Converts structure to parameter-value pairs
% Example usage:
% formatting = struct()
% formatting.color = 'black';
% formatting.fontweight = 'bold';
% formatting.fontsize = 24;
% formatting = struct2opt(formatting);
% xlabel('Distance', formatting{:});
% Adapted from:
% http://stackoverflow.com/questions/15013026/how-can-i-unpack-a-matlab-structure-into-function-arguments
% by user 'yuk'
fname = fieldnames(paramStruct);
fval = struct2cell(paramStruct);
paramCell = [fname, fval]';
paramCell = paramCell(:);
end % struct2opt
|
github
|
JaneliaSciComp/JRCLUST-main
|
getSiteFeatures.m
|
.m
|
JRCLUST-main/+jrclust/+features/getSiteFeatures.m
| 3,839 |
utf_8
|
135c82bfa678ea499e17be8c8429b907
|
% function [mrFet12_, viSpk12_, n1_, n2_, viiSpk12_ord_] = fet12_site_(trFet_spk, S0, P, iSite, vlRedo_spk)
function [siteFeatures, spikes, n1, n2, spikeOrder] = getSiteFeatures(spikeFeatures, site, spikeData, hCfg)
%GETSITEFEATURES Get features occurring on primary and secondary (optionally tertiary) sites
[siteFeatures, spikes, n1, n2, spikeOrder] = deal([]);
[spikes2, spikes3, timeFeature] = deal([]);
[nFeatures, nPeaksFeatures, ~] = size(spikeFeatures);
timeFeatureFactor = hCfg.getOr('timeFeatureFactor', 0); % TW
if ~isfield(spikeData, 'spikes1') || isempty(spikeData.spikes1)
return;
end
spikes1 = int32(spikeData.spikes1);
if isfield(spikeData, 'spikes2')
spikes2 = int32(spikeData.spikes2);
end
if isfield(spikeData, 'spikes3')
spikes3 = int32(spikeData.spikes3);
end
if isfield(spikeData, 'vlRedo_spk') && ~isempty(spikeData.vlRedo_spk)
spikes1 = spikes1(spikeData.vlRedo_spk(spikes1));
spikes2 = spikes2(spikeData.vlRedo_spk(spikes2));
spikes3 = spikes3(spikeData.vlRedo_spk(spikes3));
end
% compute time feature (last entry of feature vector
if timeFeatureFactor ~= 0
times1 = single(spikeData.spikeTimes(spikes1))'; % row vector
times2 = single(spikeData.spikeTimes(spikes2))'; % row vector or empty
times3 = single(spikeData.spikeTimes(spikes3))'; % row vector or empty
timeFeature = timeFeatureFactor * [times1 times2 times3];
end
% features from the first peak
n1 = numel(spikes1);
siteFeatures = getPeakFeature(spikeFeatures(:, 1, spikes1), nFeatures, n1);
% features from the second peak
if nPeaksFeatures > 1
n2 = numel(spikes2);
sf2 = getPeakFeature(spikeFeatures(:, 2, spikes2), nFeatures, n2);
siteFeatures = [siteFeatures sf2];
end
% features from the third peak
if nPeaksFeatures > 2
n3 = numel(spikes3);
sf3 = getPeakFeature(spikeFeatures(:, 3, spikes3), nFeatures, n3);
siteFeatures = [siteFeatures sf3];
n2 = n2 + n3;
end
% scale time feature (no effect if empty) and add to siteFeatures
timeFeature = timeFeature*std(siteFeatures(1, :))/std(timeFeature);
siteFeatures = [siteFeatures; timeFeature];
% weight features by distance from site, greater for nearer sites
nSites = hCfg.nSitesEvt;
try
if hCfg.weightFeatures && nSites >= hCfg.minSitesWeightFeatures
nFeaturesPerSite = size(siteFeatures, 1) / nSites;
weights = distWeight(site, nSites, hCfg);
weights = repmat(weights(:), [nFeaturesPerSite, 1]);
siteFeatures = bsxfun(@times, siteFeatures, weights(:));
end
catch ME
warning('error in distWeight: ''%s'', using unweighted features', ME.message);
end
% concatenate all spikes
spikes = [spikes1; spikes2; spikes3];
spikeOrder = jrclust.utils.rankorder(spikes, 'ascend');
end
%% LOCAL FUNCTIONS
function weights = distWeight(site, nSites, hCfg)
%DISTWEIGHT Compute weights for neighboring sites, larger for nearer
siteLoc = hCfg.siteLoc(hCfg.siteNeighbors(1:nSites, site), :);
siteDists = pdist2(siteLoc(1, :), siteLoc);
weights = 2.^(-siteDists/hCfg.evtDetectRad);
weights = weights(:);
end
function feat = getPeakFeature(feat, nFeatures, nSpikes)
%GETPEAKFEATURES Reshape feat to nFeatures x nSpikes if necessary.
feat = squeeze(feat);
[d1, d2] = size(feat);
% either 1, in which case a scalar, or n > 1, in which case leave alone
if nSpikes == nFeatures || (d1 == nFeatures && d2 == nSpikes)
return;
end
if d1 == nSpikes && d2 == nFeatures
feat = feat';
else
error('Expected dimensions [%d, %d], got [%d, %d]', feat, nSpikes, d1, d2);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
spikePCA.m
|
.m
|
JRCLUST-main/+jrclust/+features/spikePCA.m
| 3,141 |
utf_8
|
a809fa3606e52f01c9d50ca9e8bc9868
|
function [features1, features2, features3] = spikePCA(spikeWindows, hCfg)
%SPIKEPCA Project spikes onto their principal components
% if strcmpi(hCfg.vcFet, 'pca')
prVecs = spikePrVecs(spikeWindows, hCfg);
% else
% mrPv_global = get0_('mrPv_global');
% if isempty(mrPv_global)
% [mrPv_global, vrD_global] = spikePrVecs(spikeWindows, hCfg);
% [mrPv_global, vrD_global] = jrclust.utils.tryGather(mrPv_global, vrD_global);
% set0_(mrPv_global, vrD_global);
% end
% prVecs = mrPv_global;
% end
[features1, features2, features3] = projectInterp(spikeWindows, prVecs, hCfg);
end
%% LOCAL FUNCTIONS
function [prVecs, eigVals] = spikePrVecs(spikeWindows, hCfg)
%SPIKEPRVECS Get principal vectors for spikes
MAX_SAMPLE = 10000;
% subsample spikes on their primary sites up to MAX_SAMPLE
ss = jrclust.utils.subsample(1:size(spikeWindows, 2), MAX_SAMPLE);
spikeSample = spikeWindows(:, ss, 1);
covMat = (spikeSample*spikeSample')/(numel(ss)-1);
[eigVecs, eigVals] = eig(covMat);
% MATLAB returns value-vector pairs smallest to largest; flip them
eigVecs = jrclust.utils.zscore(fliplr(eigVecs));
eigVals = flipud(diag(eigVals));
% spike center should be negative
iMid = 1-hCfg.evtWindowSamp(1); % sample where the spike is said to occur
sgn = (eigVecs(iMid, :) < 0) * 2 - 1; % 1 or -1 depending on the sign
prVecs = bsxfun(@times, eigVecs, sgn);
end
function [features1, features2, features3] = projectInterp(spikeWindows, prVecs, hCfg)
%PROJECTINTERP Project spikes onto principal vectors
shape = size(spikeWindows);
if ismatrix(spikeWindows)
shape(end + 1) = 1;
end
% lay the deck out left to right
spikeWaveforms = reshape(spikeWindows, shape(1), []);
prVecs = jrclust.utils.tryGather(prVecs);
% project spikes onto first PC
features1 = reshape(prVecs(:, 1)'*spikeWaveforms, shape(2:3))';
if hCfg.nPCsPerSite >= 2 % project spikes onto second PC
features2 = reshape(prVecs(:, 2)'*spikeWaveforms, shape(2:3))';
else
features2 = [];
end
if hCfg.nPCsPerSite == 3 % project spikes onto third PC
features3 = reshape(prVecs(:, 3)'*spikeWaveforms, shape(2:3))';
else
features3 = [];
end
if ~hCfg.interpPC
return;
end
% find optimal delay by interpolating
vr1 = prVecs(:, 1);
vi0 = (1:numel(vr1))';
shifts = [0, -1, -.5, .5, 1];
mrPv1 = zeros(numel(vr1), numel(shifts), 'like', prVecs);
mrPv1(:, 1) = vr1;
for iShift = 2:numel(shifts)
mrPv1(:, iShift) = zscore(interp1(vi0, vr1, vi0+shifts(iShift), 'pchip', 'extrap'));
end
% find shift that maximizes the projection
[~, viMax_spk] = max(abs(mrPv1'*spikeWindows(:, :, 1)));
for iShift=2:numel(shifts)
viSpk2 = find(viMax_spk == iShift);
if isempty(viSpk2)
continue;
end
mrWav_spk2 = reshape(spikeWindows(:, viSpk2, :), shape(1), []);
features1(:, viSpk2) = reshape(mrPv1(:, iShift)'*mrWav_spk2, [], shape(3))';
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
sortNat.m
|
.m
|
JRCLUST-main/+jrclust/+utils/sortNat.m
| 3,392 |
utf_8
|
498433183b844c5d271ba88620263f85
|
%--------------------------------------------------------------------------
function [cs,index] = sortNat(c,mode)
%sort_nat: Natural order sort of cell array of strings.
% usage: [S,INDEX] = sort_nat(C)
%
% where,
% C is a cell array (vector) of strings to be sorted.
% S is C, sorted in natural order.
% INDEX is the sort order such that S = C(INDEX);
%
% Natural order sorting sorts strings containing digits in a way such that
% the numerical value of the digits is taken into account. It is
% especially useful for sorting file names containing index numbers with
% different numbers of digits. Often, people will use leading zeros to get
% the right sort order, but with this function you don't have to do that.
% For example, if C = {'file1.txt','file2.txt','file10.txt'}, a normal sort
% will give you
%
% {'file1.txt' 'file10.txt' 'file2.txt'}
%
% whereas, sort_nat will give you
%
% {'file1.txt' 'file2.txt' 'file10.txt'}
%
% See also: sort
% Version: 1.4, 22 January 2011
% Author: Douglas M. Schwarz
% Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
% Real_email = regexprep(Email,{'=','*'},{'@','.'})
% Set default value for mode if necessary.
if nargin < 2
mode = 'ascend';
end
% Make sure mode is either 'ascend' or 'descend'.
modes = strcmpi(mode,{'ascend','descend'});
is_descend = modes(2);
if ~any(modes)
error('sort_nat:sortDirection',...
'sorting direction must be ''ascend'' or ''descend''.')
end
% Replace runs of digits with '0'.
c2 = regexprep(c,'\d+','0');
% Compute char version of c2 and locations of zeros.
s1 = char(c2);
z = s1 == '0';
% Extract the runs of digits and their start and end indices.
[digruns,first,last] = regexp(c,'\d+','match','start','end');
% Create matrix of numerical values of runs of digits and a matrix of the
% number of digits in each run.
num_str = length(c);
max_len = size(s1,2);
num_val = NaN(num_str,max_len);
num_dig = NaN(num_str,max_len);
for i = 1:num_str
num_val(i,z(i,:)) = sscanf(sprintf('%s ',digruns{i}{:}),'%f');
num_dig(i,z(i,:)) = last{i} - first{i} + 1;
end
% Find columns that have at least one non-NaN. Make sure activecols is a
% 1-by-n vector even if n = 0.
activecols = reshape(find(~all(isnan(num_val))),1,[]);
n = length(activecols);
% Compute which columns in the composite matrix get the numbers.
numcols = activecols + (1:2:2*n);
% Compute which columns in the composite matrix get the number of digits.
ndigcols = numcols + 1;
% Compute which columns in the composite matrix get chars.
charcols = true(1,max_len + 2*n);
charcols(numcols) = 0;
charcols(ndigcols) = 0;
% Create and fill composite matrix, comp.
comp = zeros(num_str,max_len + 2*n);
comp(:,charcols) = double(s1);
comp(:,numcols) = num_val(:,activecols);
comp(:,ndigcols) = num_dig(:,activecols);
% Sort rows of composite matrix and use index to sort c in ascending or
% descending order, depending on mode.
[unused,index] = sortrows(comp);
if is_descend
index = index(end:-1:1);
end
index = reshape(index,size(c));
cs = c(index);
end %func
|
github
|
JaneliaSciComp/JRCLUST-main
|
subsample.m
|
.m
|
JRCLUST-main/+jrclust/+utils/subsample.m
| 1,217 |
utf_8
|
e82f8e8b1d845748f743dd943b0eb537
|
function [vals, vi] = subsample(vals, k, dim)
%SUBSAMPLE Sample k items from vals, optionally along dim
if nargin < 3
dim = 2;
end
if isvector(vals)
doReshape = isrow(vals);
[vals, vi] = subsampleVec(vals(:), k);
% reshape sampled values if necessary
if doReshape
vals = vals';
end
else
if isempty(intersect(dim, 1:ndims(vals)))
error('cannot sample along dimension %d', dim);
end
[vals, vi] = subsampleNd(vals, k, dim);
end
end
%% LOCAL FUNCTIONS
function [vals, inds] = subsampleVec(vals, k)
%SUBSAMPLEVEC Subsample `k` values from a vector
if isempty(k) || k >= numel(vals)
inds = 1:numel(vals);
else
inds = sort(randsample(1:numel(vals), k, 0));
end
vals = vals(inds);
end
function [vals, inds] = subsampleNd(vals, k, dim)
%SUBSAMPLEND Subsample `k` rows (or cols, or ...) from an Nd array, N >= 2
if isempty(k) || k >= size(vals, dim)
inds = 1:size(vals, dim);
else
inds = sort(randsample(1:size(vals, dim), k, 0));
end
if dim == 1
vals = vals(inds, :);
else
vals = vals(:, inds);
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
detectPeaks.m
|
.m
|
JRCLUST-main/+jrclust/+utils/detectPeaks.m
| 2,635 |
utf_8
|
ddb83097899d69049720c43cb51392ce
|
function [spikeTimes, spikeAmps, spikeSites] = detectPeaks(samplesIn, siteThresh, keepMe, hCfg)
%DETECTPEAKS Detect peaks for each site
samplesIn = jrclust.utils.tryGpuArray(samplesIn, hCfg.useGPU);
nSites = size(samplesIn, 2);
[spikesBySite, ampsBySite] = deal(cell(nSites, 1));
hCfg.updateLog('detectSpikes', 'Detecting spikes from each site', 1, 0);
for iSite = 1:nSites
% find spikes
[peakLocs, peaks] = detectPeaksSite(samplesIn(:, iSite), siteThresh(iSite), hCfg);
if isempty(keepMe)
spikesBySite{iSite} = peakLocs;
ampsBySite{iSite} = peaks;
else % reject global mean
spikesBySite{iSite} = peakLocs(keepMe(peakLocs));
ampsBySite{iSite} = peaks(keepMe(peakLocs));
end
hCfg.updateLog('detectSite', sprintf('Detected %d spikes on site %d', numel(spikesBySite{iSite}), iSite), 0, 0);
end
hCfg.updateLog('detectSpikes', 'Finished detecting spikes', 0, 1);
samplesIn = jrclust.utils.tryGather(samplesIn); %#ok<NASGU>
% Group spiking events using vrWav_mean1. already sorted by time
if hCfg.getOr('fMerge_spk', 1)
hCfg.updateLog('eventsMerged', 'Merging duplicate spiking events', 1, 0);
[spikeTimes, spikeAmps, spikeSites] = mergePeaks(spikesBySite, ampsBySite, hCfg);
hCfg.updateLog('eventsMerged', sprintf('%d spiking events found', numel(spikeTimes)), 0, 1);
else
spikeTimes = jrclust.utils.neCell2mat(spikesBySite);
spikeAmps = jrclust.utils.neCell2mat(ampsBySite);
% generate a bunch of 1's, 2's, ..., nSites's to sort later
nSpikesSite = cellfun(@(ss) numel(ss), spikesBySite);
siteOnes = cell(numel(spikesBySite), 1);
for iSite = 1:numel(spikesBySite)
siteOnes{iSite} = iSite * ones(nSpikesSite(iSite), 1);
end
spikeSites = jrclust.utils.neCell2mat(siteOnes);
% sort by time
[spikeTimes, argsort] = sort(spikeTimes, 'ascend');
spikeAmps = spikeAmps(argsort);
spikeSites = spikeSites(argsort);
end
% Group all sites in the same shank
if hCfg.groupShank
spikeSites = groupByShank(spikeSites, hCfg); % change the site location to the shank center
end
end
%% LOCAL FUNCTIONS
function [spikeSites] = groupByShank(spikeSites, hCfg)
%GROUPBYSHANK Group all spike sites by shank
site2site = zeros([hCfg.nSites, 1], 'like', spikeSites);
% remap
[~, ia, ic] = unique(hCfg.shankMap);
site2site(hCfg.siteMap) = ia(ic);
site2site = site2site(site2site > 0);
spikeSites = site2site(spikeSites);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
meanSubtract.m
|
.m
|
JRCLUST-main/+jrclust/+utils/meanSubtract.m
| 976 |
utf_8
|
39d600752638caa293c5ec831a95ef4f
|
function vals = meanSubtract(vals, dim, hFun)
%MEANSUBTRACT Subtract mean (or other statistic) from vals
if nargin < 2
dim = 1;
end
if nargin < 3
hFun = @mean;
end
if ~reallyisa(vals, 'single') && ~reallyisa(vals, 'double')
vals = single(vals);
end
% have to reshape if ndims(vals) > 2
shape = size(vals);
if numel(shape) > 2
vals = reshape(vals, shape(1), []);
end
% compute mean and subtract it from vals
vals = bsxfun(@minus, vals, hFun(vals, dim));
% restore original shape
if numel(shape) > 2
vals = reshape(vals, shape);
end
end
%% LOCAL FUNCTIONS
function flag = reallyisa(val, clsname)
%REALLYISA Like isa, but checks the underlying class if a gpuArray
try
if isa(val, 'gpuArray')
flag = strcmpi(clsname, classUnderlying(val));
else
flag = isa(val, clsname);
end
catch
flag = 0;
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
absPath.m
|
.m
|
JRCLUST-main/+jrclust/+utils/absPath.m
| 2,577 |
utf_8
|
15ef22602369c3e4645a47c0b20657e5
|
function ap = absPath(pathname, basedir)
%ABSPATH Get the absolute path of pathname (file or directory)
% Returns empty str if pathname can't be found
if nargin < 2 || ~exist(basedir, 'dir')
basedir = pwd();
elseif ~isAbsPath(basedir)
basedir = fullfile(pwd(), basedir);
end
if nargin == 0 || ~ischar(pathname) || isempty(pathname)
ap = '';
elseif strcmp(pathname, '.')
ap = pwd();
elseif exist(pathname, 'file') == 2 && ~isempty(regexp(pathname, '^\.[/\\]', 'once'))
basedir = pwd();
[~, filename, ext] = fileparts(pathname);
ap = fullfile(basedir, [filename, ext]);
elseif isAbsPath(pathname) && (exist(pathname, 'file') == 2 || exist(pathname, 'dir') == 7)
ap = pathname;
elseif any(pathname == '*') || any(pathname == '?')
% first check full file
d = dir(pathname);
if ~isempty(d)
dfolder = {d.folder};
dname = {d.name};
ap = arrayfun(@(i) fullfile(dfolder{i}, dname{i}), 1:numel(d), 'UniformOutput', 0); % cell array
else % try with basedir hint
d = dir(fullfile(basedir, pathname));
ap = fullfile(basedir, {d.name});
if isempty(ap)
ap = '';
end
end
else
if exist(fullfile(basedir, pathname), 'file') == 2 || exist(fullfile(basedir, pathname), 'dir') == 7 % check hinted directory first
ap = fullfile(basedir, pathname);
elseif exist(fullfile(pwd(), pathname), 'file') || exist(fullfile(pwd(), pathname), 'dir') % try to find it relative to current directory
ap = fullfile(pwd(), pathname);
else % can't find it, you're on your own
ap = '';
end
end
end
%% LOCAL FUNCTIONS
function iap = isAbsPath(pathname)
%ISABSPATH Return true if pathname is an absolute path
% but don't check if it actually exists or not
% On *nix, it begins with /
% On Windows, it begins with / or \ after chopping off an optional `[A-Za-z]:`
if ispc() % Windows
% chop off drive letter at beginning
truncd = regexprep(pathname, '^[a-z]:', '', 'ignorecase');
% no drive letter at the beginning; network drive?
if strcmp(truncd, pathname) && numel(pathname) > 1
iap = strcmp(pathname(1:2), '\\') || strcmp(pathname(1:2), '//');
else
iap = (all(regexp(truncd, '^[/\\]')) == 1);
end
else
iap = regexp(pathname, '^/');
iap = ~isempty(iap) && iap;
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
info.m
|
.m
|
JRCLUST-main/+jrclust/+utils/info.m
| 1,304 |
utf_8
|
c1cba019abf9a1514a48ed325d545169
|
function md = info()
%INFO Get JRCLUST repository metadata
fid = fopen(fullfile(jrclust.utils.basedir(), 'json', 'jrc.json'), 'r', 'n', 'UTF-8');
fstr = fread(fid, '*char')';
fclose(fid);
md = jsondecode(fstr);
hash = gitHash();
if ~isempty(hash)
md.version.commitHash = hash;
end
end
%% LOCAL FUNCTIONS
function h = gitHash()
h = '';
gitDir = fullfile(jrclust.utils.basedir(), '.git');
if exist(gitDir, 'dir') == 7 && exist(fullfile(gitDir, 'HEAD'), 'file') == 2
% get contents of HEAD
fid = fopen(fullfile(gitDir, 'HEAD'), 'r', 'n', 'UTF-8');
fstr = strip(fread(fid, '*char')');
fclose(fid);
refIdx = strfind(fstr, 'ref: '); % follow references
if numel(refIdx) == 1 && refIdx == 1
% remove 'ref: ' and use this path instead
refPath = strsplit(strrep(fstr, 'ref: ', ''), '/');
headPath = fullfile(gitDir, refPath{:});
if exist(headPath, 'file') == 2
fid = fopen(headPath, 'r', 'n', 'UTF-8');
fstr = strip(fread(fid, '*char')');
fclose(fid);
end
end
if ~isempty(regexp(fstr, '^[0-9a-f]{5,40}$', 'once')) % probably a commit hash
h = fstr;
end
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
carReject.m
|
.m
|
JRCLUST-main/+jrclust/+utils/carReject.m
| 2,779 |
utf_8
|
2d2169a9bda0e7aaa89378f50de0a435
|
% function [vlKeep_ref, channelMeansMAD] = carReject(vrWav_mean1, P)
function [keepMe, channelMeansMAD] = carReject(channelMeans, blankPerMs, blankThresh, sampleRate)
%CARREJECT
channelMeansMAD = [];
channelMeans = single(channelMeans);
blankWindow = ceil(sampleRate*blankPerMs/1000);
if blankWindow > 0
if nargout < 2
keepMe = threshMAD(abs(channelMeans), blankThresh);
else
[keepMe, channelMeansMAD] = threshMAD(abs(channelMeans), blankThresh);
end
if blankWindow > 1 % clear out neighbors of blanked samples
overThresh = find(~keepMe);
for crossing = overThresh'
left = max(crossing - ceil(blankWindow/2), 1);
right = min(crossing + ceil(blankWindow/2), numel(keepMe));
keepMe(left:right) = 0;
end
end
% else
% channelMeansBinned = std(padReshape(channelMeans, blankWindow), 1, 1);
% if nargout < 2
% keepMe = threshMAD(channelMeansBinned, blankThresh);
% else
% [keepMe, channelMeansMAD] = threshMAD(channelMeansBinned, blankThresh);
% channelMeansMAD = expand_vr_(channelMeansMAD, blankWindow, size(channelMeans));
% end
%
% keepMe = expand_vr_(keepMe, blankWindow, size(channelMeans));
else
[keepMe, channelMeansMAD] = deal([]);
end
end
%% LOCAL FUNCTIONS
function [keepMe, channelMeans] = threshMAD(channelMeans, madThresh)
%THRESHMAD Find which channel means fall within MAD threshold
nSubsamples = 300000;
% estimate MAD of channelMeans
med = median(jrclust.utils.subsample(channelMeans, nSubsamples));
channelMeans = channelMeans - med; % deviation from the median
mad = median(abs(jrclust.utils.subsample(channelMeans, nSubsamples)));
if isempty(madThresh) || madThresh == 0
keepMe = true(size(channelMeans));
else
keepMe = channelMeans < mad*madThresh;
end
if nargout >= 2
channelMeans = channelMeans/mad; % MAD unit
end
end
% function mat = padReshape(vec, nwin)
% %PADRESHAPE Reshape a vector to a matrix, padding if necessary
% nbins = ceil(numel(vec)/nwin);
% vec(nbins*nwin) = 0; % pad the end with zeros
% mat = reshape(vec(1:nbins*nwin), nwin, nbins);
% end
%
% function vr1 = expand_vr_(vr, nwin, shape)
% if islogical(vr)
% vr1 = false(shape);
% else
% vr1 = zeros(shape, 'like', vr);
% end
% vr = repmat(vr(:)', [nwin, 1]);
% vr = vr(:);
% [n,n1] = deal(numel(vr), numel(vr1));
% if n1 > n
% vr1(1:n) = vr;
% vr1(n+1:end) = vr1(n);
% elseif numel(vr1) < n
% vr1 = vr(1:n1);
% else
% vr1 = vr;
% end
% end
|
github
|
JaneliaSciComp/JRCLUST-main
|
mToStruct.m
|
.m
|
JRCLUST-main/+jrclust/+utils/mToStruct.m
| 1,398 |
utf_8
|
e9b307abe3fa074c1b7855f742c62208
|
function S = mToStruct(filename)
%MTOSTRUCT read and evaluate a .m script, convert workspace to struct
S = struct();
lines = jrclust.utils.readLines(filename);
lines = stripComments(lines);
if isempty(lines)
return;
end
try
eval(cell2mat(lines'));
wspace = whos();
varnames = setdiff({wspace.name}, {'lines', 'filename'});
for j = 1:numel(varnames)
eval(sprintf('a = %s;', varnames{j}));
S.(varnames{j}) = a;
end
catch ME
warning('Failed to parse %s: %s', filename, ME.message);
end
end
%% LOCAL FUNCTIONS
function lines = stripComments(lines)
lines = lines(cellfun(@(ln) ~isempty(ln), lines));
lines = cellfun(@(ln) strtrim(ln), lines, 'UniformOutput', 0);
lines = lines(cellfun(@(ln) ln(1) ~= '%', lines));
% remove comments in the middle
for i = 1:numel(lines)
iLine = lines{i};
cMarker = find(iLine == '%', 1, 'first');
if ~isempty(cMarker)
iLine = iLine(1:cMarker - 1);
end
iLine = strrep(iLine, '...', '');
if ismember(strsplit(iLine), {'for', 'end', 'if'})
lines{i} = [strtrim(iLine), ', ']; % add blank at the end
else
lines{i} = [strtrim(iLine), ' ']; % add blank at the end
end
end
lines = lines(cellfun(@(ln) ~isempty(ln), lines));
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
mergePeaks.m
|
.m
|
JRCLUST-main/+jrclust/+utils/private/mergePeaks.m
| 4,518 |
utf_8
|
8d182d5e84ef95f634a4c4fe8793ee19
|
function [spikeTimes, spikeAmps, spikeSites] = mergePeaks(spikesBySite, ampsBySite, hCfg)
%MERGEPEAKS Merge duplicate peak events
nSites = numel(spikesBySite);
spikeTimes = jrclust.utils.neCell2mat(spikesBySite);
spikeAmps = jrclust.utils.neCell2mat(ampsBySite);
spikeSites = jrclust.utils.neCell2mat(cellfun(@(vi, i) repmat(i, size(vi)), spikesBySite, num2cell((1:nSites)'), 'UniformOutput', 0));
[spikeTimes, argsort] = sort(spikeTimes);
spikeAmps = spikeAmps(argsort);
spikeSites = int32(spikeSites(argsort));
spikeTimes = int32(spikeTimes);
[mergedTimes, mergedAmps, mergedSites] = deal(cell(nSites,1));
try
% avoid sending the entire hCfg object out to workers
cfgSub = struct('refracIntSamp', hCfg.refracIntSamp, ...
'siteLoc', obj.hCfg.siteLoc, ...
'evtDetectRad', obj.hCfg.evtDetectRad);
parfor iSite = 1:nSites
try
[mergedTimes{iSite}, mergedAmps{iSite}, mergedSites{iSite}] = ...
mergeSpikesSite(spikeTimes, spikeAmps, spikeSites, iSite, cfgSub);
catch % don't try to display an error here
end
end
catch % parfor failure
for iSite = 1:nSites
try
[mergedTimes{iSite}, mergedAmps{iSite}, mergedSites{iSite}] = ...
mergeSpikesSite(spikeTimes, spikeAmps, spikeSites, iSite, hCfg);
catch ME
warning('failed to merge spikes on site %d: %s', iSite, ME.message);
end
end
end
% merge parfor output and sort
spikeTimes = jrclust.utils.neCell2mat(mergedTimes);
spikeAmps = jrclust.utils.neCell2mat(mergedAmps);
spikeSites = jrclust.utils.neCell2mat(mergedSites);
[spikeTimes, argsort] = sort(spikeTimes); % sort by time
spikeAmps = jrclust.utils.tryGather(spikeAmps(argsort));
spikeSites = spikeSites(argsort);
end
%% LOCAL FUNCTIONS
function [timesOut, ampsOut, sitesOut] = mergeSpikesSite(spikeTimes, spikeAmps, spikeSites, iSite, hCfg)
%MERGESPIKESSITE Merge spikes in the refractory period
nLims = int32(abs(hCfg.refracIntSamp));
% find neighboring spikes
nearbySites = jrclust.utils.findNearbySites(hCfg.siteLoc, iSite, hCfg.evtDetectRad); % includes iSite
spikesBySite = arrayfun(@(jSite) find(spikeSites == jSite), nearbySites, 'UniformOutput', 0);
timesBySite = arrayfun(@(jSite) spikeTimes(spikesBySite{jSite}), 1:numel(nearbySites), 'UniformOutput', 0);
ampsBySite = arrayfun(@(jSite) spikeAmps(spikesBySite{jSite}), 1:numel(nearbySites), 'UniformOutput', 0);
iiSite = (nearbySites == iSite);
iSpikes = spikesBySite{iiSite};
iTimes = timesBySite{iiSite};
iAmps = ampsBySite{iiSite};
% search over peaks on neighboring sites and in refractory period to
% see which peaks on this site to keep
keepMe = true(size(iSpikes));
for jjSite = 1:numel(spikesBySite)
jSite = nearbySites(jjSite);
jSpikes = spikesBySite{jjSite};
jTimes = timesBySite{jjSite};
jAmps = ampsBySite{jjSite};
if iSite == jSite
delays = [-nLims:-1, 1:nLims]; % skip 0 delay
else
delays = -nLims:nLims;
end
for iiDelay = 1:numel(delays)
iDelay = delays(iiDelay);
[jLocs, iLocs] = ismember(jTimes, iTimes + iDelay);
if ~any(jLocs)
continue;
end
% jLocs: index into j{Spikes,Times,Amps}
% iLocs: (1st) corresponding index into i{Spikes,Times,Amps}/keepMe
jLocs = find(jLocs);
iLocs = iLocs(jLocs);
% drop spikes on iSite where spikes on jSite have larger
% magnitudes
nearbyLarger = abs(jAmps(jLocs)) > abs(iAmps(iLocs));
keepMe(iLocs(nearbyLarger)) = 0;
% flag equal-amplitude nearby spikes
ampsEqual = (jAmps(jLocs) == iAmps(iLocs));
if any(ampsEqual)
if iDelay < 0 % drop spikes on iSite occurring later than those on jSite
keepMe(iLocs(ampsEqual)) = 0;
elseif iDelay == 0 && jSite < iSite % drop spikes on iSite if jSite is of lower index
keepMe(iLocs(ampsEqual)) = 0;
end
end
end
end
% keep the peak spikes only
timesOut = iTimes(keepMe);
ampsOut = iAmps(keepMe);
sitesOut = repmat(int32(iSite), size(timesOut));
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
detectPeaksSite.m
|
.m
|
JRCLUST-main/+jrclust/+utils/private/detectPeaksSite.m
| 3,027 |
utf_8
|
565bdacd7dce6718de33d4ff0002f066
|
function [peakLocs, peaks, siteThresh] = detectPeaksSite(samplesIn, siteThresh, hCfg)
%DETECTPEAKSSITE Detect peaks on a given site, computing threshold if necessary
% determine threshold if it has still escaped us
MAX_SAMPLE_QQ = 300000;
if ~isempty(hCfg.evtManualThreshSamp)
siteThresh = hCfg.evtManualThreshSamp;
end
if siteThresh == 0 % bad site
[peakLocs, peaks] = deal([]);
return;
end
if isempty(siteThresh)
siteThresh = hCfg.qqFactor*jrclust.utils.estimateRMS(samplesIn, MAX_SAMPLE_QQ);
end
siteThresh = cast(siteThresh, 'like', samplesIn);
% detect turning point in waveforms exceeding threshold
peakLocs = findPeaks(samplesIn, siteThresh, hCfg.minNeighborsDetect);
if hCfg.detectBipolar % detect positive peaks
peakLocs = [peakLocs; findPeaks(-samplesIn, siteThresh, hCfg.minNeighborsDetect)];
peakLocs = sort(peakLocs);
end
if isempty(peakLocs)
peakLocs = double([]);
peaks = int16([]);
else
peaks = samplesIn(peakLocs);
% remove overlarge spikes
if ~isempty(hCfg.spikeThreshMax)
threshMax = cast(abs(hCfg.spikeThreshMax)/hCfg.bitScaling, 'like', peaks);
keepMe = (abs(peaks) < abs(threshMax));
peakLocs = peakLocs(keepMe);
peaks = peaks(keepMe);
end
end
peakLocs = jrclust.utils.tryGather(peakLocs);
peaks = jrclust.utils.tryGather(peaks);
siteThresh = jrclust.utils.tryGather(siteThresh);
end
%% LOCAL FUNCTIONS
function peaks = findPeaks(samplesIn, thresh, nneighBelow)
%FINDPEAKS Find samples which exceed threshold
if isempty(nneighBelow)
nneighBelow = 1;
end
peaks = [];
if isempty(samplesIn)
return;
end
exceedsThresh = jrclust.utils.tryGather(samplesIn < -abs(thresh));
peakLocs = find(exceedsThresh);
if isempty(peakLocs)
return;
end
% got a peak at 1st sample, incomplete waveform (+ indexing error)
if peakLocs(1) <= 1 && numel(peakLocs) == 1 % only peak found, give up
return;
elseif peakLocs(1) <= 1 % discard this one, salvage the others
peakLocs(1) = [];
end
% got a peak at last sample, incomplete waveform (+ indexing error)
if peakLocs(end) >= numel(samplesIn) && numel(peakLocs) == 1 % only peak found, give up
return;
else % discard this one, salvage the others
peakLocs(end) = [];
end
peakCenters = samplesIn(peakLocs);
% take only "peaks" whose sample neighbors are not larger
peaks = peakLocs(peakCenters <= samplesIn(peakLocs + 1) & peakCenters <= samplesIn(peakLocs - 1));
if isempty(peaks)
return;
end
% take only peaks who have one or two sample neighbors exceeding threshold
if nneighBelow == 1
peaks = peaks(exceedsThresh(peaks - 1) | exceedsThresh(peaks + 1));
elseif nneighBelow == 2
peaks = peaks(exceedsThresh(peaks - 1) & exceedsThresh(peaks + 1));
end
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
probe.m
|
.m
|
JRCLUST-main/@JRC/probe.m
| 2,808 |
utf_8
|
267ae5f679c3893d30825d7e40f87e75
|
function probe(obj, probeFile)
%PROBE Plot a probe layout
if nargin > 1
[~, ~, ext] = fileparts(probeFile);
if isempty(ext) % a convenience for a forgetful mind
probeFile = [probeFile '.prb'];
end
probeFile_ = jrclust.utils.absPath(probeFile, fullfile(jrclust.utils.basedir(), 'probes'));
if isempty(probeFile_)
obj.errMsg = sprintf('Could not find probe file: %s', probeFile);
obj.isError = 1;
return;
end
showProbe(jrclust.Config(struct('probe_file', probeFile)));
elseif isempty(obj.hCfg)
obj.errMsg = 'Specify a probe file or config file';
obj.isError = 1;
return;
else
showProbe(obj.hCfg);
end
end
%% LOCAL FUNCTIONS
function showProbe(probeData)
%DOPLOTPROBE Plot a figure representing a probe
hFigProbe = jrclust.views.Figure('FigProbe', [0 0 .5 1], 'Probe', 0, 0);
vrX = 0.5*[-1 -1 1 1] * probeData.probePad(2);
vrY = 0.5*[-1 1 1 -1] * probeData.probePad(1);
uShanks = unique(probeData.shankMap);
nShanks = numel(uShanks);
[nRows, nCols] = min(ceil(nShanks ./ (1:4)), [], 2);
hFigProbe.addSubplot('hShanks', nRows, nCols);
for iShank = 1:nShanks
shank = uShanks(iShank);
shankMask = (probeData.shankMap == shank);
XData = bsxfun(@plus, probeData.siteLoc(shankMask, 1)', vrX(:));
YData = bsxfun(@plus, probeData.siteLoc(shankMask, 2)', vrY(:));
nSites = sum(shankMask);
% plot sites
hFigProbe.subplotApply('hShanks', iShank, @patch, XData, YData, 'w', 'EdgeColor', 'k');
% label sites
if ~isempty(probeData.siteMap(shankMask))
siteLabels = arrayfun(@(i) sprintf('%d/%d', i, probeData.siteMap(i)), find(shankMask), 'UniformOutput', 0);
else
siteLabels = arrayfun(@(i) sprintf('%d', i), 1:nSites, 'UniformOutput', 0);
end
hFigProbe.subplotApply('hShanks', iShank, @text, probeData.siteLoc(shankMask, 1), ...
probeData.siteLoc(shankMask, 2), ...
siteLabels, 'VerticalAlignment', 'middle', 'HorizontalAlignment', 'center');
spTitle = 'Site # / Chan #';
if nShanks > 1
spTitle = sprintf('Shank %d: %s', shank, spTitle);
end
hFigProbe.subplotApply('hShanks', iShank, @axis, [min(XData(:)), max(XData(:)), min(YData(:)), max(YData(:))]);
hFigProbe.subplotApply('hShanks', iShank, @title, spTitle);
hFigProbe.subplotApply('hShanks', iShank, @xlabel, 'X Position (\mum)');
hFigProbe.subplotApply('hShanks', iShank, @ylabel, 'Y Position (\mum)');
hFigProbe.subplotApply('hShanks', iShank, @axis, 'equal');
end
hFigProbe.setMouseable();
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
activity.m
|
.m
|
JRCLUST-main/@JRC/activity.m
| 2,936 |
utf_8
|
dda8df45b7d146a543ac4bdab5127de3
|
function activity(obj)
%ACTIVITY Plot activity
if isempty(obj.res)
obj.loadFiles();
end
plotActivity(obj.res, obj.hCfg);
end
%% LOCAL FUNCTIONS
function plotActivity(spikeData, hCfg)
%DOPLOTACTIVITY Plot activity as a function of depth and time
tBin = 10; % activity every 10 sec
% plot activity as a function of time
recDur = double(max(spikeData.spikeTimes)) / hCfg.sampleRate; % in sec
nBins = ceil(recDur / tBin);
% 90th percentile of amplitudes per time bin per site
amp90 = zeros(nBins, hCfg.nSites);
binLims = [1, tBin * hCfg.sampleRate];
for iSite = 1:hCfg.nSites
iSpikes = find(spikeData.spikeSites == iSite);
iAmps = spikeData.spikeAmps(iSpikes);
if isempty(iAmps)
continue;
end
iTimes = spikeData.spikeTimes(iSpikes);
for iBin = 1:nBins
bounds = binLims + (iBin-1) * binLims(2);
inBounds = iTimes >= bounds(1) & iTimes <= bounds(2);
if ~any(inBounds)
continue;
end
binAmps = iAmps(inBounds);
amp90(iBin, iSite) = quantile(abs(binAmps), .9);
end
end % for
amp90 = amp90';
leftEdge = hCfg.siteLoc(:, 1) == 0; % the leftmost column on the probe
YLocs = hCfg.siteLoc(:, 2);
hFigActivity = jrclust.views.Figure('FigActivity', [0 0 .5 1], hCfg.sessionName, 1, 1);
hFigActivity.addSubplot('hActivity', 1, 2);
hFigActivity.subplotApply('hActivity', 1, @imagesc, amp90(leftEdge, :), 'XData', (1:nBins) * tBin, 'YData', YLocs(leftEdge));
hFigActivity.subplotApply('hActivity', 1, @axis, 'xy');
hFigActivity.subplotApply('hActivity', 1, @xlabel, 'Time');
hFigActivity.subplotApply('hActivity', 1, @ylabel, 'Sites');
hFigActivity.subplotApply('hActivity', 1, @title, 'Left edge sites');
hFigActivity.subplotApply('hActivity', 2, @imagesc, amp90(~leftEdge, :), 'XData', (1:nBins) * tBin, 'YData', YLocs(leftEdge));
hFigActivity.subplotApply('hActivity', 2, @axis, 'xy');
hFigActivity.subplotApply('hActivity', 2, @xlabel, 'Time');
hFigActivity.subplotApply('hActivity', 2, @ylabel, 'Sites');
hFigActivity.subplotApply('hActivity', 2, @title, 'Right edge sites');
[~, meanSite] = max(mean(amp90, 2));
meanSiteNeighbors = intersect(1:max(meanSite)+2, meanSite + (-2:2));
amp90Center = amp90(meanSiteNeighbors, :);
centroid = bsxfun(@rdivide, sum(bsxfun(@times, amp90Center.^2, YLocs(meanSiteNeighbors))), sum(amp90Center.^2));
if numel(centroid) == 1
LineStyle = 'r*';
else
LineStyle = 'r-';
end
hFigActivity.subplotApply('hActivity', 1, @hold, 'on');
hFigActivity.subplotApply('hActivity', 1, @plot, (1:nBins) * tBin, centroid, LineStyle);
hFigActivity.subplotApply('hActivity', 2, @hold, 'on');
hFigActivity.subplotApply('hActivity', 2, @plot, (1:nBins) * tBin, centroid, LineStyle);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
loadFiles.m
|
.m
|
JRCLUST-main/@JRC/loadFiles.m
| 11,074 |
utf_8
|
e190d1c719a51a835b9c51e6812788c8
|
function loadFiles(obj)
%LOADFILES Load results struct
if obj.isError
error(obj.errMsg);
end
if ~exist(obj.hCfg.resFile, 'file')
error('%s does not exist', obj.hCfg.resFile);
return;
end
try
obj.hCfg.updateLog('loadRes', sprintf('Loading %s', obj.hCfg.resFile), 1, 0);
res_ = load(obj.hCfg.resFile);
obj.hCfg.updateLog('loadRes', sprintf('Finished loading %s', obj.hCfg.resFile), 0, 1);
catch ME
warning('Failed to load %s: %s', ME.message);
return;
end
if isfield(res_, 'spikeTimes')
% load spikesRaw
if isfield(res_, 'rawShape') && ~isempty(res_.rawShape)
obj.hCfg.updateLog('loadRaw', sprintf('Loading %s', obj.hCfg.rawFile), 1, 0);
spikesRaw = readBin(obj.hCfg.rawFile, res_.rawShape, '*int16');
obj.hCfg.updateLog('loadRaw', sprintf('Finished loading %s', obj.hCfg.rawFile), 0, 1);
else
spikesRaw = [];
end
% load spikesFilt
if isfield(res_, 'filtShape') && ~isempty(res_.filtShape)
obj.hCfg.updateLog('loadFilt', sprintf('Loading %s', obj.hCfg.filtFile), 1, 0);
spikesFilt = readBin(obj.hCfg.filtFile, res_.filtShape, '*int16');
obj.hCfg.updateLog('loadFilt', sprintf('Finished loading %s', obj.hCfg.filtFile), 0, 1);
else
spikesFilt = [];
end
% load spikeFeatures
if isfield(res_, 'featuresShape') && ~isempty(res_.featuresShape)
obj.hCfg.updateLog('loadFeatures', sprintf('Loading %s', obj.hCfg.featuresFile), 1, 0);
spikeFeatures = readBin(obj.hCfg.featuresFile, res_.featuresShape, '*single');
obj.hCfg.updateLog('loadFeatures', sprintf('Finished loading %s', obj.hCfg.featuresFile), 0, 1);
else
spikeFeatures = [];
end
% set spikesRaw/spikesFilt/spikeFeatures (warn if empty!)
if isempty(spikesRaw)
warning('spikesRaw is empty');
end
res_.spikesRaw = spikesRaw;
if isempty(spikesFilt)
warning('spikesFilt is empty');
end
res_.spikesFilt = spikesFilt;
if isempty(spikeFeatures)
warning('spikeFeatures is empty');
end
res_.spikeFeatures = spikeFeatures;
if isfield(res_, 'history') && iscell(res_.history) % old-style history
res_.history = convertHistory(res_.history, res_.initialClustering, obj.hCfg);
end
% restore values to hClust
if isfield(res_, 'hClust')
if isa(res_.hClust, 'jrclust.models.clustering.DensityPeakClustering')
res_.hClust = convertToNew(res_, obj.hCfg);
end
hClustFields = fieldnames(res_.hClust);
for i = 1:numel(hClustFields)
fn = hClustFields{i};
if isempty(res_.hClust.(fn)) && isfield(res_, fn)
res_.hClust.(fn) = res_.(fn);
elseif ismember(fn, {'clusterCenters', 'clusterCentroids'}) && isfield(res_, fn)
res_.hClust.sRes.(fn) = res_.(fn);
end
end
% restore initialClustering
res_.hClust.initialClustering = res_.spikeClusters;
% supply hClust with our own hCfg
res_.hClust.hCfg = obj.hCfg;
elseif isfield(res_, 'spikeTemplates') % create a new TemplateClustering
hClust = jrclust.sort.TemplateClustering(obj.hCfg);
fieldNames = fieldnames(res_);
md = ?jrclust.sort.TemplateClustering;
pl = md.PropertyList;
for i = 1:numel(fieldNames)
fn = fieldNames{i};
propMetadata = pl(strcmp(fn, {pl.Name}));
if isprop(hClust, fn) && ~((propMetadata.Dependent && isempty(propMetadata.SetMethod)))
hClust.(fn) = res_.(fn);
end
end
res_.hClust = hClust;
elseif isfield(res_, 'spikeClusters')
hClust = jrclust.sort.DensityPeakClustering(obj.hCfg);
fieldNames = fieldnames(res_);
md = ?jrclust.sort.DensityPeakClustering;
pl = md.PropertyList;
for i = 1:numel(fieldNames)
fn = fieldNames{i};
propMetadata = pl(strcmp(fn, {pl.Name}));
if isprop(hClust, fn) && ~((propMetadata.Dependent && isempty(propMetadata.SetMethod)))
hClust.(fn) = res_.(fn);
end
end
res_.hClust = hClust;
end
if isfield(res_, 'hClust')
if ~isempty(res_.hClust.inconsistentFields()) && obj.hCfg.getOr('autoRecover', 0)
flag = res_.hClust.recover(1); % recover inconsistent data if needed
successAppend = 'You should look through your data and ensure everything is correct, then save it.';
failureAppend = 'You will probably experience problems curating your data.';
msg = '';
switch flag
case 2
msg = sprintf('Non-contiguous spike table found and corrected. %s', successAppend);
case 1
msg = sprintf('Inconsistent fields found and corrected. %s', successAppend);
case 0
msg = sprintf('Clustering data in an inconsistent state and automatic recovery failed. Please post an issue on the GitHub issue tracker. %s', failureAppend);
case -1
msg = sprintf('Automatic recovery canceled by the user but the clustering data is still in an inconsistent state. %s', failureAppend);
end
if ~isempty(msg)
jrclust.utils.qMsgBox(msg, 1, 1);
end
end
res_.hClust.syncHistFile();
end
if isfield(res_, 'hRecs') % don't try to load recordings
res_ = rmfield(res_, 'hRecs');
end
else
warning('spikeTimes not found in %s', obj.hCfg.resFile);
res_ = struct();
end
obj.res = res_;
end
%% LOCAL FUNCTIONS
function binData = readBin(filename, binShape, dataType)
%LOADBIN Load traces/features from binary file
if exist(filename, 'file')
fid = fopen(filename, 'r');
binData = fread(fid, Inf, dataType);
fclose(fid);
binData = reshape(binData, binShape);
else
binData = [];
end
end
function hClust = convertToNew(res, hCfg)
%CONVERTHISTORY Convert old-style hClust to new-style
hClustOld = res.hClust;
dRes = hClustOld.dRes;
dRes.spikesRaw = res.spikesRaw;
dRes.spikesFilt = res.spikesFilt;
dRes.spikeFeatures = res.spikeFeatures;
sRes = hClustOld.sRes;
if isfield(sRes, 'simScore')
sRes.waveformSim = sRes.simScore;
sRes = rmfield(sRes, 'simScore');
end
hClust = jrclust.sort.DensityPeakClustering(hCfg, sRes, dRes);
end
function history = convertHistory(oldHistory, spikeClusters, hCfg)
%CONVERTHISTORY Convert old-style (cell) history to the history file
history = containers.Map('KeyType', 'int32', 'ValueType', 'char');
history(1) = 'initial commit';
fidHist = fopen(hCfg.histFile, 'w');
fwrite(fidHist, int32(1), 'int32');
fwrite(fidHist, int32(spikeClusters), 'int32');
for j = 2:size(oldHistory, 1)
op = oldHistory(j, :);
switch op{2}
case 'delete'
deleted = op{3};
nClustersOld = max(spikeClusters);
spikeClusters(ismember(spikeClusters, deleted)) = 0;
if ~isempty(obj.clusterCenters)
obj.clusterCenters(deleted) = [];
end
% shift clusters larger than deleted down by 1
if numel(deleted) == 1
gtMask = (spikeClusters > deleted);
spikeClusters(gtMask) = spikeClusters(gtMask) - 1;
else
keepMe = setdiff(1:nClustersOld, deleted);
nClustersNew = numel(keepMe);
good = (spikeClusters > 0);
mapFrom = zeros(1, nClustersOld);
mapFrom(keepMe) = 1:nClustersNew;
spikeClusters(good) = mapFrom(spikeClusters(good));
end
case 'merge'
iCluster = op{3};
jCluster = op{4};
spikeClusters(spikeClusters == jCluster) = iCluster;
% shift clusters larger than jCluster down by 1
gtMask = (spikeClusters > jCluster);
spikeClusters(gtMask) = spikeClusters(gtMask) - 1;
case 'split'
iCluster = op{3};
retained = op{4};
% shift clusters larger than iCluster up by 1 (make
% room for splitted off cluster)
gtMask = (spikeClusters > iCluster);
spikeClusters(gtMask) = spikeClusters(gtMask) + 1;
% take splitted off spikes and make a new cluster
% of them
iMask = (spikeClusters == iCluster);
iSpikes = find(iMask);
jSpikes = iSpikes(~ismember(iSpikes, retained)); % spikes to split off
spikeClusters(jSpikes) = iCluster + 1;
case 'partition'
iCluster = op{3};
assignPart = op{4};
initialSpikes = find(spikeClusters == iCluster);
for kSplit = 1:numel(assignPart)-1
if kSplit > 1
iSpikes = find(spikeClusters == iCluster);
else
iSpikes = initialSpikes;
end
splitOff = initialSpikes(assignPart{kSplit});
retain = iSpikes(~ismember(iSpikes, splitOff));
iSite = mode(obj.spikeSites(retain));
jSite = mode(obj.spikeSites(splitOff));
% swap retain and split-off spikes; always make splitOff the next
% cluster
if iSite > jSite
splitOff = retain;
end
% make room for new cluster
mask = (spikeClusters > iCluster + kSplit - 1);
spikeClusters(mask) = spikeClusters(mask) + 1;
spikeClusters(splitOff) = iCluster + kSplit;
end
otherwise
diffs = oldHistory{j, 3};
if ~isempty(diffs)
iDiffs = diffs(1, :);
sDiffs = diffs(2, :);
spikeClusters(iDiffs) = sDiffs;
end
end
fwrite(fidHist, int32(j), 'int32');
fwrite(fidHist, spikeClusters, 'int32');
history(j) = op{2};
end
fclose(fidHist);
end
|
github
|
JaneliaSciComp/JRCLUST-main
|
bootstrap.m
|
.m
|
JRCLUST-main/@JRC/bootstrap.m
| 12,650 |
utf_8
|
a2ce076e62d45618c1b4ccb323bc5548
|
function bootstrap(obj, varargin)
%BOOTSTRAP Bootstrap a JRCLUST session
% metafile: optional string; path (or glob) to meta file(s)
if nargin > 1
metafile_ = jrclust.utils.absPath(varargin{1});
if isempty(metafile_) % TODO: warn?
metafile = '';
workingdir = pwd();
elseif ischar(metafile_)
workingdir = fileparts(metafile_);
metafile = {metafile_};
else % cell
metafile = metafile_;
workingdir = fileparts(metafile_{1});
end
if ~isempty(metafile)
[~, ~, exts] = cellfun(@(f) fileparts(f), metafile, 'UniformOutput', 0);
uniqueExts = unique(exts);
if numel(uniqueExts) > 1
error('Specify only a single file type');
end
ext = uniqueExts{:};
switch lower(ext)
case '.rhd'
obj.bootstrapIntan(metafile);
return;
case '.meta'
binfile = cellfun(@(f) jrclust.utils.subsExt(f, '.bin'), metafile, 'UniformOutput', 0);
end
end
% set whether to ask user input
if any(cellfun(@(x) strcmp(x,'-noconfirm'), varargin))
ask=false;
else
ask=true;
end
% check whether user requires advanced parameters
if any(cellfun(@(x) strcmp(x,'-advanced'), varargin))
advanced=true;
else
advanced=false;
end
else
metafile = '';
workingdir = pwd();
% since narg <= 1, '-noconfirm' not set
ask=true;
end
% first check for a .meta file
if isempty(metafile)
[metafile, binfile, workingdir] = getMetafile(workingdir);
end
% check for missing binary files
if any(cellfun(@(f) isempty(jrclust.utils.absPath(f)), binfile))
binfile = jrclust.utils.selectFile({'*.bin;*.dat', 'SpikeGLX recordings (*.bin, *.dat)'; ...
'*.*', 'All Files (*.*)'}, 'Select one or more raw recordings', workingdir, 1);
if cellfun(@isempty, binfile)
return;
end
end
if ~isempty(metafile) % load metafile
cfgData = metaToConfig(metafile, binfile, workingdir);
else % ask for a probe file instead
cfgData = struct('outputDir', workingdir);
cfgData.rawRecordings = binfile;
cfgData.probe_file = getProbeFile(cfgData.outputDir,ask);
if isempty(cfgData.probe_file) % closed dialog, cancel bootstrap
return;
end
end
% construct the Config object from specified data
hCfg_ = jrclust.Config(cfgData);
while 1
% confirm with the user
[~, sessionName, ~] = fileparts(hCfg_.rawRecordings{1});
configFile = fullfile(hCfg_.outputDir, [sessionName, '.prm']);
dlgFieldNames = {'Config filename', ...
'Raw recording file(s)', ...
'Sampling rate (Hz)', ...
'Number of channels in file', ...
sprintf('%sV/bit', char(956)), ...
'Header offset (bytes)', ...
'Data Type (int16, uint16, single, double)'};
dlgFieldVals = {configFile, ...
strjoin(hCfg_.rawRecordings, ','), ...
num2str(hCfg_.sampleRate, 15), ...
num2str(hCfg_.nChans), ...
num2str(hCfg_.bitScaling), ...
num2str(hCfg_.headerOffset), ...
hCfg_.dataType};
if ask
dlgAns = inputdlg(dlgFieldNames, 'Does this look correct?', 1, dlgFieldVals, struct('Resize', 'on', 'Interpreter', 'tex'));
else
dlgAns= dlgFieldVals';
end
if isempty(dlgAns)
return;
end
try
if ~exist(dlgAns{1}, 'file')
fclose(fopen(dlgAns{1}, 'w'));
end
hCfg_.setConfigFile(dlgAns{1}, 0);
hCfg_.outputDir = fileparts(dlgAns{1}); % set outputdir to wherever configFile lives
catch ME
errordlg(ME.message);
continue;
end
try
hCfg_.rawRecordings = cellfun(@strip, strsplit(dlgAns{2}, ','), 'UniformOutput', 0);
catch ME
errordlg(ME.message);
continue;
end
try
hCfg_.sampleRate = str2double(dlgAns{3});
catch ME
errordlg(ME.message);
continue;
end
try
hCfg_.nChans = str2double(dlgAns{4});
catch ME
errordlg(ME.message);
continue;
end
try
hCfg_.bitScaling = str2double(dlgAns{5});
catch ME
errordlg(ME.message);
continue;
end
try
hCfg_.headerOffset = str2double(dlgAns{6});
catch ME
errordlg(ME.message);
continue;
end
try
hCfg_.dataType = dlgAns{7};
catch ME
errordlg(ME.message);
continue;
end
break;
end
if ask
dlgAns = questdlg('Would you like to export advanced parameters?', 'Bootstrap', 'No');
elseif advanced
dlgAns = 'Yes';
else
dlgAns = 'No';
end
switch dlgAns
case 'Yes'
hCfg_.save('', 1);
case 'No'
hCfg_.save('', 0);
otherwise
return;
end
obj.hCfg = hCfg_;
obj.hCfg.edit();
end
%% LOCAL FUNCTIONS
function [metafile, binfile, workingdir] = getMetafile(workingdir)
dlgAns = questdlg('Do you have a .meta file?', 'Bootstrap', 'No');
switch dlgAns
case 'Yes' % select .meta file
[metafile, workingdir] = jrclust.utils.selectFile({'*.meta', 'SpikeGLX meta files (*.meta)'; '*.*', 'All Files (*.*)'}, 'Select one or more .meta files', workingdir, 1);
if all(cellfun(@isempty, metafile))
return;
end
binfile = cellfun(@(f) jrclust.utils.subsExt(f, '.bin'), metafile, 'UniformOutput', 0);
case 'No' % select recording file
metafile = '';
[binfile, workingdir] = jrclust.utils.selectFile({'*.bin;*.dat', 'SpikeGLX recordings (*.bin, *.dat)'; ...
'*.rhd', 'Intan recordings (*.rhd)'; ...
'*.*', 'All Files (*.*)'}, 'Select one or more raw recordings', workingdir, 1);
if all(cellfun(@isempty, binfile))
return;
end
[~, ~, exts] = cellfun(@(f) fileparts(f), binfile, 'UniformOutput', 0);
uniqueExts = unique(exts);
if numel(uniqueExts) > 1
error('Specify only a single file type');
end
ext = uniqueExts{:};
if strcmpi(ext, '.rhd')
obj.bootstrapIntan(binfile);
return;
end
case {'Cancel', ''}
return;
end
end
function cfgData = metaToConfig(metafile, binfile, workingdir)
cfgData = struct('outputDir', workingdir);
cfgData.rawRecordings = binfile;
SMeta = jrclust.utils.loadMetadata(metafile{1});
cfgData.sampleRate = SMeta.sampleRate;
cfgData.nChans = SMeta.nChans;
cfgData.bitScaling = SMeta.bitScaling;
cfgData.headerOffset = 0; % standard for SpikeGLX
cfgData.dataType = 'int16'; % standard for SpikeGLX
probeFile = getProbeFile(cfgData.outputDir, 0);
if isempty(probeFile) && SMeta.isImec % think we've got a Neuropixels probe
if ~isempty(SMeta.probeOpt) % 3A with option
probeFile = sprintf('imec3_opt%d.prb', SMeta.probeOpt);
else % 3A or 3B; ask
dlgAns = questdlg('It looks like you have a Neuropixels probe. Is this correct?', 'Bootstrap', ...
'Yes', 'No', 'No'); % don't permit 'Cancel'
if isempty(dlgAns) % closed dialog; cancel
cfgData = [];
return;
end
if strcmp(dlgAns, 'Yes')
dlgAns = listdlg('PromptString', 'Specify your configuration', ...
'SelectionMode', 'single', ...
'ListString', {'Phase 3A', ...
'Phase 3B (Staggered)', ...
'Phase 3B (Aligned)', ...
'Custom configuration', ...
'Set manually'});
switch dlgAns
case 1
probeFile = 'imec3a.prb';
case 2
probeFile = 'imec3b_staggered.prb';
case 3
probeFile = 'imec3b_aligned.prb';
case 4
probeFile = getProbeFile(cfgData.outputDir);
case 5
% Fill in a little probe file with 4 sites
% User can paste their coordinates in, e.g.
% generated by SGLXMetaToCoords
probeFile = 'NP_starter.prb';
end
end
end
elseif isempty(probeFile)
probeFile = getProbeFile(cfgData.outputDir);
end
cfgData.probe_file = probeFile;
% check whether there's a trial file in the directory as well
[cfgData.trialFile,cfgData.psthTimeLimits] = getTrialFile(cfgData.outputDir);
if ~isempty(cfgData.trialFile)
% check whether the .meta specifies PSTH display parameters
if isfield(SMeta,'psthTimeLimits'); cfgData.psthTimeLimits=str2num(SMeta.psthTimeLimits); end
if isfield(SMeta,'psthTimeBin'); cfgData.psthTimeBin=SMeta.psthTimeBin; end
if isfield(SMeta,'psthXTick'); cfgData.psthXTick=SMeta.psthXTick; end
end
end
function probeFile = probeFileInDir(workingdir)
probeFile = '';
d = dir(fullfile(workingdir, '*.prb'));
if isempty(d)
return;
end
probeFile = fullfile(workingdir, d(1).name);
end
function probeFile = getProbeFile(workingdir, ask)
if nargin < 2
ask = 1;
end
probeFile = probeFileInDir(workingdir);
if ~isempty(probeFile) && ask % found a probe file in working directory; confirm
dlgAns = questdlg(sprintf('Found probe file ''%s''. Use it?', probeFile));
if strcmp(dlgAns, 'Yes')
return;
else
probeFile = '';
end
end
if ask
dlgAns = questdlg('Would you like to specify a probe file?', 'Bootstrap', 'No');
if strcmp(dlgAns, 'Yes')
probedir = workingdir;
if isempty(dir(fullfile(workingdir, '*.prb')))
probedir = fullfile(jrclust.utils.basedir(), 'probes');
end
[probefile, probedir] = jrclust.utils.selectFile({'*.prb', 'Probe files (*.prb)'; '*.*', 'All Files (*.*)'}, ...
'Select a probe file', probedir, 0);
probeFile = fullfile(probedir, probefile);
end
end
end
function [trialFile,psthTimeLimits] = getTrialFile(workingdir, ask)
if nargin < 2
ask = 0;
end
trialFile = trialFileInDir(workingdir);
if ~isempty(trialFile) && ask % found a trial file in working directory; confirm
dlgAns = questdlg(sprintf('Found trial file ''%s''. Use it?', trialFile));
if strcmp(dlgAns, 'Yes')
return;
else
trialFile = '';
end
end
psthTimeLimits = [-0.1 0.1]; % default time range (in s) over which to display PSTH
end
function trialFile = trialFileInDir(workingdir)
trialFile = '';
d = dir(fullfile(workingdir, '*trial.*'));
if isempty(d)
return;
end
trialFile = fullfile(workingdir, d(1).name);
end
% function hCfg = bootstrapGUI() % WIP
% %BOOTSTRAPGUI Show all (common) parameters
% % load old2new param set and convert to new2old
% [old2new, new2old] = jrclust.utils.getOldParamMapping();
%
% % build the bootstrap GUI
% hBootstrap = uicontainer();
% hRecData = uipanel('Parent', hBootstrap, 'Title', 'Recording file', 'Position', [0, 0.75, 0.25, 0.25]);
% hProbe = uipanel('Parent', hBootstrap, 'Title', 'Probe parameters', 'Position', [0.25, 0.75, 0.25, 0.25]);
% end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
BEHR_initial_setup.m
|
.m
|
BEHR-core-utils-master/BEHR_initial_setup.m
| 19,737 |
utf_8
|
372cbecdc1343d93cff8c38d21457b20
|
function [ ] = BEHR_initial_setup( )
%BEHR_INITIAL_SETUP Perform the actions necessary to set up BEHR to run
% There are several steps to prepare the BEHR algorithm to run:
% 1) Clone the necessary repositories from GitHub
% 2) Identify the paths where OMI, MODIS, GLOBE, and WRF-Chem data
% reside.
% 3) Add the necessary code paths to the Matlab search path
% 4) Build the "omi" Python package included in the BEHR-PSM-Gridding
% repository.
% If you're reading this, then you should have already done #1. This
% function will automatically perform steps 2-4. You may be prompted for
% each step, so you must run this function interactively (i.e. it cannot
% be run as part of a batch job on a cluster).
%
% NOTE TO DEVELOPERS: This function should only rely on built-in Matlab
% functions and not any functions included as part of the BEHR code or
% related repositories, since it is intended to be run before any of the
% BEHR code has been added to the Matlab path.
[behr_utils_repo_path, myname] = fileparts(mfilename('fullpath'));
paths_filename = 'behr_paths.m';
template_filename = 'behr_paths_template.m';
constants_path = fullfile(behr_utils_repo_path,'Utils','Constants');
paths_file = fullfile(constants_path,paths_filename);
template_file = fullfile(constants_path,template_filename);
make_paths_file();
add_code_paths();
build_omi_python();
function make_paths_file
% Check that behr_paths.m does not already exist anywhere. If there's one
% in the right place, then ask if we want to overwrite it. If there's one
% somewhere else, the user will need to move or delete it so that we don't
% get two behr_paths.m files.
if exist(paths_file,'file')
user_ans = input(sprintf('A %s file already exists in BEHR/Utils/Constants. Skip the paths setup and use existing?: ', paths_filename), 's');
if strcmpi(user_ans,'Yes') || strcmpi(user_ans, 'y')
% Previously I had this function delete behr_path.m.
% However, since behr_paths is called later, that led to
% issue where Matlab wouldn't recompile the class or
% something, and try to use the old class. Having the user
% manually delete it avoids this problem.
return;
else
error('behr_setup:file_exists', 'You must manually delete the existing behr_paths.m file at %s before this function will recreate that file', constants_path);
end
elseif ~isempty(which(paths_filename))
error('behr_setup:file_exists','%1$s exists on your Matlab search path, but at %2$s, not at %3$s. Please delete or move that version to %3$s.',paths_filename, which(paths_filename), constants_path);
end
% This defines all the paths that should exist in that file. The
% field name is the name the property will be given, the 'comment'
% subfield is the explanatory comment, and the 'default' subfield
% is what the default will be. If either field is omitted, that is
% fine. A generic comment will be inserted and a blank path will be
% inserted. Including the subfield "no_quote" at all will cause it
% not to automatically quote the default path, which is useful if
% you need to allow for multiple paths in a cell array. Including
% the the field "isfile" (whatever value is set to it) will cause
% behr_paths.ValidatePaths() to check if a file exists at that
% path, rather than a directory. Including the field "is_code_dir"
% will make behr_paths aware that the directory given contains
% code, and should be added to the Matlab path on request. If its
% value is the string 'norecurse', only that directory (and not its
% subfolders) will be added to the path. Likewise, if "is_pypath"
% is a field, it will be aware that this path contains Python code
% and should be added to the Python path by SetPythonPath().
sat_file_server = '128.32.208.13';
wrf_file_server = 'cohenwrfnas.dyn.berkeley.edu';
if ismac
sat_folder = fullfile('/Volumes','share-sat');
wrf1_folder = fullfile('/Volumes', 'share-wrf1','BEHR-WRF');
wrf2_folder = fullfile('/Volumes', 'share-wrf2','BEHR-WRF');
elseif isunix
sat_folder = fullfile('/mnt','share-sat');
wrf1_folder = fullfile('/mnt', 'share-wrf1','BEHR-WRF');
wrf2_folder = fullfile('/mnt', 'share-wrf2','BEHR-WRF');
elseif ispc
drive_letter_request = 'Enter the drive letter (just the letter, not the ":\" that "%s" is mounted as';
sat_folder = strcat(input(sprintf(drive_letter_request, 'share-sat'), 's'), ':');
wrf1_folder = strcat(input(sprintf(drive_letter_request, 'share-wrf1','BEHR-WRF'), 's'), ':');
wrf2_folder = strcat(input(sprintf(drive_letter_request, 'share-wrf2','BEHR-WRF'), 's'), ':');
end
% Local repos/folders
paths.behr_core.comment = 'The directory of the BEHR-core repository. May be cloned from https://github.com/CohenBerkeleyLab/BEHR-core';
paths.behr_core.default = fullfile(behr_utils_repo_path, '..', 'BEHR-core');
paths.behr_core.is_code_dir = true;
paths.behr_utils.comment = 'The directory of the BEHR-core-utils repository. May be cloned from https://github.com/CohenBerkeleyLab/BEHR-core-utils';
paths.behr_utils.default = behr_utils_repo_path;
paths.behr_utils.is_code_dir = true;
paths.utils.comment = 'The directory of the general Matlab-Gen-Utils repository (not the BEHR-core-utils repo). May be cloned from https://github.com/CohenBerkeleyLab/Matlab-Gen-Utils';
paths.utils.default = fullfile(behr_utils_repo_path, '..', 'Matlab-Gen-Utils');
paths.utils.is_code_dir = true;
paths.amf_tools_dir.comment = 'The AMF_tools directory in the BEHR-core-utils repository on your computer. It should contain the files damf.txt and nmcTmpYr.txt';
paths.amf_tools_dir.default = fullfile(behr_utils_repo_path, 'AMF_tools');
% do not need to explicitly add AMF_tools to path, since it is in
% the behr_utils repo
paths.psm_dir.comment = 'The PSM Gridding repository. It should contain the files PSM_Main.py and psm_wrapper.m. May be cloned from https://github.com/CohenBerkeleyLab/BEHR-PSM-Gridding';
paths.psm_dir.default = fullfile(behr_utils_repo_path, '..', 'BEHR-PSM-Gridding');
paths.psm_dir.is_code_dir = 'norecurse';
paths.psm_dir.is_pypath = true;
paths.python_interface.comment = 'The MatlabPythonInterface repository. May be cloned from https://github.com/CohenBerkeleyLab/MatlabPythonInterface';
paths.python_interface.default = fullfile(behr_utils_repo_path, '..', 'MatlabPythonInterface');
paths.python_interface.is_code_dir = true;
paths.wrf_utils.comment = 'The WRF_Utils repository which should contain the function convert_wrf_temperature.m May be cloned from https://github.com/CohenBerkeleyLab/WRF_Utils';
paths.wrf_utils.default = fullfile(behr_utils_repo_path, '..', 'WRF_Utils');
paths.wrf_utils.is_code_dir = true;
% Matlab file folders
paths.sp_mat_dir.comment = sprintf('The default path where OMI_SP_*_yyyymmdd.mat files will be saved and read from. It should have subdirectories for each region to be produced (e.g. "us" - must be lower case). For UC Berkeley users, is it on the file server at %s which should be mounted on your computer.',sat_file_server);
paths.sp_mat_dir.default = fullfile(sat_folder, 'SAT', 'BEHR', 'SP_Files');
paths.behr_mat_dir.comment = sprintf('The default root path where OMI_BEHR_*_yyyymmdd.mat files will be saved and read from. It should have subdirectories for each region to be produced and within each region directories "daily" and "monthly". For UC Berkeley users, is it on the file server at %s which should be mounted on your computer.',sat_file_server);
paths.behr_mat_dir.default = fullfile(sat_folder, 'SAT', 'BEHR', 'BEHR_Files');
% OMI and ancillary data folders
paths.omno2_dir.comment = sprintf('This should contain folders organized by year and month with OMI-Aura_L2-OMNO2 files in them. For UC Berkeley users, is it on the file server at %s which should be mounted on your computer.',sat_file_server);
paths.omno2_dir.default = fullfile(sat_folder, 'SAT', 'OMI', 'OMNO2', 'version_3_3_0');
paths.ompixcor_dir.comment = sprintf('This should contain folders organized by year and month with OMI-Aura_L2-OMNPIXCOR files in them. For UC Berkeley users, is it on the file server at %s which should be mounted on your computer.',sat_file_server);
paths.ompixcor_dir.default = fullfile(sat_folder, 'SAT', 'OMI', 'OMPIXCOR', 'version_003');
paths.myd06_dir.comment = sprintf('This should contain folders for each year with MYD06_L2 files in them. For UC Berkeley users, is it on the file server at %s which should be mounted on your computer.',sat_file_server);
paths.myd06_dir.default = fullfile(sat_folder, 'SAT', 'MODIS', 'MYD06_L2');
paths.mcd43d_dir.comment = sprintf('This should contain folders for each year with MCD43D* files in them. For UC Berkeley users, is it on the file server at %s which should be mounted on your computer.',sat_file_server);
paths.mcd43d_dir.default = fullfile(sat_folder, 'SAT', 'MODIS', 'MCD43D');
paths.modis_land_mask.comment = sprintf('This is the "Land_Water_Mask_7Classes_UMD file, available from ftp://rsftp.eeos.umb.edu/data02/Gapfilled/ (as of 21 Sept 2017). For UC Berkeley users, is it on the file server at %s which should be mounted on your computer.',sat_file_server);
paths.modis_land_mask.default = fullfile(sat_folder, 'SAT', 'MODIS', 'Land_Water_Mask_7Classes_UMD.hdf');
paths.modis_land_mask.isfile = true;
paths.globe_dir.comment = sprintf('This is the folder with the GLOBE database, available from https://www.ngdc.noaa.gov/mgg/topo/gltiles.html (as of 21 Sept 2017). It should contain files a10g through p10g and their .hdr files. For UC Berkeley users, is it on the file server at %s which should be mounted on your computer.',sat_file_server);
paths.globe_dir.default = fullfile(sat_folder, 'SAT', 'BEHR','GLOBE_Database');
paths.website_staging_dir.comment = sprintf('The directory where data should be staged before being put on the folders visible to the website. Also on the file server at %s which should be mounted on your computer.', sat_file_server);
paths.website_staging_dir.default = fullfile(sat_folder,'SAT','BEHR','WEBSITE','staging');
% WRF data is spread across multiple volumes locally. It's just too
% big.
paths.wrf_monthly_profiles.comment = sprintf('The path that contains the WRF_BEHR*.nc monthly profile files. This should be on the file server at %s.', wrf_file_server);
paths.wrf_monthly_profiles.default = fullfile(wrf1_folder,'MonthlyProfiles');
paths.wrf_profiles.comment = sprintf('Add all paths that contain WRF profiles. These should be folders that are organized by year and month, with wrfout_d01 files in them. These will be found on the file server at %s, all volumes must be mounted on your computer.', wrf_file_server);
paths.wrf_profiles.default = sprintf('{''%s'', ''%s''}', fullfile(wrf1_folder, 'Outputs'), fullfile(wrf2_folder, 'Outputs'));
paths.wrf_profiles.no_quote = true;
%%%%%%%%%%%%%%%%%%
% Write the file %
%%%%%%%%%%%%%%%%%%
fid_template = fopen(template_file, 'r');
fid_new = fopen(paths_file, 'w');
tline = fgetl(fid_template);
[~,paths_classname] = fileparts(paths_filename);
[~,template_classname] = fileparts(template_filename);
while ischar(tline)
tline = strrep(tline, template_classname, paths_classname);
if strcmp(strtrim(tline), '%#PATHS')
write_paths(paths, fid_new);
elseif strcmp(strtrim(tline), '%#ISFILE')
write_is_file_struct(paths, fid_new);
elseif strcmp(strtrim(tline), '%#ISCODEDIR')
write_iscodedir_structs(paths, fid_new);
else
fprintf(fid_new, '%s\n', tline);
end
tline = fgetl(fid_template);
end
fclose(fid_template);
fclose(fid_new);
fprintf('\n!!! Defaults %s file created at %s. Review it and edit the paths as needed. !!!\n\n', paths_filename, paths_file);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Add BEHR paths to Matlab search path %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function add_code_paths
fprintf('\n');
fprintf('Trying to add BEHR code paths to Matlab path...\n');
addpath(fullfile(behr_utils_repo_path, 'Utils', 'Constants'));
try
behr_paths.AddCodePaths();
input('Press ENTER to continue','s');
catch err
if strcmpi(err.identifier, 'path_setup:bad_paths')
fprintf('%s\n', err.message);
fprintf('Correct the bad paths in %s and then run behr_paths.AddCodePaths()\n', paths_file);
input('I will still try to finish the initial setup (Press ENTER to continue)', 's');
else
rethrow(err)
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Build the omi Python package %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function build_omi_python
fprintf('\n');
% Get the version of python that Matlab will use
[~, py_exe] = pyversion;
build_omi_cmd = sprintf('%s setup.py build', py_exe);
install_omi_cmd = sprintf('%s setup.py install --user', py_exe);
psm_dir = fullfile(behr_paths.psm_dir, 'omi');
if exist(psm_dir, 'dir')
fprintf('BEHR relies on the omi Python package. This needs to be built and installed on your Python path.\n');
fprintf('I can try to do this for you; I would run:\n\n\t%s\n\nfollowed by\n\n\t%s\n\nin %s\n\n', build_omi_cmd, install_omi_cmd, psm_dir);
fprintf('I am using the Python executable that Matlab will use. You can change this with the pyversion() function.\n\n');
fprintf('If you change Python versions for Matlab, you should rebuild the omi package. To do a completely clean build,\ndelete the "build" folder in %s\n\n', psm_dir);
fprintf('Should I try to build the omi package? If not, you can do it manually later.\n');
if strcmpi(input(' Enter y to build, anything else to skip: ', 's'), 'y')
fprintf('Trying to build the omi package...\n');
oldwd = cd(psm_dir);
try
[build_status, build_result] = system(build_omi_cmd);
catch err
cd(oldwd);
rethrow(err);
end
if build_status == 0
fprintf('%s\n\n', build_result)
else
fprintf('Build failed. Output from build command:\n%s\n', build_result);
end
try
[install_status, install_result] = system(install_omi_cmd);
catch err
cd(oldwd);
rethrow(err);
end
cd(oldwd);
if install_status == 0
fprintf('%s\n\n', install_result);
fprintf('Build appears to be successful.\n');
else
fprintf('Build failed. Output from install command:\n%s\n', install_result);
end
else
fprintf('\nTo build the omi package yourself, execute "%s" followed by "%s"\nin %s\n\n', build_omi_cmd, install_omi_cmd, psm_dir);
fprintf('Note that your PATH and PYTHONPATH environmental variables may differ in the Terminal vs. the GUI Matlab.\n');
fprintf('If you experience difficultly with the PSM package after building in the Terminal, try building from Matlab instead.\n');
end
else
fprintf('The PSM directory (%s) in behr_paths is invalid. Fix that and rerun BEHR_initial_setup, or build the omi package manually.\n', behr_paths.psm_dir);
end
end
end
function str_out = wrap_comment(comment, indent_level)
% Assume each line is 76 characters long, allow 4 spaces for tabs and 2
% characters for the "% " at the beginning
nchars = 76 - 4*indent_level - 2;
tabs = repmat('\t', 1, indent_level);
i = 1;
str_out = '';
while i < length(comment)
% Find the last space before the end of the line
if length(comment) - i > nchars
i2 = min(length(comment), i+nchars);
j = strfind(comment(i:i2), ' ');
j = j(end);
else
j = length(comment) - i + 1;
end
str_out = [str_out, tabs, '%% ', strtrim(comment(i:i+j-1)), '\n'];
%str_out{end+1} = sprintf('%% %s\n',strtrim(comment(i:i+j-1)));
i = i+j;
end
end
function write_paths(paths, fid)
fns = fieldnames(paths);
for a=1:numel(fns)
if isfield(paths.(fns{a}), 'comment');
this_comment = wrap_comment(paths.(fns{a}).comment, 2);
else
this_comment = wrap_comment(fns{a}, 2);
end
fprintf(fid, this_comment);
if isfield(paths.(fns{a}), 'default')
this_default = paths.(fns{a}).default;
else
this_default = '';
end
if isfield(paths.(fns{a}), 'no_quote')
fprintf(fid, '\t\t%s = %s;\n\n', fns{a}, this_default);
else
fprintf(fid, '\t\t%s = ''%s'';\n\n', fns{a}, this_default);
end
end
end
function write_is_file_struct(paths, fid)
is_file_fxn = @(path_struct) isfield(path_struct, 'isfile');
write_bool_structure(paths, fid, 'is_field_file', is_file_fxn);
end
function write_iscodedir_structs(paths, fid)
iscodedir_fxn = @(path_struct) isfield(path_struct, 'is_code_dir');
do_genpath_fxn = @(path_struct) isfield(path_struct, 'is_code_dir') && ~strcmpi(path_struct.is_code_dir, 'norecurse');
is_pypath_fxn = @(path_struct) isfield(path_struct, 'is_pypath');
write_bool_structure(paths, fid, 'is_code_dir', iscodedir_fxn);
fprintf(fid, '\n');
write_bool_structure(paths, fid, 'do_genpath', do_genpath_fxn);
fprintf(fid, '\n');
write_bool_structure(paths, fid, 'is_pypath', is_pypath_fxn);
end
function write_bool_structure(paths, fid, struct_name, bool_fxn)
% Write a structure containing each of the paths as fields with a boolean
% value. "paths" must be the paths structure, fid an open file identifier,
% struct_name the name you want the struct to have a bool_fxn a handle to a
% functions that, when given the value of a field in paths returns the
% boolean value you want stored in the struct for that field.
bool_struct = struct;
fns = fieldnames(paths);
for a=1:numel(fns)
if bool_fxn(paths.(fns{a}))
bool_struct.(fns{a}) = 'true';
else
bool_struct.(fns{a}) = 'false';
end
end
fprintf(fid, '\t\t%s = struct(', struct_name);
for a=1:numel(fns)
if a < numel(fns)
fprintf(fid,'''%s'', %s,...\n\t\t\t', fns{a}, bool_struct.(fns{a}));
else
fprintf(fid,'''%s'', %s);\n', fns{a}, bool_struct.(fns{a}));
end
end
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
compute_flight_vector.m
|
.m
|
BEHR-core-utils-master/Regrid_tools/Compute_Corner_Pts_ms/compute_flight_vector.m
| 679 |
utf_8
|
2db9799e3119ef22e7c99d0f1a697ae1
|
%%compute_flight_vector
%%arr 12/10/2007
%JLL 2-18-2014: The flight vector is the straight line between two points
%on the earth's surface. It is the chord connecting those points, not the
%arc across the surface.
function [flightvector] = compute_flight_vector(lat, lon, lat1, lon1)
earthradius = 6378.5;
n = length(lat);
flightvector = zeros(n,3);
for i = 1:n;
[x1,y1,z1] = sph2cart(lon(i)*pi/180,lat(i)*pi/180,earthradius);
[x2,y2,z2] = sph2cart(lon1(i)*pi/180,lat1(i)*pi/180,earthradius);
dx = x2-x1; dy = y2-y1; dz = z2-z1;
flightvector(i,1) = dx;
flightvector(i,2) = dy;
flightvector(i,3) = dz;
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
compute_corner_pts.m
|
.m
|
BEHR-core-utils-master/Regrid_tools/Compute_Corner_Pts_ms/compute_corner_pts.m
| 1,436 |
utf_8
|
c809e3f1da3b689227cf8c9905002307
|
%%compute_corner_pts
%%arr 12/10/2007
function [latcorner, loncorner] = compute_corner_pts(lat, lon, flightvector, fwhm)
earthradius = 6378.5; %km
n = length(lat);
latcorner = zeros(n,2);
loncorner = zeros(n,2);
for i = 1:n;
[x1,y1,z1] = sph2cart(lon(i)*pi/180,lat(i)*pi/180,earthradius); %JLL 17 Mar 2014: This time we need the earth's radius because we are interested in the actual physical distance between the points, not in units of earth_radius
FV = flightvector(i,:); %JLL 17 Mar 2014: The 3D vector between adjacent rows
scale = (0.5 * fwhm(i)) / norm(FV); %JLL 17 Mar 2014: This will give the ratio between the "ideal" pixel size defined by its FWHM and its actual size, determined by the flight vector
posx1 = x1 - scale * FV(1); posy1 = y1 - scale * FV(2); posz1 = z1 - scale * FV(3); %JLL 17 Mar 2014: Find the corners for this side of the pixel
posx2 = x1 + scale * FV(1); posy2 = y1 + scale * FV(2); posz2 = z1 + scale * FV(3);
[poslatlonx1, poslatlony1, poslatlonz1] = cart2sph(posx1,posy1,posz1); %JLL 17 Mar 2014: Return to spherical coordinates
[poslatlonx2, poslatlony2, poslatlonz2] = cart2sph(posx2,posy2,posz2);
latcorner(i,1) = poslatlony1 / pi * 180; %JLL 17 Mar 2014: Convert back to degrees
latcorner(i,2) = poslatlony2 / pi * 180;
loncorner(i,1) = poslatlonx1 / pi * 180;
loncorner(i,2) = poslatlonx2 / pi * 180;
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
weight_flight_dir.m
|
.m
|
BEHR-core-utils-master/Regrid_tools/Compute_Corner_Pts_ms/weight_flight_dir.m
| 2,307 |
utf_8
|
3cb09cb6603c792cc3b6c03a292f851f
|
%%weight_flight_dir
%%arr 12/10/2007
%distance is the distance to the satellite
function [wx] = weight_flight_dir(distance, x)
%assume that the fwhm of ifov is 1 deg: (JLL 2-19-2014: ifov =
%intrinsic field of view, c.f. http://www.knmi.nl/omi/research/instrument/characteristics.php)
%This is the ifov along track
fwhm_deg = 1;
%the distance on the ground becomes:
fwhm_km = 2 .* tan(0.5 .* fwhm_deg ./ 180 .* pi) .* distance;
%using flat-topped gaussian with exponent 4:
%f(x) = exp(-c1 * (x - x0)^4)
%compute the constant c1, knowing that f(0.5 * fwhm_km) = 0.5
c1 = log(0.5) ./ (0.5 .* fwhm_km).^4;
%JLL 2-19-2014: This is the definition of ifov, that ifov is the field of
%view that has >0.5 pixel response. This constant fixes the gaussian s.t.
%at 1/2 fwhm_km from the center, the reponse is 0.5.
%x0 is the center of the pixel, ie the subsatellite point when half of the
%exposure time has passed.
%x0 is defined 0; thus all distances are wrt the center of the pixel.
%x0 is the middle of the ifov. at t=0, x0 is defined to 0. at time t, x0 =
%kt, where k is the ground speed:
%JLL 2-19-2014: k = 2*pi*r / (orbit period in s). The OMI orbit period is
%~ 100 min (98.83 by Wikipedia).
k = 2 .* pi .* 6378.5 ./ (100 .* 60);
%the OI master clock period is 2 seconds. the integration is done from t=-1
%to t=+1 seconds.
mcp = 2;
%the weight for a specific point x on the earth at time t becomes:
%w(x,t) = exp(c1 * (x1 - x0(t))^4);
%w(x,t) = exp(c1 * (x - kt)^4);
%to compute the weight for position x for a master clock period, we have to
%integrate from t=-1 to t=+1. this is done numerically:
nsteps = 5;
dt = mcp ./ nsteps;
wx = 0;
for i = 1:nsteps;
t = (i - 0.5) .* dt - 0.5 .* mcp; %JLL 17 Mar 2014: Set t to be at the middle of each time step
expo = (c1 .* (x - k .* t).^4); %JLL 17 Mar 2014: Calculate the exponent;
if (expo < -700); %JLL 17 Mar 2014: If all the elements of the exponent are < -700, go ahead and just set the result to 0
wxt = 0;
else
wxt = exp(expo); %JLL 17 Mar 2014: Otherwise, go ahead and calculate the expression
end
wx = wx + wxt;
end
wx = wx ./ nsteps;
%JLL 2-19-2014: Remember that x is a vector (1x101 matrix) so wx is
%actually a vector as well
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
compute_edge_pts.m
|
.m
|
BEHR-core-utils-master/Regrid_tools/Compute_Corner_Pts_ms/compute_edge_pts.m
| 1,579 |
utf_8
|
7c33a3b56929d5041fe96de4fda230f0
|
%%compute_edge_pts
%%arr 12/10/2007
function [latedge, lonedge] = compute_edge_pts(lat, lon)
n = length(lat);
latedge = zeros(n+1,1);
lonedge = zeros(n+1,1);
%the extrapolations
%JLL 5-12-2014: Assume that the pixel lat and lon is a linear function of
%"pixel number" and so calculate the edge of the first pixel by assuming
%the distance to the center of the pixel on either side is the same.
xx = find(~isnan(lat) & ~isnan(lon),2,'first');
[x1,y1,z1] = sph2cart(lon(xx(1))*pi/180,lat(xx(1))*pi/180,1);
[x2,y2,z2] = sph2cart(lon(xx(2))*pi/180,lat(xx(2))*pi/180,1);
dx = x1 - x2; dy = y1 - y2; dz = z1 - z2;
xi = x1 + dx; yi = y1 + dy; zi = z1 + dz;
[poslon,poslat,Z1] = cart2sph(xi,yi,zi);
lonedge(1) = poslon / pi * 180;
latedge(1) = poslat / pi * 180;
[x1,y1,z1] = sph2cart(lon(n)*pi/180,lat(n)*pi/180,1);
[x2,y2,z2] = sph2cart(lon(n-1)*pi/180,lat(n-1)*pi/180,1);
dx = x1 - x2; dy = y1 - y2; dz = z1 - z2;
xi = x1 + dx; yi = y1 + dy; zi = z1 + dz;
[poslon,poslat,Z1] = cart2sph(xi,yi,zi);
lonedge(n+1) = poslon / pi * 180;
latedge(n+1) = poslat / pi * 180;
%the interpolations
%JLL 2-18-2014: Assume that the edge between pixels is halfway in between
%the center points.
for i = 2:n;
[x1,y1,z1] = sph2cart(lon(i-1)*pi/180,lat(i-1)*pi/180,1);
[x2,y2,z2] = sph2cart(lon(i)*pi/180,lat(i)*pi/180,1);
xi = 0.5*(x1 + x2); yi = 0.5*(y1 + y2); zi = 0.5*(z1 + z2);
[poslon,poslat,Z1] = cart2sph(xi,yi,zi);
lonedge(i) = poslon / pi * 180;
latedge(i) = poslat / pi * 180;
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
weight_distance.m
|
.m
|
BEHR-core-utils-master/Regrid_tools/Compute_Corner_Pts_ms/weight_distance.m
| 758 |
utf_8
|
c4901b7273255d3788e9707a9fa914ac
|
%%weight_distance
%%arr 12/10/2007
%computes the array of weights on the ground as a function of the distance
%to the center of the ground pixel
function [fwhm] = weight_distance(distance)
%JLL 2-19-2014: These were commented out when I received the file.
%nsteps = 1001;
%start = -50;
%xend = 50;
%dx = (xend - xstart) / (nsteps - 1);
%wx = zeros(nsteps,1);
%x = zeros(nsteps,1);
x=linspace(-50,50,101); %JLL 17 Mar 2014: x must be in km, since in weight flight direction it is used in "x - k*t"; k is ground speed in km/s
wx = weight_flight_dir(distance, x);
%normalize wx
wx = wx / max(wx);
%determine fwhm
aa = (abs(wx - 0.5));
bb = find(aa==min(aa));
fwhm = abs(2 * x(bb(1))); %This is the fwhm in km
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
compute_distance.m
|
.m
|
BEHR-core-utils-master/Regrid_tools/Compute_Corner_Pts_ms/compute_distance.m
| 1,045 |
utf_8
|
49532ac0754613512a0c765b5f7d9f1b
|
%%compute_distance
%%arr 12/10/2007
%JLl 2-19-2014: I believe that lat and lon SHOULD be single numbers but am
%not positive. This then returns the distance from the satellite to the
%latitude and longitude input.
function [distance] = compute_distance(lat, lon, satlat, satlon, satalt)
earthradius = 6378.5;
[earthposx,earthposy,earthposz] = sph2cart(lon.*pi./180, lat.*pi./180, 1);
earthpos = [earthposx', earthposy', earthposz'];
[satposx,satposy,satposz] = sph2cart(satlon.*pi./180, satlat.*pi./180, satalt./earthradius + 1); %JLL 2-19-2014: satalt is alt. above the surface, the +1 converts that into the proper r-coordinate
satpos = [satposx, satposy, satposz];
satpos=repmat(satpos,length(lat),1);
distance = norm(satpos - earthpos); %JLL 2-19-2014: Assuming that satpos and earthpos are simply 3D vectors, this finds the distance between earth and the satellite.
distance = distance .* earthradius; %JLL 2-19-2014: Since the conversion to cartesian coordinates assumed a unit sphere, this converts back to km.
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
fxn_corner_coordinates.m
|
.m
|
BEHR-core-utils-master/Regrid_tools/Compute_Corner_Pts_ms/fxn_corner_coordinates.m
| 2,961 |
utf_8
|
96c75caa5b83b8acabb93b2b1c3cee01
|
%%corner_coordinates
%%arr 12/10/2007
%%JLL 3 Mar 2014 - Converted to a function to make more clear input and
%%output values.
%{
Latitude=zeros(60,y); Longitude=zeros(60,y); SpacecraftLatitude=zeros(60,y);
SpacecraftLongitude=zeros(60,y); SpacecraftAltitude=zeros(60,y)
where y = number of scanlines in the orbit, with 60 scenes per scanline
returns array (60,y,2,5), 2=lon,lat, 5=corners(5th=center)
%}
function corners = fxn_corner_coordinates(Latitude, Longitude, SpacecraftLatitude, SpacecraftLongitude, SpacecraftAltitude)
Latitude(Latitude<-1e29) = NaN;
Longitude(Longitude<-1e29) = NaN;
dims = size(Latitude);
corners = zeros(dims(1),dims(2),2,5);
for y = 1:dims(1)-1;
lat = Latitude(y,:);
lon = Longitude(y,:);
lat1 = Latitude(y+1,:);
lon1 = Longitude(y+1,:);
satlat = SpacecraftLatitude(y);
satlon = SpacecraftLongitude(y);
satalt = SpacecraftAltitude(y);
if sum(~isnan(lat) & ~isnan(lon) & ~isnan(lat1) & ~isnan(lon1)) < 2
fprintf('At least one of the rows is almost all NaNs\n');
continue
elseif isnan(satlat) || isnan(satlon) || isnan(satalt)
fprintf('One of the satellite position values is a nan\n');
continue
else
satalt = satalt * 1E-3; %convert to km
%compute the ground pixel edge lat, lon in the across track direction
%JLL 2-18-2014: These points lie on the edge between pixels in their
%own rows.
[latedge, lonedge] = compute_edge_pts(lat, lon);
[latedge1, lonedge1] = compute_edge_pts(lat1, lon1);
%compute flight vector
%JLL 2-19-2014: The ith row is a 3D-vector connecting the ith edge
%points of two adjacent rows
flightvector = compute_flight_vector(latedge, lonedge, latedge1, lonedge1);
%compute fwhm in the flight direction if not already calculated
fwhm = compute_fwhm(latedge, lonedge, satlat, satlon, satalt);
%compute corner points
[latcorner, loncorner] = compute_corner_pts(latedge, lonedge, flightvector, fwhm);
for x = 1:dims(2);
%JLL 17 Mar 2014: corners will have the structure (<row>, <pixel in
%row>, <1=lon, 2=lat>, <corner number, 5 = center>)
corners(y,x,1,1) = loncorner(x,1);
corners(y,x,2,1) = latcorner(x,1);
corners(y,x,1,2) = loncorner(x+1,1);
corners(y,x,2,2) = latcorner(x+1,1);
corners(y,x,1,3) = loncorner(x+1,2);
corners(y,x,2,3) = latcorner(x+1,2);
corners(y,x,1,4) = loncorner(x,2);
corners(y,x,2,4) = latcorner(x,2);
corners(y,x,1,5) = lon(x);
corners(y,x,2,5) = lat(x);
if any(any(isnan(corners(y,x,:,:))));
corners(y,x,:,:) = NaN;
end
end
end
end
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
compute_fwhm.m
|
.m
|
BEHR-core-utils-master/Regrid_tools/Compute_Corner_Pts_ms/compute_fwhm.m
| 456 |
utf_8
|
cba3a9e5634a9844a27519fa9236d567
|
%%compute_fwhm
%%arr 12/10/2007
function [fwhm] = compute_fwhm(lat, lon, satlat, satlon, satalt)
n = length(lat);
fwhm = zeros(n,1);
distance = zeros(n,1);
for i = 1:n;
distance(i) = compute_distance(lat(i), lon(i), satlat, satlon, satalt); %This is the distance from the satellite to the lat/lon specified
if isnan(distance(i));
fwhm(i) = NaN;
else
fwhm(i) = weight_distance(distance(i));
end
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
compute_edge_pts_2014.m
|
.m
|
BEHR-core-utils-master/Regrid_tools/Compute_Corner_Pts_ms/compute_edge_pts_2014.m
| 1,637 |
utf_8
|
88e4ec96b9c141f1134437ba00c210bc
|
%%compute_edge_pts
%%arr 12/10/2007
function [latedge, lonedge] = compute_edge_pts(lat, lon)
n = length(lat);
latedge = zeros(n+1,1);
lonedge = zeros(n+1,1);
%the extrapolations
%JLL 5-12-2014: Assume that the pixel lat and lon is a linear function of
%"pixel number" and so calculate the edge of the first pixel by assuming
%the distance to the center of the pixel on either side is the same.
[x1,y1,z1] = sph2cart(lon(1)*pi/180,lat(1)*pi/180,1);
[x2,y2,z2] = sph2cart(lon(2)*pi/180,lat(2)*pi/180,1);
dx = x1 - x2; dy = y1 - y2; dz = z1 - z2;
xi = x1 + 0.5*dx; yi = y1 + 0.5*dy; zi = z1 + 0.5*dz; %JLL 13 May 2014: Changed because the edges of the edge pixels should be half the distance between pixel centers
[poslon,poslat,Z1] = cart2sph(xi,yi,zi);
lonedge(1) = poslon / pi * 180;
latedge(1) = poslat / pi * 180;
[x1,y1,z1] = sph2cart(lon(n)*pi/180,lat(n)*pi/180,1);
[x2,y2,z2] = sph2cart(lon(n-1)*pi/180,lat(n-1)*pi/180,1);
dx = x1 - x2; dy = y1 - y2; dz = z1 - z2;
xi = x1 + dx; yi = y1 + dy; zi = z1 + dz;
[poslon,poslat,Z1] = cart2sph(xi,yi,zi);
lonedge(n+1) = poslon / pi * 180;
latedge(n+1) = poslat / pi * 180;
%the interpolations
%JLL 2-18-2014: Assume that the edge between pixels is halfway in between
%the center points.
for i = 2:n;
[x1,y1,z1] = sph2cart(lon(i-1)*pi/180,lat(i-1)*pi/180,1);
[x2,y2,z2] = sph2cart(lon(i)*pi/180,lat(i)*pi/180,1);
xi = 0.5*(x1 + x2); yi = 0.5*(y1 + y2); zi = 0.5*(z1 + z2);
[poslon,poslat,Z1] = cart2sph(xi,yi,zi);
lonedge(i) = poslon / pi * 180;
latedge(i) = poslat / pi * 180;
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
behr_data_check_parse.m
|
.m
|
BEHR-core-utils-master/Utils/behr_data_check_parse.m
| 3,178 |
utf_8
|
2a1efe441ff19ddfd8a9789f21b2de14
|
function [ ] = behr_data_check_parse( Data_Chk )
%behr_data_check_parse Writes a text file with missing BEHR data.
% Takes the data structure from behr_data_check and writes out a text
% file in the current directory containing the information.
E = JLLErrors;
%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% INPUT PARSING %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
% Check that a structure was passed.
if ~isstruct(Data_Chk)
error(E.badinput('This function only accepts a structure.'));
end
%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% MAIN PROGRAM %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
fid = fopen('BEHR_Data_Check.txt','w');
fprintf(fid,'OMNO2:\n');
readData(Data_Chk.OMNO2,fid);
fprintf(fid,'\n\nMYD06:\n');
readData(Data_Chk.MYD06,fid);
fprintf(fid,'\n\nMCD43C3:\n');
readData(Data_Chk.MCD43C3,fid);
fclose(fid);
end
function readData(Data,fid)
% These are the possible states that the data can be in. Missing means
% altogether not there, incomplete means some of the swaths aren't
% there but at least one from each day is.
states = {'Missing','Incomplete'};
fields = fieldnames(Data);
% The field names should contain the year. Look for 4 numbers in a
% row, and read just those. That will be used as the second level
% header in the file.
years = cell(size(fields));
for y=1:numel(years)
i = regexp(fields{y},'\d\d\d\d');
years_numstr = fields{y}(i:i+3);
fprintf(fid,'\t%s:\n',years_numstr);
data_chk = Data.(fields{y});
if ~iscell(data_chk)
% Each year will contain a cell array unless all the data is
% present, in which case, the field will be the string 'All
% data found'. Since that's not a cell and we only care about
% missing data, we'll skip that year.
continue
end
data_by_state = struct('State',states,'Dates',{cell(size(data_chk))});
for a=1:numel(states)
A=1;
% i will indicate were the state ends and the date range string
% begins so that we can trim off the state. Each entry in
% data_chk should have the form: <state>: YYYY-MM-DD to
% YYYY-MM-DD so the +2 accounts for the colon and space.
i = length(states{a}) + 2;
% Now go through the entries and determine which state they
% belong to. We'll organize them into the data_by_state
% structure so that we can print them grouped by state.
for b=1:numel(data_chk)
date_range = data_chk{b};
if ~isempty(regexpi(date_range,states{a}))
data_by_state(a).Dates{A} = strtrim(date_range(i:end));
A = A+1;
end
end
data_by_state(a).Dates = data_by_state(a).Dates(1:A-1);
end
% Now handle the actual printing to the file.
for c=1:numel(data_by_state)
fprintf(fid,'\t\t%s:\n',data_by_state(c).State);
for d=1:numel(data_by_state(c).Dates)
fprintf(fid,'\t\t %s\n',data_by_state(c).Dates{d});
end
end
end
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
cat_sat_data.m
|
.m
|
BEHR-core-utils-master/Utils/cat_sat_data.m
| 10,701 |
utf_8
|
7e92a78afa369ac3f91e13df3b778bfb
|
function [ varargout ] = cat_sat_data( filepath, datafields, varargin )
%CAT_SAT_DATA( FILEPATH, DATAFIELDS ) Concatenates data from OMI .mat files
% In some cases, one might wish to use satellite data from multiple days,
% but we import OMI data and process BEHR data into daily files. This
% function will load all the .mat files in the directory given by
% FILEPATH and output a concatenated version of the data in the field or
% fields given by DATAFIELDS, which should be a string or cell array of
% strings. The output will be each requested data field as a separate
% output, plus a cell array that gives the date, orbit, and pixel number
% of each value in the first data field.
%
% CAT_SAT_DATA( DATA, DATAFIELDS ) will concatenate all swaths in the
% structure DATA for the fields specified in DATAFIELDS. If DATAFIELDS is
% an empty array, all fields will be concatenated.
%
% Parameter arguments are:
%
% 'prefix' - the prefix of the file names (the part before the date).
% This function will use all files in the directory FILEPATH that
% match the pattern <PREFIX>*.mat, replacing <PREFIX> with the given
% prefix. This defaults to an empty string, i.e. by default all .mat
% files will be matched.
%
% 'startdate' and 'enddate' - any valid representation of dates
% (datenum or datestr). If only one is given, it will be treated as a
% start or end point with the other unspecified (e.g. if you specify
% startdate as 1-Jan-2015, this will operate on all files after
% 1-Jan-2015)
%
% 'newdim' - boolean, defaults to false. When true, each variable will
% be concatenated along a new dimension (so a 2D variable will be
% concatenated along the third dimension, a 3D one along the fourth).
% When false, they will be concatenated in the along track dimension.
%
% 'vector' - boolean, defaults to false. When true, each swatch is
% resized into a column vector before concatenation. Mutually
% exclusive with 'newdim'.
%
% 'varname' - must be the string 'Data' or 'OMI'. 'Data' is default.
% Indicates whether the structure concatenated should be the native
% pixels ('Data') or the gridded pixels ('OMI').
%
% 'reject_args' - a cell array of arguments to be passed to
% OMI_PIXEL_REJECT after the Data structure (so the second and later
% arguments). If not given (or an empty array) then OMI_PIXEL_REJECT
% is not called. If given, then pixels rejected by OMI_PIXEL_REJECT
% will be either replaced with NaN or (if 'vector' is true) removed.
% NOTE: in vector mode, all fields have rejected values removed.
% However, in all other modes, only numerical fields have rejected
% pixels set to NaN; e.g. logical fields will not be affected by
% pixel filtering.
%
% 'struct_out' - if false (default) each concatenated field is
% returned separately as its own output. If true, the fields are
% returned in a scalar structure.
%
% 'DEBUG_LEVEL' - set to 0 to suppress debugging messages, defaults
% to 1. Set to 'visual' to use the waitbar dialogue.
%
% Josh Laughner <[email protected]> 10 Sept 2015
E=JLLErrors;
%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% INPUT PARSING %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
if isstruct(filepath)
Data = filepath;
load_data = false;
else
load_data = true;
if ~ischar(filepath) || ~exist(filepath,'dir')
E.badinput('filepath must be a string specifying a valid directory')
end
end
if ischar(datafields)
datafields = {datafields};
elseif isempty(datafields) && isstruct(filepath)
datafields = fieldnames(Data);
elseif ~iscell(datafields) || any(~iscellcontents(datafields,'ischar'))
E.badinput('datafields must be a string or cell array of strings')
end
p=inputParser;
p.addParameter('prefix','',@ischar);
p.addParameter('startdate',0);
p.addParameter('enddate','3000-01-01'); % pick a date far enough into the future that effectively all files will be before it
p.addParameter('newdim',false);
p.addParameter('vector',false);
p.addParameter('varname','Data');
p.addParameter('reject_args',{});
p.addParameter('struct_out', false);
p.addParameter('DEBUG_LEVEL',1,@(x) (ischar(x) || isnumeric(x) && isscalar(x)));
p.parse(varargin{:});
pout = p.Results;
prefix = pout.prefix;
startdate = pout.startdate;
enddate = pout.enddate;
newdim = pout.newdim;
vector_bool = pout.vector;
varname = pout.varname;
reject_args = pout.reject_args;
do_output_struct = pout.struct_out;
DEBUG_LEVEL = pout.DEBUG_LEVEL;
if ~ismember(varname,{'Data','OMI'})
E.badinput('VARNAME must be either ''Data'' or ''OMI''');
end
if newdim && vector_bool
E.badinput('NEWDIM and VECTOR are mutually exclusive')
end
wbbool = false;
if ischar(DEBUG_LEVEL)
if strcmpi(DEBUG_LEVEL, 'visual')
if isDisplay
wbbool = true;
DEBUG_LEVEL = 0;
end
else
warning('Only the string ''visual'' for DEBUG_LEVEL will trigger the use of the waitbar.')
DEBUG_LEVEL = 1;
end
end
startdate = validate_date(startdate);
enddate = validate_date(enddate);
date_array = [startdate(:), enddate(:)];
if startdate > enddate
E.badinput('startdate is later than enddate.')
end
if ~isscalar(newdim) || (~islogical(newdim) && ~isnumeric(newdim))
E.badinput('The parameter newdim must be understood as a scalar logical.')
end
if ~isscalar(vector_bool) || (~islogical(vector_bool) && ~isnumeric(vector_bool))
E.badinput('The parameter vector must be understood as a scalar logical.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% MAIN FUNCTION %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
if load_data
% Get all .mat files in the specified directory
F = dir(fullfile(filepath, sprintf('%s*.mat',prefix)));
if isempty(F)
E.filenotfound('satellite .mat file');
end
else
F = 0;
end
% Prep output - we'll always include the date and swath as the last output
output_data = cell(1,numel(datafields)+1);
% Loop over all files (within the date limits given). Load the data
% variable, look for the datafields given, and add their data to the output
% which will be one long column vector.
if wbbool && load_data
wb = waitbar(0,sprintf('Concatenating %s*.mat',strrep(prefix,'_','\_')));
elseif wbbool
wb = waitbar(0,'Concatenating input structure');
end
for a=1:numel(F)
if load_data
[s,e] = regexp(F(a).name, '\d\d\d\d\d\d\d\d');
filedate = datenum(F(a).name(s:e), 'yyyymmdd');
in_date_ranges = filedate >= date_array(:,1) & filedate <= date_array(:,2);
if ~any(in_date_ranges)
continue
end
D = load(fullfile(filepath, F(a).name),varname);
if ~isfield(D, varname)
fprintf('%s does not contain the variable "%s", skipping\n', F(a).name, varname);
continue
else
Data = D.(varname);
end
if DEBUG_LEVEL > 0
fprintf('Loading file %s...\n',F(a).name);
elseif wbbool
waitbar(a/numel(F));
end
end
for b=1:numel(datafields)
if ~isfield(Data,datafields{b})
if isstruct(F)
E.callError('fieldnotfound','The field %s is not present in file %s',datafields{b},F(a).name);
else
E.callError('fieldnotfound','The field %s is not present in the input Data structure',datafields{b});
end
end
for c=1:numel(Data)
this_field = Data(c).(datafields{b});
this_date_and_swath = format_date_swath_cell(Data(c), size(this_field));
if ~isempty(reject_args)
Data(c).Areaweight = ones(size(Data(c).Longitude));
Data(c) = omi_pixel_reject(Data(c), reject_args{:});
xx_keep = Data(c).Areaweight > 0;
if vector_bool
this_field(~xx_keep) = [];
this_date_and_swath(~xx_keep) = [];
else
% Logical fields cannot have values set to NaN. Since
% only numeric fields should really be filtered for low
% quality data, this shouldn't be a problem.
if isnumeric(this_field)
this_field(~xx_keep) = NaN;
end
% No need to set date and swath to NaNs, we just want
% to mark bad data as invalid.
end
end
if newdim
n = ndims(this_field);
output_data{b} = cat(n+1, output_data{b}, this_field);
if b == 1
output_data{end} = cat(n+1, output_data{end}, this_date_and_swath);
end
elseif vector_bool
output_data{b} = cat(1, output_data{b}, this_field(:));
if b == 1
output_data{end} = cat(1, output_data{end}, this_date_and_swath(:));
end
elseif ~newdim && ismatrix(Data(c).(datafields{b}))
output_data{b} = cat(1, output_data{b}, this_field);
if b == 1
output_data{end} = cat(1, output_data{end}, this_date_and_swath);
end
elseif ~newdim && ~ismatrix(Data(c).(datafields{b}))
output_data{b} = cat(2, output_data{b}, this_field);
if b == 1
output_data{end} = cat(2, output_data{end}, this_date_and_swath);
end
else
E.notimplemented(sprintf('concat case: newdim = %d and ndims = %d',newdim,ndims(Data(c).(datafields{b}))));
end
end
end
end
if wbbool
close(wb);
end
if do_output_struct
output_field_names = veccat(datafields, {'DateAndSwath'});
% Have to put the date/orbit cell array into a parent cell array to
% avoid creating a multielement structure
output_data{end} = {output_data{end}}; %#ok<CCAT1>
varargout{1} = make_struct_from_field_values(output_field_names, output_data);
else
varargout = output_data;
end
end
function ds_cell = format_date_swath_cell(data, sz)
E = JLLErrors;
if ~isscalar(data) || ~isstruct(data)
E.badinput('DATA must be a scalar structure');
end
date = data.Date;
% Old files might have Swath as a matrix, and sometimes will incorrectly
% have a 0 in there, this should ensure we get the correct swath number as
% a scalar value
swath = unique(data.Swath(data.Swath > 0));
ds_cell = cell(sz);
for a=1:numel(ds_cell)
ds_cell{a} = sprintf('%s_o%d_p%d',date,swath,a);
end
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
hdfreadmodis.m
|
.m
|
BEHR-core-utils-master/Utils/hdfreadmodis.m
| 3,798 |
utf_8
|
42142015479b117641fd5f4522c4928c
|
function [ data, fill_value, scale_factor, offset ] = hdfreadmodis( filename, dsetname, varargin )
%HDFREADMODIS Wrapper around HDFREAD that handles fills, scale, and offset for MODIS files
% DATA = HDFREADMODIS( FILENAME, DSETNAME ) - Reads in the dataset from
% FILENAME at internal path DSETNAME. Uses HDFREAD internally as
% HDFREAD(FILENAME, DSETNAME), so the DSETNAME must be formatted such
% that HDFREAD understands it. Fill values defined by the _FillValue
% attribute are converted to NaNs and the scale factor and offset are
% applied as DATA = scale_factor * (hdf_values - add_offset).
%
% DATA = HDFREADMODIS( ___, 'fill_crit', FILL_CRIT ) allows you to
% specify the relative difference allowed between a value in the data set
% and the fill value for the value to be considered a fill value, i.e.
%
% abs((val - fill_val)/fill_val) < fill_crit
%
% must be met for VAL to be considered a fill value. Defaults to 0.001.
%
% DATA = HDFREADMODIS( ___, 'log_index', {xx1, xx2, ...} ) uses the
% logical vectors xx1, xx2, etc. to generate START, STRIDE, EDGE arrays
% to subset the SDS during reading. xx1, xx2, etc. should be logical
% arrays that are TRUE for indicies in the corresponding dimension of the
% dataset that you want to include. Note: this assumes that the region to
% read in is contiguous. If not, a warning is issued.
%
% [ DATASET, FILL_VALUE, SCALE_FACTOR, OFFSET ] = HDFREADMODIS( __ )
% returns the other attributes as well as the dataset.
E = JLLErrors;
p = inputParser;
p.addParameter('fill_crit',0.001);
p.addParameter('log_index', {});
p.parse(varargin{:});
pout = p.Results;
fill_crit = pout.fill_crit;
if ~isnumeric(fill_crit) || ~isscalar(fill_crit) || fill_crit <= 0
E.badinput('FILL_CRIT must be a positive, scalar number')
end
log_index = pout.log_index;
if ~iscell(log_index) || any(~iscellcontents(log_index, 'isvector')) || any(~iscellcontents(log_index, 'islogical'))
E.badinput('LOG_CRIT must be a cell array of logical vectors')
end
if isempty(log_index)
data = double(hdfread(filename, dsetname));
else
index_cell = make_index_cell(log_index);
data = double(hdfread(filename, dsetname, 'index', index_cell));
end
fill_value = double(hdfreadatt(filename, dsetname, '_FillValue'));
try
scale_factor = double(hdfreadatt(filename, dsetname, 'scale_factor'));
catch err
if strcmp(err.identifier, 'hdfreadatt:hdf_attribute')
warning('No scale_factor attribute found for %s, setting to 1', dsetname);
scale_factor = 1;
else
rethrow(err)
end
end
try
offset = double(hdfreadatt(filename, dsetname, 'add_offset'));
catch err
if strcmp(err.identifier, 'hdfreadatt:hdf_attribute')
warning('No add_offset attribute found for %s, setting to 0', dsetname);
offset = 0;
else
rethrow(err);
end
end
fills = abs((data - fill_value) ./ fill_value) < fill_crit;
data(fills) = nan;
% This treatment is given by the MODIS MOD06 theoretical basis document, p.
% 87 (https://modis-atmos.gsfc.nasa.gov/_docs/C6MOD06OPUserGuide.pdf) and
% the metadata for MCD43C1 v006
% (https://ladsweb.modaps.eosdis.nasa.gov/api/v1/filespec/product=MCD43C1&collection=6,
% search BRDF_Albedo_Parameter).
data = (data - offset) * scale_factor;
end
function c = make_index_cell(log_index)
c = cell(1,3);
c([1,3]) = {zeros(1,numel(log_index))};
c(2) = {ones(1,numel(log_index))};
for a=1:numel(log_index)
s = find(log_index{a}, 1, 'first');
e = find(log_index{a}, 1, 'last')-s+1;
if ~all(log_index{a}(s:e))
warning('Subset of dimension %d is not contiguous, all elements between the first and last true value will be used', a)
end
c{1}(a) = s; % do not need to switch to 0 based indexing
c{3}(a) = e;
end
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
behr_data_check.m
|
.m
|
BEHR-core-utils-master/Utils/behr_data_check.m
| 13,437 |
utf_8
|
8a80c5f57a518197531024c37f8d540e
|
function [ Data_Struct ] = behr_data_check( )
%behr_data_check Checks for missing satellite files needed for BEHR
% BEHR requires 3 different satellite data sets:
% 1) The Level 2 OMNO2 files
% 2) Aqua-MODIS cloud product (MYD06_L2)
% 3) 16-day combined MODIS albedo (MCD43)
% This function will check each of these in the directories they are
% supposed to be and return a structure indicating any missing files
% Create the error handling class
E = JLLErrors;
DEBUG_LEVEL = 1;
% Get today's date
todays_d = day(today);
todays_m = month(today);
todays_y = year(today);
% Prepare the output structure, it will have the form satellite/year
n_years = todays_y - 2004 + 1;
struct_base = cell(1,2*n_years);
for a=1:n_years
y = 2004 + a - 1;
i = a*2 - 1; % edit the odd indicies of the cell
struct_base{i} = sprintf('Y_%d',y);
end
Data_Struct = struct('OMNO2',struct(struct_base{:}),'MYD06',struct(struct_base{:}),'MCD43C3',struct(struct_base{:}));
% First, check the OMNO2 data. OMI data starts around Oct 2004. The
% subfunction checkDaily allows the same code to be used for MODIS Cloud
% and OMI. Look for at least 13 files per day.
if DEBUG_LEVEL > 0; fprintf('\n***** Checking OMNO2 data. *****\n\n'); end
omno2dir = omno2_dir();
omno2pat_fxn = @(s) omiPat(s);
omno2_pathbuilder_fxn = @(sat,yr,mn) omiPathBuilder(sat,yr,mn);
omno2_chk_fxn = @(f) omiDataCheck(f);
Data_Struct = checkDaily(Data_Struct, todays_y, todays_m, omno2pat_fxn, omno2_pathbuilder_fxn, omno2dir, 'OMNO2', omno2_chk_fxn, DEBUG_LEVEL);
% Next, MODIS cloud data. There should be at least 18 files per day, but
% we'll relax that to 17 to be careful.
if DEBUG_LEVEL > 0; fprintf('\n***** Checking MYD06 data. *****\n\n'); end
modclddir = modis_cloud_dir;
modcldpat_fxn = @(s) modisCldPat(s);
modis_pathbuilder_fxn = @(sat,yr,mn) modisPathBuilder(sat,yr,mn);
modis_chk_fxn = @(f) modisCloudDataCheck(f);
Data_Struct = checkDaily(Data_Struct, todays_y, todays_m, modcldpat_fxn, modis_pathbuilder_fxn, modclddir, 'MYD06', modis_chk_fxn, DEBUG_LEVEL);
% Finally, MODIS albedo data.
if DEBUG_LEVEL > 0; fprintf('\n***** Checking MCD43 data. *****\n\n'); end
modalbdir = modis_albedo_dir;
modalbpath_fxn = @(s) modisAlbPat(s);
modis_pathbuilder_fxn = @(sat,yr) modisPathBuilder(sat,yr);
Data_Struct = check8Daily(Data_Struct, todays_y, todays_m, modalbpath_fxn, modis_pathbuilder_fxn, modalbdir, 'MCD43C3', 1, DEBUG_LEVEL);
end
%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% SUB FUNCTIONS %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
function Data_Struct = checkDaily(Data_Struct, todays_y, todays_m, sat_pat_fxn, sat_pathbuilder, sat_dir, sat_field, sat_test_fxn, DEBUG_LEVEL)
% Used in the messages
statuses = {'Missing', 'Incomplete'};
for ch_year = 2004:todays_y
ch_year_str = num2str(ch_year);
if DEBUG_LEVEL > 0; fprintf('\tNow checking year %s\n',ch_year_str); end
months = setMonths(ch_year, todays_y, todays_m);
day_chk = setDays(ch_year, todays_y, todays_m, 1);
for ch_month = months;
ch_month_str = sprintf('%02d',ch_month);
if DEBUG_LEVEL > 1; fprintf('\t\tMonth: %s\n',ch_month_str); end
ch_path = sat_pathbuilder(sat_dir,ch_year_str,ch_month_str);
days = 1:eomday(ch_year,ch_month);
for ch_day = days;
ch_day_str = sprintf('%02d',ch_day);
% Iterate through the days of the month, checking the number of
% files for each day.
S.ch_year_str = ch_year_str;
S.ch_month_str = ch_month_str;
S.ch_day_str = ch_day_str;
day_pat = sat_pat_fxn(S);
FILES = dir(fullfile(ch_path,day_pat));
chk = sat_test_fxn(FILES);
% Copy this to the year long day vector for today.
curr_date = sprintf('%s-%s-%s',ch_year_str,ch_month_str,ch_day_str);
ind = modis_date_to_day(curr_date);
day_chk(ind) = chk;
end
end
% Find the contiguous blocks of values, we'll then parse this into
% messages for the year to be saved to the structure.
blocks = findBlock(day_chk);
messages = cell(size(blocks,1),1);
mi = 1;
for m=1:numel(messages)
st_date = modis_day_to_date(blocks(m,1),ch_year);
end_date = modis_day_to_date(blocks(m,2),ch_year);
status = blocks(m,3);
if status < 2;
messages{mi} = sprintf('%s: %s to %s',statuses{status+1},st_date,end_date);
mi=mi+1;
end
end
messages(mi:end) = [];
if isempty(messages)
messages = 'All data found';
end
fname = sprintf('Y_%s',ch_year_str);
Data_Struct.(sat_field).(fname) = messages;
end
end
function Data_Struct = check8Daily(Data_Struct, todays_y, todays_m, sat_pat_fxn, sat_pathbuilder_fxn, sat_dir, sat_field, req_num_files, DEBUG_LEVEL)
% Used in the messages
statuses = {'Missing', 'Incomplete'};
for ch_year = 2004:todays_y
ch_year_str = num2str(ch_year);
if DEBUG_LEVEL > 0; fprintf('\tNow checking year %s\n',ch_year_str); end
[day_chk, days] = setDays(ch_year, todays_y, todays_m, 8);
% Here we take advantage of the fact that MATLAB functions don't need
% as many arguments as they accept as long as the unpassed arguments
% are not required.
ch_path = sat_pathbuilder_fxn(sat_dir, ch_year_str);
% MODIS albedo files are not stored by month, so we just look for each
% day that should exist in the year folder
for d = 1:numel(days)
ch_day_str = sprintf('%03d',days(d));
S.ch_year_str = ch_year_str;
S.ch_day_str = ch_day_str;
day_pat = sat_pat_fxn(S);
FILES = dir(fullfile(ch_path,day_pat));
% If there are at least req_num_files files, consider the day
% to be complete. If there are some, but not 13, mark it as
% incomplete. If there are none, mark it as empty.
if numel(FILES) >= req_num_files;
chk = 2;
elseif numel(FILES) > 0 && numel(FILES) < req_num_files;
chk = 1;
else
chk = 0;
end
% Copy this to the year long day vector for today.
day_chk(d) = chk;
end
% Find the contiguous blocks of values, we'll then parse this into
% messages for the year to be saved to the structure.
blocks = findBlock(day_chk);
messages = cell(size(blocks,1),1);
mi = 1;
for m=1:numel(messages)
st_date = modis_day_to_date(blocks(m,1),ch_year);
end_date = modis_day_to_date(blocks(m,2),ch_year);
status = blocks(m,3);
if status < 2;
messages{mi} = sprintf('%s: %s to %s',statuses{status+1},st_date,end_date);
mi=mi+1;
end
end
messages(mi:end) = [];
if isempty(messages)
messages = 'All data found';
end
fname = sprintf('Y_%s',ch_year_str);
Data_Struct.(sat_field).(fname) = messages;
end
end
function months = setMonths(ch_year,todays_y, todays_m)
% If we're checking 2004, only do months 10-12. If we're checking this
% year, only go up to the current month. Otherwise do all the months.
if ch_year == 2004;
months = 10:12;
elseif ch_year == todays_y;
months = 1:todays_m;
else
months = 1:12;
end
end
function [day_chk, days] = setDays(ch_year, todays_y, todays_m, ndays)
% Returns day_chk - a vector of zeros and days, a sequential vector. ndays
% determines the step size between days.
if false%leapyear(ch_year)
days = 1:ndays:366;
else
days = 1:ndays:365;
end
day_chk = zeros(size(days));
if ch_year == todays_y
month = sprintf('%02d',todays_m+1);
test_date = sprintf('%d-%s-01',todays_y,month);
last_day = modis_date_to_day(test_date);
day_chk(last_day:end) = 3; % use 3 to indicate data that is not available, period
elseif ch_year == 2004;
last_day = modis_date_to_day('2004-09-30');
day_chk(1:last_day) = 3;
end
end
function pat = omiPat(S)
omno2pat = 'OMI-Aura_L2-OMNO2_%sm%s%s*.he5';
pat = sprintf(omno2pat,S.ch_year_str,S.ch_month_str,S.ch_day_str);
end
function pat = modisCldPat(S)
modcldpat = 'MYD06_L2.A%s%03d*.hdf';
modday = modis_date_to_day(sprintf('%s-%s-%s',S.ch_year_str,S.ch_month_str,S.ch_day_str));
pat = sprintf(modcldpat,S.ch_year_str,modday);
end
function pat = modisAlbPat(S)
modalbpat = 'MCD43C3.A%s%s*.hdf';
pat = sprintf(modalbpat, S.ch_year_str,S.ch_day_str);
end
function ch_path = omiPathBuilder(sat_dir,ch_year_str,ch_month_str)
ch_path = fullfile(sat_dir,ch_year_str,ch_month_str);
end
function ch_path = modisPathBuilder(sat_dir,ch_year_str,~)
% Because the OMI data is stored by month, and since this function is
% passed to the checkDaily function, it needs 3 arguments even though
% we don't use the month for modis.
ch_path = fullfile(sat_dir,ch_year_str);
end
function chk = omiDataCheck(FILES)
% Check that there are at least 13 files for the given day.
% If so, mark it as complete. If there are some, but not 13,
% mark it as incomplete. If there are none, mark it as missing.
req_num_files = 13;
nF = numel(FILES);
if nF >= req_num_files
chk = 2;
elseif nF > 0 && nF < req_num_files
chk = 1;
else
chk = 0;
end
end
function chk = modisCloudDataCheck(FILES)
% Check that the expected MODIS MYD06 granules are present.
% You can look at their borders using draw_modis_cloud_swaths
% (in BEHR/One-off scripts currently)
% First check that there are any files are given, if not, clearly
% this is a "missing" day
if numel(FILES)==0
chk = 0;
return;
end
% Define the expected times manually. These will need to be expanded
% if BEHR is extended beyond CONUS. This should be organized so that
% each cell of expected_times contains another cell array that has
% vectors of times for each orbit. You can figure these out by looking
% at the MODIS granules using draw_modis_cloud_swaths in BEHR/One off
% scripts. You're looking for which granules (by the time identifier)
% are needed to cover the area of interest.
expected_times = cell(1,16);
expected_times{1} = {[1745, 1750], [1925, 1930], [2100, 2105, 2110]};
expected_times{2} = {[1655], [1825, 1830, 1835], [2005, 2010, 2015], [2145, 2150]};
expected_times{3} = {[1735, 1740], [1910, 1915], [2050, 2055]};
expected_times{4} = {[1815, 1820], [1955, 2000], [2130, 2135, 2140]};
expected_times{5} = {[1720, 1725], [1855, 1900, 1905], [2035, 2040, 2045]};
expected_times{6} = {[1630], [1800, 1805, 1810], [1940, 1945, 1950], [2120, 2125]};
expected_times{7} = {[1710, 1715], [1845, 1850, 1855], [2025, 2030], [2205, 2210]};
expected_times{8} = {[1750, 1755], [1930, 1935], [2105, 2110, 2115]};
expected_times{9} = {[1700], [1835, 1840], [2010, 2015, 2020], [2150, 2155]};
expected_times{10} = {[1740, 1745], [1915, 1920, 1925], [2055, 2100]};
expected_times{11} = {[1650], [1820, 1825, 1830], [2000, 2005], [2140, 2145]};
expected_times{12} = {[1725, 1730], [1905, 1910], [2045, 2050], [2220, 2225, 2230]};
expected_times{13} = {[1810, 1815], [1945, 1950, 1955], [2125, 2130]};
expected_times{14} = {[1715, 1720], [1850, 1855, 1900], [2030, 2035], [2210, 2215]};
expected_times{15} = {[1625], [1755, 1800, 1805], [1935, 1940], [2115, 2120]};
expected_times{16} = {[1705], [1840, 1845], [2020, 2025], [2155, 2200, 2205]};
% Make a list of times in the file names. Look for four numbers with .'s on either side.
times_list = zeros(1,numel(FILES));
for a=1:numel(FILES)
t_ind = regexp(FILES(a).name,'\.\d\d\d\d\.');
times_list(a) = str2num(FILES(a).name(t_ind+1:t_ind+4));
end
% Check how many of the times are present in the files. Since
% the Aqua satellite is on a 16-day repeat cycle, the mod16
% of the datenum can be used to indicate which set of times to use.
% Add one to that since MATLAB indexing doesn't start at 0.
year = FILES(1).name(11:14);
doy = FILES(1).name(15:17);
file_date = modis_day_to_date(doy,year);
mod_ind = mod(datenum(file_date),16);
test_times = expected_times{mod_ind+1};
cnt = 0;
tot = 0;
for t=1:numel(test_times)
% Add a "buffer" granule to the beginning and end of the swath
test_times_t = [timemath(test_times{t}(1),-5), test_times{t}, timemath(test_times{t}(end),5)];
% Keep track of how many granules we expect in each orbit
n = numel(test_times{t});
tot = tot + n;
% Keep track of how many of the expected times are present
times_found = ismember(test_times_t, times_list);
cnt = cnt + sum(times_found);
end
% The status will be complete if there are as many files as expected,
% and they are about the right times. If there are too few, it is
% incomplete, and obviously if there are none, the day is missing.
if cnt >= tot
chk = 2;
elseif cnt < tot && cnt > 0
chk = 0;
else
chk = 1;
end
end
function t = timemath(t,m)
% Add minutes to time t where the hundreds and thousands place are hours
% and the tens and ones are minutes.
minutes = mod(t,100);
hours = t - minutes;
minutes = minutes + m;
% what must be added to the hour: >60 = add, <0 = subtract
h = floor(minutes/60);
new_minutes = mod(minutes,60);
new_hour = hours + h*100;
t = new_hour + new_minutes;
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
subset_behr_data_struct.m
|
.m
|
BEHR-core-utils-master/Utils/subset_behr_data_struct.m
| 4,444 |
utf_8
|
d3010edd21ee09249cac53b82d099f47
|
function Data = subset_behr_data_struct(Data, varargin)
% SUBSET_BEHR_DATA_STRUCT Subset fields of a BEHR data structure, keeping shape as much as possible
% DATA = SUBSET_BEHR_DATA_STRUCT(DATA, INDEX1, INDEX2, ...) Subsets the
% fields in DATA with INDEX1, INDEX2, etc. Each INDEX argument
% corresponds to one element in DATA, so if DATA is a scalar struct, only
% one INDEX argument is needed, if DATA is a 4x1 struct, four INDEX
% arguments are needed. Each index must be either a logical or linear
% index array for one of the 2D fields in DATA.
%
% Each field is subset according to the following rules:
% * A 2D field is directly indexed with the INDEX argument for its
% element of DATA.
%
% * A 1D field with along- or across- track dimensions is expanded
% into a 2D field before indexing with the 2D index array.
%
% * A 3D field
E = JLLErrors;
% First cut down the various 2-, and 3-D fields. There are both along- and
% across- track 1D fields, so handle them by replicating them into 2D
% matrices, and there are 3D fields where the first dimension is either 4
% (corners) or ~30 (scattering weights, etc).
if ~isstruct(Data)
E.badinput('DATA must be a structure')
end
if numel(varargin) ~= numel(Data)
E.badinput('Number of indexing arrays must match the number of elements in Data')
end
fns = fieldnames(Data);
for i_data = 1:numel(Data)
this_data = Data(i_data);
size_2d = size(this_data.Longitude);
if size_2d(1) == size_2d(2)
E.notimplemented('%s', 'Cannot handle an orbit with equal along- and across- track dimensions');
end
n_corners = size(this_data.FoV75CornerLongitude,1);
n_plevs = size(this_data.BEHRPressureLevels,1);
[xx_2d, xx_corners, xx_plevs] = format_input_indexing_array(size_2d, varargin{i_data}, n_corners, n_plevs, i_data);
leading_dim_size = zeros(size(fns));
for i_fn = 1:numel(fns)
if isvector(this_data.(fns{i_fn}))
% Assume that along-track only arrays are already column
% vectors and across-track only arrays
if numel(this_data.(fns{i_fn})) == size_2d(1)
this_data.(fns{i_fn}) = repmat(this_data.(fns{i_fn}),1,size_2d(2));
elseif numel(this_data.(fns{i_fn})) == size_2d(2)
this_data.(fns{i_fn}) = repmat(this_data.(fns{i_fn}),size_2d(1),1);
end
% If the 1D array does not match the along or across track
% dimension, do nothing.
elseif ndims(this_data.(fns{i_fn})) == 3
% 3D fields with a first dimension != corners or plevs will not
% be subset, so when they get reshaped at the end, they'll just
% end up being 2D with the last two dims rearranged into one.
leading_dim_size(i_fn) = size(this_data.(fns{i_fn}),1);
end
end
this_data = subset_struct_fields(this_data, xx_2d, xx_corners, xx_plevs);
for i_fn = 1:numel(fns)
% Reshape 3D fields so that their first dimension is the same as it
% was originally, but the next two dimensions are compressed to
% one.
if leading_dim_size(i_fn) > 0
this_data.(fns{i_fn}) = reshape(this_data.(fns{i_fn}), leading_dim_size(i_fn), []);
end
end
Data(i_data) = this_data;
end
end
function [xx, xx_corners, xx_plevs] = format_input_indexing_array(size_2d, input_index, n_corners, n_plevs, i_data)
% i_data just used to make the error messages more intelligent
E = JLLErrors;
if islogical(input_index)
if ~isequal(size(input_index), size_2d)
E.badinput('The %1$s input index is a different size than the 2D arrays in the %1$s element of Data', ordinal_string(i_data));
else
xx = input_index;
end
elseif isnumeric(input_index)
xx = false(size_2d);
xx(input_index) = true;
else
E.badinput('The %s input index is neither a logical nor numeric array', ordinal_string(i_data));
end
xx_corners = repmat(permute(xx,[3 1 2]),n_corners,1,1);
xx_plevs = repmat(permute(xx,[3 1 2]),n_plevs,1,1);
end
function s = ordinal_string(i)
% Return an ordinal number string. Make it so that e.g. 1 = 1st, 101 =
% 101st, 2 = 2nd, 102 = 102nd, etc.
if mod(abs(i),100) == 1
suffix = 'st';
elseif mod(abs(i),100) == 2
suffix = 'nd';
elseif mod(abs(i),100) == 3
suffix = 'rd';
else
suffix = 'th';
end
s = sprintf('%d%s',i,suffix);
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
m_proj.m
|
.m
|
BEHR-core-utils-master/Utils/m_map/m_proj.m
| 5,598 |
utf_8
|
08103651696dcffd4901c8f2575f210d
|
function m_proj(proj,varargin)
% M_PROJ Initializes map projections info, putting the result into a structure
%
% M_PROJ('get') tells you the current state
% M_PROJ('set') gives you a list of all possibilities
% M_PROJ('set','proj name') gives info about a projection in the
% 'get' list.
% M_PROJ('proj name','property',value,...) initializes a projection.
%
%
% see also M_GRID, M_LL2XY, M_XY2LL.
% Rich Pawlowicz ([email protected]) 2/Apr/1997
%
% This software is provided "as is" without warranty of any kind. But
% it's mine, so you can't sell it.
%
% 20/Sep/01 - Added support for other coordinate systems.
% 25/Feb/07 - Swapped "get" and "set" at lines 34 and 47
% to make it consistent with the help
% (and common Matlab style)
% - Added lines 62-70 & 74
% to harden against error when no proj is set
% (fixes thanks to Lars Barring)
global MAP_PROJECTION MAP_VAR_LIST MAP_COORDS
% Get all the projections
projections=m_getproj;
if nargin==0, proj='usage'; end;
proj=lower(proj);
switch proj,
case 'set', % Print out their names
if nargin==1,
disp(' ');
disp('Available projections are:');
for k=1:length(projections),
disp([' ' projections(k).name]);
end;
else
k=m_match(varargin{1},projections(:).name);
eval(['X=' projections(k).routine '(''set'',projections(k).name);']);
disp(X);
end;
case 'get', % Get the values of all set parameters
if nargin==1,
if isempty(MAP_PROJECTION),
disp('No map projection initialized');
m_proj('usage');
else
k=m_match(MAP_PROJECTION.name,projections(:).name);
eval(['X=' projections(k).routine '(''get'');']);
disp('Current mapping parameters -');
disp(X);
end;
else
if isempty(MAP_PROJECTION),
k=m_match(varargin{1},projections(:).name);
eval(['X=' projections(k).routine '(''set'',projections(k).name);']);
X=strvcat(X, ...
' ', ...
'**** No projection is currently defined ****', ...
['**** USE "m_proj(''' varargin{1} ''',<see options above>)" ****']);
disp(X);
else
k=m_match(varargin{1},projections(:).name);
eval(['X=' projections(k).routine '(''get'');']);
disp(X);
end;
end;
case 'usage',
disp(' ');
disp('Possible calling options are:');
disp(' ''usage'' - this list');
disp(' ''set'' - list of projections');
disp(' ''set'',''projection'' - list of properties for projection');
disp(' ''get'' - get current mapping parameters (if defined)');
disp(' ''projection'' <,properties> - initialize projection\n');
otherwise % If a valid name, give the usage.
k=m_match(proj,projections(:).name);
MAP_PROJECTION=projections(k);
eval([ projections(k).routine '(''initialize'',projections(k).name,varargin{:});']);
% With the projection store what coordinate system we are using to define it.
if isempty(MAP_COORDS),
m_coord('geographic');
end;
MAP_PROJECTION.coordsystem=MAP_COORDS;
end;
%---------------------------------------------------------
function projections=m_getproj;
% M_GETPROJ Gets a list of the different projection routines
% and returns a structure containing both their
% names and the formal name of the projection.
% (used by M_PROJ).
% Rich Pawlowicz ([email protected]) 9/May/1997
%
% 9/May/97 - fixed paths for Macs (thanks to Dave Enfield)
%
% 7/05/98 - VMS pathnames (thanks to Helmut Eggers)
% Get all the projections
lpath=which('m_proj');
fslashes=findstr(lpath,'/');
bslashes=findstr(lpath,'\');
colons=findstr(lpath,':');
closparantheses=findstr(lpath,']');
if ~isempty(fslashes),
lpath=[ lpath(1:max(fslashes)) 'private/'];
elseif ~isempty(bslashes),
lpath=[ lpath(1:max(bslashes)) 'private\'];
elseif ~isempty(closparantheses), % for VMS computers only, others don't use ']' in filenames
lpath=[ lpath(1:max(closparantheses)-1) '.private]'];
else,
lpath=[ lpath(1:max(colons)) 'private:'];
end;
w=dir([lpath 'mp_*.m']);
if isempty(w), % Not installed correctly
disp('**********************************************************');
disp('* ERROR - Can''t find anything in a /private subdirectory *');
disp('* m_map probably unzipped incorrectly - please *');
disp('* unpack again, preserving directory structure *');
disp('* *');
disp('* ...Abandoning m_proj now. *');
error('**********************************************************');
end;
l=1;
projections=[];
for k=1:length(w),
funname=w(k).name(1:(findstr(w(k).name,'.'))-1);
projections(l).routine=funname;
eval(['names= ' projections(l).routine '(''name'');']);
for m=1:length(names);
projections(l).routine=funname;
projections(l).name=names{m};
l=l+1;
end;
end;
%----------------------------------------------------------
function match=m_match(arg,varargin);
% M_MATCH Tries to match input string with possible options
% Rich Pawlowicz ([email protected]) 2/Apr/1997
match=strmatch(lower(arg),cellstr(lower(char(varargin))));
if length(match)>1,
error(['Projection ''' arg ''' not a unique specification']);
elseif isempty(match),
error(['Projection ''' arg ''' not recognized']);
end;
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
m_hatch.m
|
.m
|
BEHR-core-utils-master/Utils/m_map/m_hatch.m
| 8,674 |
utf_8
|
2c6e74cd312d1da0fdbb1287ec4cbe7a
|
function [xi,yi,x,y]=m_hatch(lon,lat,varargin);
% M_HATCH Draws hatched or speckled interiors to a patch
%
% M_HATCH(LON,LAT,STYL,ANGLE,STEP,...line parameters);
%
% INPUTS:
% X,Y - vectors of points.
% STYL - style of fill
% ANGLE,STEP - parameters for style
%
% E.g.
%
% 'single',45,5 - single cross-hatch, 45 degrees, 5 points apart
% 'cross',40,6 - double cross-hatch at 40 and 90+40, 6 points apart
% 'speckle',7,1 - speckled (inside) boundary of width 7 points, density 1
% (density >0, .1 dense 1 OK, 5 sparse)
% 'outspeckle',7,1 - speckled (outside) boundary of width 7 points, density 1
% (density >0, .1 dense 1 OK, 5 sparse)
%
%
% H=M_HATCH(...) returns handles to hatches/speckles.
%
% [XI,YI,X,Y]=MHATCH(...) does not draw lines - instead it returns
% vectors XI,YI of the hatch/speckle info, and X,Y of the original
% outline modified so the first point==last point (if necessary).
%
% Note that inside and outside speckling are done quite differently
% and 'outside' speckling on large coastlines can be very slow.
%
% If you get weird results - try putting an M_LINE(LON,LAT) call *before*
% (or otherwise set the plot axis xlim/ylim parameters - this is necessary
% because otherwise M_HATCH can't properly determine the 'points' units).
%
%
% Hatch Algorithm originally by K. Pankratov, with a bit stolen from
% Iram Weinsteins 'fancification'. Speckle modifications by R. Pawlowicz.
%
% R Pawlowicz ([email protected]) 15/Dec/2005
%
% This software is provided "as is" without warranty of any kind. But
% it's mine, so you can't sell it.
%
%% 4/DEc/11 - isstr to ischar
% Apr/12 - handle NaN-separated coastlines
styl='speckle';
angle=7;
step=1/2;
if length(varargin)>0 & ischar(varargin{1}),
styl=varargin{1};
varargin(1)=[];
end;
if length(varargin)>0 & ~ischar(varargin{1}),
angle=varargin{1};
varargin(1)=[];
end;
if length(varargin)>0 & ~ischar(varargin{1}),
step=varargin{1};
varargin(1)=[];
end;
% If we have a naN-separated multi-line input vector:
ii=find(isnan(lon));
if any(ii),
% if there isn't a NaN to mark the first or last segments
if ii(1)>1, ii=[1;ii(:)]; end;
if ii(end)<length(lon), ii=[ii(:);length(lon)]; end;
% Compute the info, but don't draw - otherwise we end up with
% lots of 'childred' to the plot and it is SLOWWWWW
xi=[];yi=[];x=[];y=[];
for k=1:length(ii)-1,
[xiT,yiT,xT,yT]=m_hatch(lon(ii(k)+1:ii(k+1)-1),lat(ii(k)+1:ii(k+1)-1),styl,angle,step,varargin{:});
xi=[xi,NaN,xiT];
yi=[yi,NaN,yiT];
x=[x,NaN,xT];
y=[y,NaN,yT];
end;
% OK, so now plot it all.
if nargout<2,
switch lower(styl),
case {'single','cross'},
xi=line(xi,yi,varargin{:});
case {'speckle','outspeckle'},
xi=line(xi,yi,'marker','.','linestyle','none','markersize',2,varargin{:});
end;
end;
return;
end;
%----------------------
% otherwise, handle a single line without NaN
[x,y,I]=m_ll2xy(lon,lat,'clip','patch');
%% plot(x,y,'color','r');%%pause;
if x(end)~=x(1) | y(end)~=y(1), % & to |
x=x([1:end 1]);
y=y([1:end 1]);
I=I([1:end 1]);
end;
if strcmp(styl,'speckle') | strcmp(styl,'outspeckle'),
angle=angle*(1-I);
end;
if size(x,1)~=1,
x=x(:)';
angle=angle(:)';
end;
if size(y,1)~=1,
y=y(:)';
end;
% Code stolen from Weinstein hatch
oldu = get(gca,'units');
set(gca,'units','points');
sza = get(gca,'position'); sza = sza(3:4);
set(gca,'units',oldu) % Set axes units back
xlim = get(gca,'xlim');
ylim = get(gca,'ylim');
xsc = sza(1)/(xlim(2)-xlim(1)+eps);
ysc = sza(2)/(ylim(2)-ylim(1)+eps);
switch lower(styl),
case 'single',
[xi,yi]=drawhatch(x,y,angle,step,xsc,ysc,0);
if nargout<2,
xi=line(xi,yi,varargin{:});
end;
case 'cross',
[xi,yi]=drawhatch(x,y,angle,step,xsc,ysc,0);
[xi2,yi2]=drawhatch(x,y,angle+90,step,xsc,ysc,0);
xi=[xi,xi2];
yi=[yi,yi2];
if nargout<2,
xi=line(xi,yi,varargin{:});
end;
case 'speckle',
[xi,yi ] =drawhatch(x,y,45, step,xsc,ysc,angle);
[xi2,yi2 ]=drawhatch(x,y,45+90,step,xsc,ysc,angle);
xi=[xi,xi2];
yi=[yi,yi2];
if nargout<2,
if any(xi),
xi=line(xi,yi,'marker','.','linestyle','none','markersize',2,varargin{:});
else
xi=NaN;yi=NaN;
end;
end;
case 'outspeckle',
[xi,yi ] =drawhatch(x,y,45, step,xsc,ysc,-angle);
[xi2,yi2 ]=drawhatch(x,y,45+90,step,xsc,ysc,-angle);
xi=[xi,xi2];
yi=[yi,yi2];
% disp([size(xi) size(yi)])
inside=logical(inpolygon(xi,yi,x,y)); % logical needed for v6!
xi(inside)=[];yi(inside)=[];
if nargout<2,
if any(xi),
xi=line(xi,yi,'marker','.','linestyle','none','markersize',2,varargin{:});
else
xi=NaN;yi=NaN;
end;
end;
end;
return
%%%%%
function [xi,yi]=drawhatch(x,y,angle,step,xsc,ysc,speckle);
%
% This is the guts.
%
angle=angle*pi/180;
% Idea here appears to be to rotate everthing so lines will be
% horizontal, and scaled so we go in integer steps in 'y' with
% 'points' being the units in x.
% Center it for "good behavior".
ca = cos(angle); sa = sin(angle);
x0 = mean(x); y0 = mean(y);
x = (x-x0)*xsc; y = (y-y0)*ysc;
yi = x*ca+y*sa; % Rotation
y = -x*sa+y*ca;
x = yi;
y = y/step; % Make steps equal to one
% Compute the coordinates of the hatch line ...............
yi = ceil(y);
yd = [diff(yi) 0]; % when diff~=0 we are crossing an integer
fnd = find(yd); % indices of crossings
dm = max(abs(yd)); % max possible #of integers between points
%
% This is going to be pretty space-inefficient if the line segments
% going in have very different lengths. We have one column per line
% interval and one row per hatch line within that interval.
%
A = cumsum( repmat(sign(yd(fnd)),dm,1), 1);
% Here we interpolate points along all the line segments at the
% correct intervals.
fnd1 = find(abs(A)<=abs( repmat(yd(fnd),dm,1) ));
A = A+repmat(yi(fnd),dm,1)-(A>0);
xy = (x(fnd+1)-x(fnd))./(y(fnd+1)-y(fnd));
xi = repmat(x(fnd),dm,1)+(A-repmat(y(fnd),dm,1) ).*repmat(xy,dm,1);
yi = A(fnd1);
xi = xi(fnd1);
% Sorting points of the hatch line ........................
%%%yi0 = min(yi); yi1 = max(yi);
% Sort them in raster order (i.e. by x, then by y)
% Add '2' to make sure we don't have problems going from a max(xi)
% to a min(xi) on the next line (yi incremented by one)
if length(xi)>0,
xi0 = min(xi); xi1 = max(xi);
ci = 2*yi*(xi1-xi0)+xi;
[ci,num] = sort(ci);
xi = xi(num); yi = yi(num);
else
xi=NaN;yi=NaN;
return;
end;
% if this happens an error has occurred somewhere (we have an odd
% # of points), and the "fix" is not correct, but for speckling anyway
% it really doesn't make a difference.
if rem(length(xi),2)==1,
disp('mhatch warning');
xi = [xi; xi(end)];
yi = [yi; yi(end)];
end
% Organize to pairs and separate by NaN's ................
li = length(xi);
xi = reshape(xi,2,li/2);
yi = reshape(yi,2,li/2);
% The speckly part - instead of taking the line we make a point some
% random distance in.
if length(speckle)>1 | speckle(1)~=0,
if length(speckle)>1,
% Now we get the speckle parameter for each line.
% First, carry over the speckle parameter for the segment
% yd=[0 speckle(1:end-1)];
yd=[speckle(1:end)];
A=repmat(yd(fnd),dm,1);
speckle=A(fnd1);
% Now give it the same preconditioning as for xi/yi
speckle=speckle(num);
if rem(length(speckle),2)==1,
speckle = [speckle; speckle(end)];
end
speckle=reshape(speckle,2,li/2);
else
speckle=[speckle;speckle];
end;
% Thin out the points in narrow parts.
% This keeps everything when abs(dxi)>2*speckle, and then makes
% it increasingly sparse for smaller intervals.
oldxi=xi;oldyi=yi;
dxi=diff(xi);
nottoosmall=sum(speckle,1)~=0 & rand(1,li/2)<abs(dxi)./(max(sum(speckle,1),eps));
xi=xi(:,nottoosmall);
yi=yi(:,nottoosmall);
dxi=dxi(nottoosmall);
if size(speckle,2)>1, speckle=speckle(:,nottoosmall); end;
% Now randomly scatter points (if there any left)
li=length(dxi);
if any(li),
xi(1,:)=xi(1,:)+sign(dxi).*(1-rand(1,li).^0.5).*min(speckle(1,:),abs(dxi) );
xi(2,:)=xi(2,:)-sign(dxi).*(1-rand(1,li).^0.5).*min(speckle(2,:),abs(dxi) );
% Remove the 'zero' speckles
if size(speckle,2)>1,
xi=xi(speckle~=0);
yi=yi(speckle~=0);
end;
end;
else
xi = [xi; ones(1,li/2)*nan]; % Separate the line segments
yi = [yi; ones(1,li/2)*nan];
end;
xi = xi(:)'; yi = yi(:)';
% Transform back to the original coordinate system
yi = yi*step;
xy = xi*ca-yi*sa;
yi = xi*sa+yi*ca;
xi = xy/xsc+x0;
yi = yi/ysc+y0;
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
m_grid.m
|
.m
|
BEHR-core-utils-master/Utils/m_map/m_grid.m
| 27,478 |
utf_8
|
c3b2dec8e52e76f44663d1945ae83fe4
|
function m_grid(varargin);
% M_GRID make a grid on a map.
% M_GRID('parameter','value',...) with any number (or no)
% optional parameters is used to draw a lat/long grid for a
% previously initialized map projection.
%
% The optional parameters allow the user
% to control the look of the grid. These parameters are listed
% by M_GRID('get'), with defualt parameters in M_GRID('set');
%
% see also M_PROJ
% Rich Pawlowicz ([email protected]) 2/Apr/1997
%
% This software is provided "as is" without warranty of any kind. But
% it's mine, so you can't sell it.
%
% 19/6/97 - set visibility of titles and so forth to 'on' (they
% default to 'off' when axes visibility is turned off)
% 2/11/97 - for M5.1, the old way of making the patch at the bottom (i.e.
% by rearranging the axes children) instead causes matlab to lose
% track of titles. Try a different fix.
% 11/01/98 - Added way of making longitude lines cut off to prevent crowding near poles (you have
% to specify a vector for allowabale latitudes for this to work).
% 16/02/98 - Made a little fudge to allow the user to fully specify grid location
% without getting the edge points. It doesn't quite work if only *one* edge
% point is desired....but I hope it will be OK that way.
% 19/02/98 - PC-users complain about layers getting out of order! Their fault for using
% such an awful OS...however (with help from Eric Firing) I think I have
% a fix.
% 7/04/98 - Another fix to grid locations to not automatically add edge points
% (as requested by EF)
% 7/05/98 - Added 'fancy' outline box.
% 14/11/98 - Changed tag names from m_* to m_grid_*.
% 11/07/99 - Apparently fontname changing didn't work (thanks to Dave McCollum)
% 28/04/04 - Changed m_grid_color code so it works right under unix; old
% way retained for windows (ugh).
% 16/10/05 - Kirk Ireson discovered that the way to fix those annoying 'cut-throughs'
% in fancy_box was to add a 'large' zdata...so I've adapted his fix in
% fancybox and fancybox2.
% 21/11/06 - added 'backcolor'
% 16/4/07 - sorted ticklabels when user-specified (prevents an odd problem near in
% azimuthal projections).
% 4/DEc/11 - isstr to ischar
% 7/Dec/11 - Octave 3.2.3 compatibility
% 8/Sep/13 - added 'tickstyle' parameter
% 27/Sep/13 - matlab 2013b out, includes graphic bug. Workaround provided by
% Corinne Bassin.
% Note that much of the work in generating line data
% is done by calls to the individual projections -
% most of M_GRID is concerned with the mechanics of plotting
% These structures are initialized by m_proj()
global MAP_PROJECTION MAP_VAR_LIST
% Have to have initialized a map first
if isempty(MAP_PROJECTION),
disp('No Map Projection initialized - call M_PROJ first!');
return;
end;
% Recognize Octave
a=ver;
if strcmp(a(1).Name,'Octave'),
IsOctave=logical(1);
else
IsOctave=logical(0);
end;
% Otherwise we are drawing a grid!
% Set current projection to geographic
Currentmap=m_coord('set');
m_coord(MAP_PROJECTION.coordsystem.name);
% Default parameters for grid
xtick=6;
ytick=6;
xlabels=NaN;
ylabels=NaN;
gcolor='k';
gbackcolor='w'; %%get(gcf,'color');
glinestyle=':';
glinewidth=get(gca,'linewidth');
gbox='on';
gfontsize=get(gca,'fontsize');
gfontname=get(gca,'fontname');
gxaxisloc=get(gca,'xaxislocation');
gyaxisloc=get(gca,'yaxislocation');
gtickdir=get(gca,'tickdir');
gticklen=get(gca,'ticklength'); gticklen=gticklen(1);
gxticklabeldir='middle';
gyticklabeldir='end';
gtickstyle='dm';
dpatch=5; % interpolation factor for fancy grids
% Parse parameter list for options. I really should do some
% error checking here, but...
k=1;
while k<=length(varargin),
switch lower(varargin{k}(1:3)),
case 'box',
gbox=varargin{k+1};
case 'xti',
if length(varargin{k})==5,
xtick=sort(varargin{k+1}); % Added 'sort' here for people who put things in
else % a random order near poles
xlabels=varargin{k+1};
end;
case 'yti',
if length(varargin{k})==5,
ytick=sort(varargin{k+1});
else
ylabels=varargin{k+1};
end;
case 'xla',
gxticklabeldir=varargin{k+1};
case 'yla',
gyticklabeldir=varargin{k+1};
case 'col',
gcolor=varargin{k+1};
case 'bac',
gbackcolor=varargin{k+1};
case 'lin',
switch lower(varargin{k}(1:5)),
case 'linew',
glinewidth=varargin{k+1};
case 'lines',
glinestyle=varargin{k+1};
end;
case 'fon',
switch lower(varargin{k}(1:5)),
case 'fonts',
gfontsize=varargin{k+1};
case 'fontn',
gfontname=varargin{k+1};
end;
case 'xax',
gxaxisloc=varargin{k+1};
case 'yax',
gyaxisloc=varargin{k+1};
case 'tic',
switch lower(varargin{k}(1:5)),
case 'tickl',
gticklen=varargin{k+1};
case 'tickd',
gtickdir=varargin{k+1};
case 'ticks',
gtickstyle=varargin{k+1};
end;
case {'get','usa'},
disp(' ''box'',( ''on'' | ''fancy'' | ''off'' )');
disp(' ''xtick'',( num | [value1 value2 ...])');
disp(' ''ytick'',( num | [value1 value2 ...])');
disp(' ''xticklabels'',[label1;label2 ...]');
disp(' ''yticklabels'',[label1;label2 ...]');
disp(' ''xlabeldir'', ( ''middle'' | ''end'' )');
disp(' ''ylabeldir'', ( ''end'' | ''middle'' )');
disp(' ''ticklength'',value');
disp(' ''tickdir'',( ''in'' | ''out'' )');
disp(' ''tickstyle'',(''dm'' | ''dd'' )'); % deg-min or decimal-deg
disp(' ''color'',colorspec');
disp(' ''backcolor'',colorspec');
disp(' ''linewidth'', value');
disp(' ''linestyle'', ( linespec | ''none'' )');
disp(' ''fontsize'',value');
disp(' ''fontname'',name');
disp(' ''XaxisLocation'',( ''bottom'' | ''middle'' | ''top'' ) ');
disp(' ''YaxisLocation'',( ''left'' | ''middle'' | ''right'' ) ');
return;
case 'set',
disp([' box = ' gbox]);
disp([' xtick = ' num2str(xtick)]);
disp([' ytick = ' num2str(ytick)]);
disp([' ticklength = ' num2str(gticklen)]);
disp([' tickdir = ' gtickdir]);
disp([' tickstyle = ' gtickstyle]);
disp([' xlabeldir = ' gxticklabeldir]);
disp([' ylabeldir = ' gyticklabeldir]);
disp([' color = ' gcolor]);
disp([' linewidth = ' num2str(glinewidth)]);
disp([' linestyle = ' glinestyle]);
disp([' fontsize = ' num2str(gfontsize)]);
disp([' fontname = ' gfontname]);
disp([' XaxisLocation = ' gxaxisloc]);
disp([' YaxisLocation = ' gyaxisloc]);
return;
end;
k=k+2;
end;
if IsOctave & strcmp(gbox,'fancy'),
warning('No fancy box outlines with Octave');
gbox='on';
end;
if strcmp(gbox,'fancy'),
if strcmp(MAP_VAR_LIST.rectbox,'on') | strcmp(MAP_VAR_LIST.rectbox,'circle'),
gbox='on';
warning([' No fancy outline with ''rectbox'' set to ''' MAP_VAR_LIST.rectbox '''']);
end;
end;
% Draw the plot box
[X,Y]=feval(MAP_PROJECTION.routine,'box');
if strcmp(gbox,'on');
line(X(:),Y(:),'linestyle','-','linewidth',glinewidth,'color',gcolor,'tag','m_grid_box','clipping','off');
end;
% Axes background - to defeat the inverthardcopy, I need a non-white border (the edgecolor),
% but sneakily I can set it's width to (effectively) 0 so it doesn't actually show!
if ~IsOctave,
% This is a very problematic part of the code. It turns out the the interaction between
% PATCH objects and CONTOURF objects does not work correctly in the Painters renderer -
% this is true in all versions up to 7.7 at least. Patches with large negative Z just
% don't get drawn under contourgroup patches.
%
% There are several possible workarounds:
%
% 1) Make sure you use the 'v6' option in contourf calls (see m_contourf.m to see
% how I have tried to do that for some versions of matlab)
% - problem: the 'v6' option is going away soon, also you may want the
% contourgroup object that the v6 option destroys.
%
% 2) Change the renderer to something else:
% set(gcf,'renderer','opengl') or
% set(gcf,'renderer','zbuffer')
% - problem: These other renderers are not available on all systems, they may also
% give less-precise results.
%
% 3) Use the painters renderer, but reorder the children so that the patch is at the
% bottom of the list (painters cares about child order)
% - problem: sometimes the child order is rearranged if you click on the figure,
% also (at least in some versions of matlab) this causes labels to
% disappear.
%
% With version 7.4 onwards I have discovered that reordering the children apparently
% is Mathworks-blessed (c.f. the UISTACK function). So I am going to try to implement
% the latter as a default.
% Now, putting in a white background works under linux (at least) and
% NOT under windows...I don't know about macs.
%%a=ver('matlab'); % Ver doesn't return stuff under v5!
a=version;
%if (sscanf(a(1:3),'%f') >6.0 & sscanf(a(1:3),'%f') <7.4) & ~ispc,
patch('xdata',X(:),'ydata',Y(:),'zdata',-flintmax*ones(size(X(:))),'facecolor',gbackcolor,...
'edgecolor','k','linestyle','none','tag','m_grid_color');
%
%else
% Now, I used to set this at a large (negative) zdata, but this didn't work for PC users,
% so now I just draw a patch...but I have decided to go back to the old
% way (above) with higher versions. Maybe the PC version works now?
% Unfortunately this kludge has some strange side-effects.
% patch('xdata',X(:),'ydata',Y(:),'zdata',-bitmax*ones(size(X(:))),'facecolor',gbackcolor,...
% 'edgecolor','k','linestyle','none','tag','m_grid_color');
% patch('xdata',X(:),'ydata',Y(:),'facecolor',gbackcolor,...
% 'edgecolor','k','linestyle','none','tag','m_grid_color');
% Now I set it at the bottom of the children list so it gets drawn first (i.e. doesn't
% cover anything)
show=get(0, 'ShowHiddenHandles');
set(0, 'ShowHiddenHandles', 'on');
hh=get(gca,'children');
htags = get(hh,'tag');
k = strmatch('m_grid_color',htags);
hht = hh;
hh(k) = [];
hh = [hh;hht(k)];
set(gca,'children',hh);
set(0, 'ShowHiddenHandles', show);
end;
% X-axis labels and grid
if ~isempty(xtick),
% Tricky thing - if we are drawing a map with the poles, its nasty when the lines get too close
% together. So we can sort of fudge this by altering MAP_VAR_LIST.lats to be slightly smaller,
% and then changing it back again later.
fudge_north='n';fudge_south='n';
if ~isempty(ytick) & length(ytick)>1,
if MAP_VAR_LIST.lats(2)==90,
fudge_north='y';
MAP_VAR_LIST.lats(2)=ytick(end);
end;
if MAP_VAR_LIST.lats(1)==-90,
fudge_south='y';
MAP_VAR_LIST.lats(1)=ytick(1);
end;
end;
[X,Y,lg,lgI]=feval(MAP_PROJECTION.routine,'xgrid',xtick,gxaxisloc,gtickstyle);
[labs,scl]=m_labels('lon',lg,xlabels,gtickstyle);
% Draw the grid. Every time we draw something, I first reshape the matrices into a long
% row so that a) it plots faster, and b) all lines are given the same handle (which cuts
% down on the number of children hanging onto the axes).
[n,m]=size(X);
line(reshape([X;NaN+ones(1,m)],(n+1)*m,1),reshape([Y;NaN+ones(1,m)],(n+1)*m,1),...
'linestyle',glinestyle,'color',gcolor,'linewidth',0.1,'tag','m_grid_xgrid');
% Get the tick data
[ltx,lty,utx,uty]=maketicks(X,Y,gticklen,gtickdir);
% Draw ticks if labels are on top or bottom (not if they are in the middle)
if strcmp(gxticklabeldir,'middle'),
if lgI==size(X,1) & strcmp(gxaxisloc,'top'), % Check to see if the projection supports this option.
vert='bottom';horiz='center';drawticks=1;
xx=utx(1,:);yy=uty(1,:);rotang=atan2(diff(uty),diff(utx))*180/pi+90;
elseif lgI==1 & strcmp(gxaxisloc,'bottom')
vert='top';horiz='center';drawticks=1;
xx=ltx(1,:);yy=lty(1,:);rotang=atan2(diff(lty),diff(ltx))*180/pi-90;
else
vert='middle';horiz='center';lgIp1=lgI+1;drawticks=0;
xx=X(lgI,:); yy=Y(lgI,:);rotang=atan2(Y(lgIp1,:)-Y(lgI,:),X(lgIp1,:)-X(lgI,:))*180/pi-90;
end;
else
if lgI==size(X,1) & strcmp(gxaxisloc,'top'), % Check to see if the projection supports this option.
vert='middle';horiz='left';drawticks=1;
xx=utx(1,:);yy=uty(1,:);rotang=atan2(diff(uty),diff(utx))*180/pi+180;
elseif lgI==1 & strcmp(gxaxisloc,'bottom')
vert='middle';;horiz='right';drawticks=1;
xx=ltx(1,:);yy=lty(1,:);rotang=atan2(diff(lty),diff(ltx))*180/pi;
else
vert='top';;horiz='center';lgIp1=lgI+1;drawticks=0;
xx=X(lgI,:); yy=Y(lgI,:);rotang=atan2(Y(lgIp1,:)-Y(lgI,:),X(lgIp1,:)-X(lgI,:))*180/pi;
end;
end;
if strcmp(gbox,'fancy'),
if gtickdir(1)=='i',
fancybox(lg,MAP_VAR_LIST.longs,'xgrid','bottom',dpatch,gticklen,gtickstyle);
drawticks=0;
else
fancybox2(lg,MAP_VAR_LIST.longs,'xgrid','bottom',dpatch,gticklen,gtickstyle);
end;
end;
if drawticks,
[n,m]=size(ltx);
line(reshape([ltx;NaN+ones(1,m)],(n+1)*m,1),reshape([lty;NaN+ones(1,m)],(n+1)*m,1),...
'linestyle','-','color',gcolor,'linewidth',glinewidth,'tag','m_grid_xticks-lower','clipping','off');
line(reshape([utx;NaN+ones(1,m)],(n+1)*m,1),reshape([uty;NaN+ones(1,m)],(n+1)*m,1),...
'linestyle','-','color',gcolor,'linewidth',glinewidth,'tag','m_grid_xticks-upper','clipping','off');
end;
% Add the labels! (whew)
ik=1:size(X,2);
for k=ik,
[rotang(k), horizk, vertk] = upright(rotang(k), horiz, vert);
text(xx(k),yy(k),labs{k},'horizontalalignment',horizk,'verticalalignment',vertk, ...
'rotation',rotang(k),'fontsize',gfontsize*scl(k),'color',gcolor,...
'tag','m_grid_xticklabel','fontname',gfontname);
end;
if fudge_north=='y',
MAP_VAR_LIST.lats(2)=90;
end;
if fudge_south=='y',
MAP_VAR_LIST.lats(1)=-90;
end;
end;
if ~isempty(ytick),
% Y-axis labels and grid
[X,Y,lt,ltI]=feval(MAP_PROJECTION.routine,'ygrid',ytick,gyaxisloc,gtickstyle);
[labs,scl]=m_labels('lat',lt,ylabels,gtickstyle);
% Draw the grid
[n,m]=size(X);
line(reshape([X;NaN+ones(1,m)],(n+1)*m,1),reshape([Y;NaN+ones(1,m)],(n+1)*m,1),...
'linestyle',glinestyle,'color',gcolor,'linewidth',0.1,'tag','m_grid_ygrid');
% Get the tick data
[ltx,lty,utx,uty]=maketicks(X,Y,gticklen,gtickdir);
% Draw ticks if labels are on left or right (not if they are in the middle)
if strcmp(gyticklabeldir,'end'),
if ltI==size(X,1) & strcmp(gyaxisloc,'right'), % Check to see if the projection supports this option.
horiz='left';vert='middle';drawticks=1;
xx=utx(1,:);yy=uty(1,:);rotang=atan2(diff(uty),diff(utx))*180/pi+180;
elseif ltI==1 & strcmp(gyaxisloc,'left');
horiz='right';vert='middle';drawticks=1;
xx=ltx(1,:);yy=lty(1,:);rotang=atan2(diff(lty),diff(ltx))*180/pi;
else
horiz='center';vert='top';ltIp1=ltI+1;drawticks=0;
xx=X(ltI,:); yy=Y(ltI,:);rotang=atan2(Y(ltIp1,:)-Y(ltI,:),X(ltIp1,:)-X(ltI,:))*180/pi;
end;
else
if ltI==size(X,1) & strcmp(gyaxisloc,'right'), % Check to see if the projection supports this option.
horiz='center';vert='top';drawticks=1;
xx=utx(1,:);yy=uty(1,:);rotang=atan2(diff(uty),diff(utx))*180/pi+270;
elseif ltI==1 & strcmp(gyaxisloc,'left');
horiz='center';vert='bottom';drawticks=1;
xx=ltx(1,:);yy=lty(1,:);rotang=atan2(diff(lty),diff(ltx))*180/pi+90;
else
horiz='left';vert='middle';ltIp1=ltI+1;drawticks=0;
xx=X(ltI,:); yy=Y(ltI,:);rotang=atan2(Y(ltIp1,:)-Y(ltI,:),X(ltIp1,:)-X(ltI,:))*180/pi+90;
end;
end;
if strcmp(gbox,'fancy'),
if gtickdir(1)=='i',
fancybox(lt,MAP_VAR_LIST.lats,'ygrid','left',dpatch,gticklen,gtickstyle);
drawticks=0;
else
fancybox2(lt,MAP_VAR_LIST.lats,'ygrid','left',dpatch,gticklen,gtickstyle);
end;
end;
if drawticks,
[n,m]=size(ltx);
line(reshape([ltx;NaN+ones(1,m)],(n+1)*m,1),reshape([lty;NaN+ones(1,m)],(n+1)*m,1),...
'linestyle','-','color',gcolor,'linewidth',glinewidth,'tag','m_grid_yticks-left','clipping','off');
line(reshape([utx;NaN+ones(1,m)],(n+1)*m,1),reshape([uty;NaN+ones(1,m)],(n+1)*m,1),...
'linestyle','-','color',gcolor,'linewidth',glinewidth,'tag','m_grid_yticks-right','clipping','off');
end;
% Finally - the labels!
ik=1:size(X,2);
for k=ik,
[rotang(k), horizk, vertk] = upright(rotang(k), horiz, vert);
text(xx(k),yy(k),labs{k},'horizontalalignment',horizk,'verticalalignment',vertk,...
'rotation',rotang(k),'fontsize',gfontsize*scl(k),'color',gcolor,...
'tag','m_grid_yticklabel','fontname',gfontname);
end;
end;
% Give a 1-1 aspect ratio and get rid of the matlab-provided axes stuff.
if isempty(strfind(version,'R2013b')), % 27/Sept/13 - Handling for 2013b provided by CB.
set(gca,'visible','off',...
'dataaspectratio',[1 1 1],...
'xlim',MAP_VAR_LIST.xlims,...
'ylim',MAP_VAR_LIST.ylims);
else
set(gca,'visible','off',...
'dataaspectratio',[1 1 1e16],...
'xlim',MAP_VAR_LIST.xlims,...
'ylim',MAP_VAR_LIST.ylims);
end
set(get(gca,'title'),'visible','on');
set(get(gca,'xlabel'),'visible','on');
set(get(gca,'ylabel'),'visible','on');
% Set coordinate system back
m_coord(Currentmap.name);
%-------------------------------------------------------------
% upright simply turns tick labels right-side up while leaving
% their positions unchanged.
% Sat 98/02/21 Eric Firing
%
function [rotang, horiz, vert] = upright(rotang, horiz, vert);
if rotang > 180, rotang = rotang - 360; end
if rotang < -180, rotang = rotang + 360; end
if rotang > 90,
rotang = rotang - 180;
elseif rotang < -90,
rotang = 180 + rotang;
else
return % no change needed.
end
switch horiz(1)
case 'l'
horiz = 'right';
case 'r'
horiz = 'left';
end
switch vert(1)
case 't'
vert = 'bottom';
case 'b'
vert = 'top';
end
%--------------------------------------------------------------------------
function [L,fs]=m_labels(dir,vals,uservals,tickstyle);
% M_LONLABEL creates longitude labels
% Default values are calculated automatically when the grid is
% generated. However, the user may wish to specify the labels
% as either numeric values or as strings (in the usual way
% for axes).
%
% If auto-labelling occurs, minutes are labelled in a different
% (smaller) fontsize than even degrees.
% Rich Pawlowicz ([email protected]) 2/Apr/1997
% If the user has specified [] (i.e. no labels), we return blanks.
if isempty(uservals),
L=cellstr(char(' '*ones(length(vals),1)));
fs=1.0*ones(length(L),1);
return;
end;
% If the user has specified strings, we merely need to make
% sure that there are enough to cover all ticks.
if any(ischar(uservals)),
L=cellstr( uservals((rem([0:length(vals)-1],length(uservals))+1),:) );
fs=1.0*ones(length(L),1);
return;
end;
% Otherwise we are going to have to generate labels from numeric
% data.
if length(uservals)==1 & isnan(uservals), % use default values
vals=vals(:)'; % make it a row.
else % or ones provided
lv=length(vals);
vals=uservals(:)';
while length(vals)<lv,
vals=[vals uservals(:)'];
end;
end;
% longitudes and latitudes have some differences....
if findstr(dir,'lat'),
labname=['S';'N';' '];
else
labname=['W';'E';' '];
vals=rem(vals+540,360)-180;
end;
i=[vals<0;vals>0;vals==0]; % get the 'names' (i.e. N/S or E/W)
vals=abs(vals); % Convert to +ve values
L=cell(length(vals),1);
fs=ones(length(vals),1);
if strcmp(tickstyle,'dm'),
% For each label we have different options:
% 1 - even degrees are just labelled as such.
% 2 - ticks that fall on even minutes are just labelled as even minutes
% in a smaller fontsize.
% 3 - fractional minutes are labelled to 2 decimal places in the
% smaller fontsize.
for k=1:length(vals),
if rem(vals(k),1)==0,
nam=find(i(:,k));
L{k}=sprintf([' %3.0f^o' labname(nam) ' '],vals(k));
elseif abs(vals*60-round(vals*60))<.01,
L{k}=sprintf([' %2.0f'' '],rem(vals(k),1)*60);
fs(k)=0.75;
else
L{k}=sprintf([' %2.2f'' '],rem(vals(k),1)*60);
fs(k)=0.75;
end;
end;
% In most cases, the map will have at least one tick with an even degree label,
% but for very small regions (<1 degree in size) this won't happen so we
% want to force one label to show degrees *and* minutes.
if ~any(fs==1),
k=round(length(vals)/2);
nam=find(i(:,k));
L{k}={sprintf([' %3.0f^o' labname(nam) ' '],fix(vals(k))),...
sprintf([' %2.2f'' '],rem(vals(k),1)*60)};
fs(k)=1;
end;
elseif strcmp(tickstyle,'dd'),
% For each label we have different options:
% 1 - even degrees are just labelled as such.
% 2 - 2 decimal place intervals use 2 decimal places
% 3 - the rest fo to 4
for k=1:length(vals),
if rem(vals(k),1)==0,
nam=find(i(:,k));
L{k}=sprintf([' %3.0f^o' labname(nam) ' '],vals(k));
elseif abs(vals*100-round(vals*100))<0.01,
L{k}=sprintf([' %2.2f'],vals(k));
fs(k)=0.75;
else
L{k}=sprintf([' %6.4f'],vals(k));
fs(k)=0.75;
end;
end;
% write code.
end;
%---------------------------------------------------------
function [ltx,lty,utx,uty]=maketicks(X,Y,gticklen,gtickdir);
% MAKETICKS makes the axis ticks.
% AXes ticks are based on making short lines at
% the end of the grid lines X,Y.
% Rich Pawlowicz ([email protected]) 2/Apr/1997
global MAP_VAR_LIST
tlen=gticklen*max( diff(MAP_VAR_LIST.xlims),diff(MAP_VAR_LIST.ylims));
lx=sqrt((X(2,:)-X(1,:)).^2+(Y(2,:)-Y(1,:)).^2);
if strcmp(gtickdir,'out'),
ltx=[X(1,:)-tlen*(X(2,:)-X(1,:))./lx;X(1,:)];
lty=[Y(1,:)-tlen*(Y(2,:)-Y(1,:))./lx;Y(1,:)];
else
ltx=[X(1,:);X(1,:)+tlen*(X(2,:)-X(1,:))./lx];
lty=[Y(1,:);Y(1,:)+tlen*(Y(2,:)-Y(1,:))./lx];
end;
lx=sqrt((X(end,:)-X(end-1,:)).^2+(Y(end,:)-Y(end-1,:)).^2);
if strcmp(gtickdir,'out'),
utx=[X(end,:)-tlen*(X(end-1,:)-X(end,:))./lx;X(end,:)];
uty=[Y(end,:)-tlen*(Y(end-1,:)-Y(end,:))./lx;Y(end,:)];
else
utx=[X(end,:);X(end,:)+tlen*(X(end-1,:)-X(end,:))./lx];
uty=[Y(end,:);Y(end,:)+tlen*(Y(end-1,:)-Y(end,:))./lx];
end;
%---------------------------------------------------------
function fancybox(vals,lims,gridarg1,gridarg2,dpatch,gticklen,gridarg3);
%
% FANCYBOX - draws fancy outlines for either top/bottom or left/right sides,
% depending on calling parameters.
global MAP_PROJECTION
% Get xlocations including endpoints
xval=sort([lims(1) vals(vals>lims(1) & vals<lims(2)) lims(2)]);
% Add all half-way points as well.
xval=sort([xval,xval(1:end-1)+diff(xval)/2]);
% Interpolate extra points to handle curved boundary conditions.
xval=(xval(1:end-1)'*ones(1,dpatch)+diff(xval)'*[0:dpatch-1]/dpatch)';
xval=[xval(:);lims(2)];
% Get lat/long positions for everything
[X2,Y2,lg2,lgI2]=feval(MAP_PROJECTION.routine,gridarg1,xval,gridarg2,gridarg3);
[l2x,l2y,u2x,u2y]=maketicks(X2,Y2,gticklen,'in');
if gridarg1(1)=='x', sig=1; else sig=-1; end;
id=[1:dpatch size(l2x,2)+[-dpatch+1:0]];
dx=diff(l2x(:,id));
l2x(2,id)=l2x(2,id)+diff(l2y(:,id)).*([dpatch:-1:1 -1:-1:-dpatch]/(dpatch))*sig;
l2y(2,id)=l2y(2,id)-dx.*([dpatch:-1:1 -1:-1:-dpatch]/(dpatch))*sig;
dx=diff(u2x(:,id));
u2x(2,id)=u2x(2,id)-diff(u2y(:,id)).*([dpatch:-1:1 -1:-1:-dpatch]/(dpatch))*sig;
u2y(2,id)=u2y(2,id)+dx.*([dpatch:-1:1 -1:-1:-dpatch]/(dpatch))*sig;
% Now actually draw the patches.
% Added the z-values 16/Oct/05.
px=prod(size(l2x));
kk=[0:(dpatch*4):px-3]'*ones(1,dpatch*2+2);
kk=kk+ones(size(kk,1),1)*[1 2:2:(dpatch*2+2) (dpatch*2+1):-2:3];
patch(reshape(u2x(kk),size(kk,1),size(kk,2))',...
reshape(u2y(kk),size(kk,1),size(kk,2))',...
repmat(flintmax,size(kk,2),size(kk,1)),'w','edgecolor','k','clipping','off','tag','m_grid_fancybox1');
patch(reshape(l2x(kk),size(kk,1),size(kk,2))',...
reshape(l2y(kk),size(kk,1),size(kk,2))',...
repmat(flintmax-1,size(kk,2),size(kk,1)),'k','clipping','off','tag','m_grid_fancybox1');
kk=[dpatch*2:(dpatch*4):px-3]'*ones(1,dpatch*2+2);
kk=kk+ones(size(kk,1),1)*[1 2:2:(dpatch*2+2) (dpatch*2+1):-2:3];
patch(reshape(l2x(kk),size(kk,1),size(kk,2))',...
reshape(l2y(kk),size(kk,1),size(kk,2))',...
repmat(flintmax ,size(kk,2),size(kk,1)),'w','edgecolor','k','clipping','off','tag','m_grid_fancybox1');
patch(reshape(u2x(kk),size(kk,1),size(kk,2))',...
reshape(u2y(kk),size(kk,1),size(kk,2))',...
repmat(flintmax-1,size(kk,2),size(kk,1)),'k','clipping','off','tag','m_grid_fancybox1');
%---------------------------------------------------------
function fancybox2(vals,lims,gridarg1,gridarg2,dpatch,gticklen,gridarg3);
%
% FANCYBOX - draws fancy outlines for either top/bottom or left/right sides,
% depending on calling parameters.
global MAP_PROJECTION
% Get xlocations including endpoints
xval=sort([lims(1) vals(vals>lims(1) & vals<lims(2)) lims(2)]);
% Add all half-way points as well.
xval=sort([xval,xval(1:end-1)+diff(xval)/2]);
% Interpolate extra points to handle curved boundary conditions.
xval=(xval(1:end-1)'*ones(1,dpatch)+diff(xval)'*[0:dpatch-1]/dpatch)';
xval=[xval(:);lims(2)];
% Get lat/long positions for everything
[X2,Y2,lg2,lgI2]=feval(MAP_PROJECTION.routine,gridarg1,xval,gridarg2,gridarg3);
[l2x,l2y,u2x,u2y]=maketicks(X2,Y2,gticklen,'in');
if gridarg1(1)=='x', sig=1; else sig=-1; end;
id=[1:dpatch size(l2x,2)+[-dpatch+1:0]];
dx=diff(l2x(:,id));
l2x(2,id)=l2x(2,id)+diff(l2y(:,id)).*([dpatch:-1:1 -1:-1:-dpatch]/(dpatch))*sig;
l2y(2,id)=l2y(2,id)-dx.*([dpatch:-1:1 -1:-1:-dpatch]/(dpatch))*sig;
dx=diff(u2x(:,id));
u2x(2,id)=u2x(2,id)-diff(u2y(:,id)).*([dpatch:-1:1 -1:-1:-dpatch]/(dpatch))*sig;
u2y(2,id)=u2y(2,id)+dx.*([dpatch:-1:1 -1:-1:-dpatch]/(dpatch))*sig;
% Now actually draw the patches.
% Added large z-values 16/Oct/05
px=prod(size(l2x));
kk=[0:(dpatch*2):px-3]'*ones(1,dpatch*2+2);
kk=kk+ones(size(kk,1),1)*[1 2:2:(dpatch*2+2) (dpatch*2+1):-2:3];
patch(reshape(l2x(kk),size(kk,1),size(kk,2))',...
reshape(l2y(kk),size(kk,1),size(kk,2))',...
repmat(flintmax-1,size(kk,2),size(kk,1)),...
'w','edgecolor','k','clipping','off','linewidth',.2,'tag','m_grid_fancybox2');
patch(reshape(u2x(kk),size(kk,1),size(kk,2))',...
reshape(u2y(kk),size(kk,1),size(kk,2))',...
repmat(flintmax-1,size(kk,2),size(kk,1)),...
'w','edgecolor','k','clipping','off','linewidth',.2,'tag','m_grid_fancybox2');
kk=[0:(dpatch*2):size(l2x,2)-dpatch-1]'*ones(1,dpatch+1);
kk=(kk+ones(size(kk,1),1)*[1:dpatch+1])';
[k1,k2]=size(kk);
line(reshape(mean(l2x(:,kk)),k1,k2),reshape(mean(l2y(:,kk))',k1,k2),...
repmat(flintmax,k1,k2),'color','k','clipping','off','tag','m_grid_fancybox2');
kk=[dpatch:(dpatch*2):size(l2x,2)-dpatch-1]'*ones(1,dpatch+1);
kk=(kk+ones(size(kk,1),1)*[1:dpatch+1])';
[k1,k2]=size(kk);
line(reshape(mean(u2x(:,kk))',k1,k2),reshape(mean(u2y(:,kk))',k1,k2),...
repmat(flintmax,k1,k2),'color','k','clipping','off','tag','m_grid_fancybox2');
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
mp_utm.m
|
.m
|
BEHR-core-utils-master/Utils/m_map/private/mp_utm.m
| 10,031 |
utf_8
|
0f2bdbaae3627ac4ef3095faa5d099a5
|
function [X,Y,vals,labI]=mp_utm(optn,varargin)
% MP_UTM Universal Transverse Mercator projection
% This function should not be used directly; instead it is
% is accessed by various high-level functions named M_*.
% mp_utm.m, Peter Lemmond ([email protected])
% created mp_utm.m 13Aug98 from mp_tmerc.m, v1.2d distribution, by:
%
% Rich Pawlowicz ([email protected]) 2/Apr/1997
%
% This software is provided "as is" without warranty of any kind. But
% it's mine, so you can't sell it.
%
% Mathematical formulas for the projections and their inverses are taken from
%
% Snyder, John P., Map Projections used by the US Geological Survey,
% Geol. Surv. Bull. 1532, 2nd Edition, USGPO, Washington D.C., 1983.
%
% 10/Dec/98 - PL added various ellipsoids.
% 17/May/12 - clarified hemisphere setting
global MAP_PROJECTION MAP_VAR_LIST
% define a structure of various ellipsoids. each has a name, and
% a vector consisting of equatorial radius and flattening. the first
% two are somewhat special cases.
MAP_ELLIP = struct ( 'normal', [1.0, 0], ...
'sphere', [6370997.0, 0], ...
'grs80' , [6378137.0, 1/298.257], ...
'grs67' , [6378160.0, 1/247.247], ...
'wgs84' , [6378137.0, 1/298.257], ...
'wgs72' , [6378135.0, 1/298.260], ...
'wgs66' , [6378145.0, 1/298.250], ...
'wgs60' , [6378165.0, 1/298.300], ...
'clrk66', [6378206.4, 1/294.980], ...
'clrk80', [6378249.1, 1/293.466], ...
'intl24', [6378388.0, 1/297.000], ...
'intl67', [6378157.5, 1/298.250]);
name={'UTM'};
switch optn,
case 'name',
X=name;
case {'usage','set'}
m_names=fieldnames(MAP_ELLIP);
X=char({[' ''' varargin{1} ''''],...
' <,''lon<gitude>'',[min max]>',...
' <,''lat<itude>'',[min max]>',...
' <,''zon<e>'',value>',...
' <,''hem<isphere>'',[1|0] (0 for N)>',...
' <,''ell<ipsoid>'', one of',...
reshape(sprintf(' %6s',m_names{:}),15,length(m_names))',...
' >',...
' <,''rec<tbox>'', ( ''on'' | ''off'' )>'});
case 'get',
X=char([' Projection: ' MAP_PROJECTION.name ' (function: ' ...
MAP_PROJECTION.routine ')'],...
[' longitudes: ' num2str(MAP_VAR_LIST.ulongs) ],...
[' latitudes: ' num2str(MAP_VAR_LIST.ulats) ],...
[' zone: ' num2str(MAP_VAR_LIST.zone) ],...
[' hemisphere: ' num2str(MAP_VAR_LIST.hemisphere) ],...
[' ellipsoid: ' MAP_VAR_LIST.ellipsoid ], ...
[' Rectangular border: ' MAP_VAR_LIST.rectbox ]);
case 'initialize',
MAP_VAR_LIST=[];
MAP_PROJECTION.name=varargin{1};
MAP_VAR_LIST.ulongs = [-72 -68];
MAP_VAR_LIST.ulats = [40 44];
MAP_VAR_LIST.zone = 0; % will be computed if not there
MAP_VAR_LIST.hemisphere = -1;
MAP_VAR_LIST.ellipsoid = 'normal';
MAP_VAR_LIST.rectbox='off';
k=2;
while k<length(varargin),
switch varargin{k}(1:3),
case 'lon',
MAP_VAR_LIST.ulongs=varargin{k+1};
case 'lat',
MAP_VAR_LIST.ulats=varargin{k+1};
case 'zon',
MAP_VAR_LIST.zone=varargin{k+1};
case 'hem',
MAP_VAR_LIST.hemisphere=varargin{k+1};
case 'ell',
MAP_VAR_LIST.ellipsoid=varargin{k+1};
case 'rec',
MAP_VAR_LIST.rectbox=varargin{k+1};
otherwise
disp(['Unknown option: ' varargin{k}]);
end;
k=k+2;
end;
% set the zone and hemisphere if not specified
if (~MAP_VAR_LIST.zone)
MAP_VAR_LIST.zone = 1 + fix((mod(mean(MAP_VAR_LIST.ulongs)+180,360))/6);
end
if MAP_VAR_LIST.hemisphere==-1,
MAP_VAR_LIST.hemisphere=mean(MAP_VAR_LIST.ulats)<0;
end;
% check for a valid ellipsoid. if not, use the normalized sphere
if ~isfield(MAP_ELLIP,MAP_VAR_LIST.ellipsoid),
MAP_VAR_LIST.ellipsoid = 'normal';
end
% Get X/Y and (if rectboxs are desired) recompute lat/long limits.
mu_util('xylimits');
if strcmp(MAP_VAR_LIST.rectbox,'on'), mu_util('lllimits'); end;
case 'll2xy',
long=varargin{1};
lat=varargin{2};
vals=zeros(size(long));
% Clip out-of-range values (lat/long boxes)
if strcmp(MAP_VAR_LIST.rectbox,'off') & ~strcmp(varargin{4},'off'),
vals=vals | long<=MAP_VAR_LIST.longs(1)+eps*10 | long>=MAP_VAR_LIST.longs(2)-eps*10 | ...
lat<=MAP_VAR_LIST.lats(1)+eps*10 | lat>=MAP_VAR_LIST.lats(2)-eps*10;
[long,lat]=mu_util('clip',varargin{4},long,MAP_VAR_LIST.longs(1),long<MAP_VAR_LIST.longs(1),lat);
[long,lat]=mu_util('clip',varargin{4},long,MAP_VAR_LIST.longs(2),long>MAP_VAR_LIST.longs(2),lat);
[lat,long]=mu_util('clip',varargin{4},lat,MAP_VAR_LIST.lats(1),lat<MAP_VAR_LIST.lats(1),long);
[lat,long]=mu_util('clip',varargin{4},lat,MAP_VAR_LIST.lats(2),lat>MAP_VAR_LIST.lats(2),long);
end;
% do the forward transformation
[X,Y] = mu_ll2utm(lat,long,MAP_VAR_LIST.zone,MAP_VAR_LIST.hemisphere, ...
getfield(MAP_ELLIP,MAP_VAR_LIST.ellipsoid));
% Clip out-of-range values (rectboxes)
if strcmp(MAP_VAR_LIST.rectbox,'on') & ~strcmp(varargin{4},'off'),
vals= vals | X<=MAP_VAR_LIST.xlims(1)+eps*10 | X>=MAP_VAR_LIST.xlims(2)-eps*10 | ...
Y<=MAP_VAR_LIST.ylims(1)+eps*10 | Y>=MAP_VAR_LIST.ylims(2)-eps*10;
[X,Y]=mu_util('clip',varargin{4},X,MAP_VAR_LIST.xlims(1),X<MAP_VAR_LIST.xlims(1),Y);
[X,Y]=mu_util('clip',varargin{4},X,MAP_VAR_LIST.xlims(2),X>MAP_VAR_LIST.xlims(2),Y);
[Y,X]=mu_util('clip',varargin{4},Y,MAP_VAR_LIST.ylims(1),Y<MAP_VAR_LIST.ylims(1),X);
[Y,X]=mu_util('clip',varargin{4},Y,MAP_VAR_LIST.ylims(2),Y>MAP_VAR_LIST.ylims(2),X);
end;
case 'xy2ll',
[Y,X] = mu_utm2ll(varargin{1}, varargin{2}, MAP_VAR_LIST.zone, ...
MAP_VAR_LIST.hemisphere, getfield(MAP_ELLIP,MAP_VAR_LIST.ellipsoid));
case 'xgrid',
[X,Y,vals,labI]=mu_util('xgrid',MAP_VAR_LIST.longs,MAP_VAR_LIST.lats,varargin{1},31,varargin{2:3});
case 'ygrid',
[X,Y,vals,labI]=mu_util('ygrid',MAP_VAR_LIST.lats,MAP_VAR_LIST.longs,varargin{1},31,varargin{2:3});
case 'box',
[X,Y]=mu_util('box',31);
end;
%-------------------------------------------------------------------
function [x,y] = mu_ll2utm (lat,lon, zone, hemisphere,ellipsoid)
%mu_ll2utm Convert geodetic lat,lon to X/Y UTM coordinates
%
% [x,y] = mu_ll2utm (lat, lon, zone, hemisphere,ellipsoid)
%
% input is latitude and longitude vectors, zone number,
% hemisphere(N=0,S=1), ellipsoid info [eq-rad, flat]
% output is X/Y vectors
%
% see also mu_utm2ll, utmzone
% some general constants
DEG2RADS = 0.01745329252;
RADIUS = ellipsoid(1);
FLAT = ellipsoid(2);
K_NOT = 0.9996;
FALSE_EAST = 500000;
FALSE_NORTH = 10000000;
% check for valid numbers
if (max(abs(lat)) > 90)
error('latitude values exceed 89 degree');
return;
end
if ((zone < 1) | (zone > 60))
error ('utm zones only valid from 1 to 60');
return;
end
% compute some geodetic parameters
lambda_not = ((-180 + zone*6) - 3) * DEG2RADS;
e2 = 2*FLAT - FLAT*FLAT;
e4 = e2 * e2;
e6 = e4 * e2;
ep2 = e2/(1-e2);
% some other constants, vectors
lat = lat * DEG2RADS;
lon = lon * DEG2RADS;
sinL = sin(lat);
tanL = tan(lat);
cosL = cos(lat);
T = tanL.*tanL;
C = ep2 * (cosL.*cosL);
A = (lon - lambda_not).*cosL;
A2 = A.*A;
A4 = A2.*A2;
S = sinL.*sinL;
% solve for N
N = RADIUS ./ (sqrt (1-e2*S));
% solve for M
M0 = 1 - e2*0.25 - e4*0.046875 - e6*0.01953125;
M1 = e2*0.375 + e4*0.09375 + e6*0.043945313;
M2 = e4*0.05859375 + e6*0.043945313;
M3 = e6*0.011393229;
M = RADIUS.*(M0.*lat - M1.*sin(2*lat) + M2.*sin(4*lat) - M3.*sin(6*lat));
% solve for x
X0 = A4.*A/120;
X1 = 5 - 18*T + T.*T + 72*C - 58*ep2;
X2 = A2.*A/6;
X3 = 1 - T + C;
x = N.*(A + X3.*X2 + X1.* X0);
% solve for y
Y0 = 61 - 58*T + T.*T + 600*C - 330*ep2;
Y1 = 5 - T + 9*C + 4*C.*C;
y = M + N.*tanL.*(A2/2 + Y1.*A4/24 + Y0.*A4.*A2/720);
% finally, do the scaling and false thing. if using a unit-normal radius,
% we don't bother.
x = x*K_NOT + (RADIUS>1) * FALSE_EAST;
y = y*K_NOT;
if (hemisphere)
y = y + (RADIUS>1) * FALSE_NORTH;
end
return
%-------------------------------------------------------------------
function [lat,lon] = mu_utm2ll (x,y, zone, hemisphere,ellipsoid)
%mu_utm2ll Convert X/Y UTM coordinates to geodetic lat,lon
%
% [lat,lon] = mu_utm2ll (x,y, zone, hemisphere,ellipsoid)
%
% input is X/Y vectors, zone number, hemisphere(N=0,S=1),
% ellipsoid info [eq-rad, flat]
% output is lat/lon vectors
%
% see also mu_ll2utm, utmzone
% some general constants
DEG2RADS = 0.01745329252;
RADIUS = ellipsoid(1);
FLAT = ellipsoid(2);
K_NOT = 0.9996;
FALSE_EAST = 500000;
FALSE_NORTH = 10000000;
if ((zone < 1) | (zone > 60))
error ('utm zones only valid from 1 to 60');
return;
end
% compute some geodetic parameters
e2 = 2*FLAT - FLAT*FLAT;
e4 = e2 * e2;
e6 = e4 * e2;
eps = e2 / (1-e2);
em1 = sqrt(1-e2);
e1 = (1-em1)/(1+em1);
e12 = e1*e1;
lambda_not = ((-180 + zone*6) - 3) * DEG2RADS;
% remove the false things
x = x - (RADIUS>1)*FALSE_EAST;
if (hemisphere)
y = y - (RADIUS>1)*FALSE_NORTH;
end
% compute the footpoint latitude
M = y/K_NOT;
mu = M/(RADIUS * (1 - 0.25*e2 - 0.046875*e4 - 0.01953125*e6));
foot = mu + (1.5*e1 - 0.84375*e12*e1)*sin(2*mu) ...
+ (1.3125*e12 - 1.71875*e12*e12)*sin(4*mu) ...
+ (1.57291666667*e12*e1)*sin(6*mu) ...
+ (2.142578125*e12*e12)*sin(8*mu);
% some other terms
sinF = sin(foot);
cosF = cos(foot);
tanF = tan(foot);
N = RADIUS ./ sqrt(1-e2*(sinF.*sinF));
T = tanF.*tanF;
T2 = T.*T;
C = eps * cosF.*cosF;
C2 = C.*C;
denom = sqrt(1-e2*(sinF.*sinF));
R = RADIUS * em1*em1 ./ (denom.*denom.*denom);
D = x./(N*K_NOT);
D2 = D.*D;
D4 = D2.*D2;
% can now compute the lat and lon
lat = foot - (N.*tanF./R) .* (0.5*D2 - (5 + 3*T + 10*C - 4*C2 - 9*eps).*D4/24 ...
+ (61 + 90*T + 298*C + 45*T2 - 252*eps - 3*C2) .* D4 .* D2/720);
lon = lambda_not + (D - (1 + 2*T +C).*D2.*D/6 + ...
(5 - 2*C + 28*T - 3*C2 + 8*eps + 24*T2).*D4.*D./120)./cosF;
% convert back to degrees;
lat=lat/DEG2RADS;
lon=lon/DEG2RADS;
return
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
mu_coast.m
|
.m
|
BEHR-core-utils-master/Utils/m_map/private/mu_coast.m
| 23,340 |
utf_8
|
e311e8a8c34c939a523f620a92658064
|
function [ncst,Area,k]=mu_coast(optn,varargin);
% MU_COAST Add a coastline to a given map.
% MU_COAST draw a coastline as either filled patches (slow) or
% lines (fast) on a given projection. It uses a coastline database with
% a resolution of about 1/4 degree.
%
% It is not meant to be called directly by the user, instead it contains
% code common to various functions in the m_map directory.
%
% Calling sequence is MU_COAST(option,arguments) where
%
% Option string
% c,l,i,h,f : Accesses various GSHHS databases. Next argument is
% GSHHS filename.
%
% u[ser] : Accesses user-specified coastline file (a mat-file of
% data saved from a previous MU_COAST call). Next argument
% is filename
%
% v[ector] : Uses input vector of data. Next argument is the
% data in the form of a nx2 matrix of [longitude latitude].
% Patches must have first and last points the same. In a vector,
% different patches can be separated by NaN.
%
% d[efault] : Accesses default coastline.
%
% The arguments given above are then followed by (optional) arguments
% specifying lines or patches, in the form:
%
% optional arguments: <line property/value pairs>, or
% 'line',<line property/value pairs>.
% 'patch',<patch property/value pairs>.
% 'speckle',width,density,<line property/value pairs>.
%
% If no or one output arguments are specified then the coastline is drawn, with
% patch handles returned.
% If 3 output arguments are specified in the calling sequence, then no drawing
% is done. This can be used to save subsampled coastlines for future use
% with the 'u' option, for fast drawing of multiple instances of a particular
% coastal region.
%
%
%
% See also M_PROJ, M_GRID
% Rich Pawlowicz ([email protected]) 2/Apr/1997
%
% Notes: 15/June/98 - fixed some obscure problems that occured sometimes
% when using conic projections with large extents that
% crossed the 180-deg longitude line.
% 31/Aug/98 - added "f" gshhs support (Thanks to RAMO)
% 17/June/99 - 'line' option as per manual (thanks to Brian Farrelly)
% 3/Aug/01 - kludge fix for lines to South Pole in Antarctica (response
% to Matt King).
% 30/May/02 - fix to get gshhs to work in Antarctica.
% 15/Dec/05 - speckle additions
% 21/Mar/06 - handling of gshhs v1.3 (developed from suggestions by
% Martin Borgh)
% 26/Nov/07 - changed 'finite' to 'isfinite' after warnings
%
% This software is provided "as is" without warranty of any kind. But
% it's mine, so you can't sell it.
global MAP_PROJECTION MAP_VAR_LIST
% Have to have initialized a map first
if isempty(MAP_PROJECTION),
disp('No Map Projection initialized - call M_PROJ first!');
return;
end;
% m_coasts.mat contains 3 variables:
% ncst: a Nx2 matrix of [LONG LAT] line segments, each of which form
% a closed contour, separated by NaN
% k=[find(isnan(ncst(:,1)))];
% Area: a vector giving the areas of the different patches. Both ncst
% and Area should be ordered with biggest regions first. Area can
% be computed as follows:
%
% Area=zeros(length(k)-1,1);
% for i=1:length(k)-1,
% x=ncst([k(i)+1:(k(i+1)-1) k(i)+1],1);
% y=ncst([k(i)+1:(k(i+1)-1) k(i)+1],2);
% nl=length(x);
% Area(i)=sum( diff(x).*(y(1:nl-1)+y(2:nl))/2 );
% end;
%
% Area should be >0 for land, and <0 for lakes and inland seas.
switch optn(1),
case {'c','l','i','h','f'},
[ncst,k,Area]=get_coasts(optn,varargin{1});
varargin(1)=[];
case 'u',
eval(['load ' varargin{1} ' -mat']);
varargin(1)=[];
case 'v',
ncst=[NaN NaN;varargin{1};NaN NaN];
varargin(1)=[];
k=[find(isnan(ncst(:,1)))]; % Get k
Area=ones(size(k)); % Make dummy Area vector (all positive).
otherwise
load m_coasts
end;
% If all we wanted was to extract a sub-coastline, return.
if nargout==3,
return;
end;
% Handle wrap-arounds (not needed for azimuthal and oblique projections)
switch MAP_PROJECTION.routine,
case {'mp_cyl','mp_conic','mp_tmerc'}
if MAP_VAR_LIST.longs(2)<-180,
ncst(:,1)=ncst(:,1)-360;
elseif MAP_VAR_LIST.longs(1)>180,
ncst(:,1)=ncst(:,1)+360;
elseif MAP_VAR_LIST.longs(1)<-180,
Area=[Area;Area];
k=[k;k(2:end)+k(end)-1];
ncst=[ncst;[ncst(2:end,1)-360 ncst(2:end,2)]];
% This is kinda kludgey - but sometimes adding all these extra points
% causes wrap-around in the conic projection, so we want to limit the
% longitudes to the range needed. However, we don't just clip them to
% min long because that can cause problems in trying to decide which way
% curves are oriented when doing the fill algorithm below. So instead
% I sort of crunch the scale, preserving topology.
%
% 12/Sep/2006 - in the gsshs_crude database we have a lot of long skinny
% things which interact badly with this - so I offset the scrunch 2 degrees
% away from the bdy
nn=ncst(:,1)<MAP_VAR_LIST.longs(1)-2;
ncst(nn,1)=(ncst(nn,1)-MAP_VAR_LIST.longs(1)+2)/100+MAP_VAR_LIST.longs(1)-2;
elseif MAP_VAR_LIST.longs(2)>180,
Area=[Area;Area];
k=[k;k(2:end)+k(end)-1];
ncst=[ncst;[ncst(2:end,1)+360 ncst(2:end,2)]];
% Ditto.
nn=ncst(:,1)>MAP_VAR_LIST.longs(2)+2;
ncst(nn,1)=(ncst(nn,1)-MAP_VAR_LIST.longs(2)-2)/100+MAP_VAR_LIST.longs(2)+2;
end;
end;
if length(varargin)>0,
if strcmp(varargin(1),'patch'),
optn='patch';
end
if strcmp(varargin(1),'speckle'),
optn='speckle';
end
if strcmp(varargin(1),'line'),
optn='line';
varargin=varargin(2:end); % ensure 'line' does not get passed to line
end
else
optn='line';
end;
switch optn,
case {'patch','speckle'}
switch MAP_VAR_LIST.rectbox,
case 'on',
xl=MAP_VAR_LIST.xlims;
yl=MAP_VAR_LIST.ylims;
[X,Y]=m_ll2xy(ncst(:,1),ncst(:,2),'clip','on');
oncearound=4;
case 'off',
xl=MAP_VAR_LIST.longs;
yl=MAP_VAR_LIST.lats;
X=ncst(:,1);
Y=ncst(:,2);
[X,Y]=mu_util('clip','on',X,xl(1),X<xl(1),Y);
[X,Y]=mu_util('clip','on',X,xl(2),X>xl(2),Y);
[Y,X]=mu_util('clip','on',Y,yl(1),Y<yl(1),X);
[Y,X]=mu_util('clip','on',Y,yl(2),Y>yl(2),X);
oncearound=4;
case 'circle',
rl=MAP_VAR_LIST.rhomax;
[X,Y]=m_ll2xy(ncst(:,1),ncst(:,2),'clip','on');
oncearound=2*pi;
end;
p_hand=zeros(length(k)-1,1); % Patch handles
for i=1:length(k)-1,
x=X(k(i)+1:k(i+1)-1);
fk=isfinite(x);
if any(fk),
y=Y(k(i)+1:k(i+1)-1);
%% if i>921, disp('pause 1'); pause; end;
nx=length(x);
if Area(i)<0, x=flipud(x);y=flipud(y); fk=flipud(fk); end;
%clf
%line(x,y,'color','m');
st=find(diff(fk)==1)+1;
ed=find(diff(fk)==-1);
%length(x),
%ed,
%st
if length(st)<length(ed) | isempty(st), st=[ 1;st]; end;
if length(ed)<length(st), ed=[ed;nx]; end;
%ed
%st
if ed(1)<st(1),
if c_edge(x(1),y(1))==9999,
x=x([(ed(1)+1:end) (1:ed(1))]);
y=y([(ed(1)+1:end) (1:ed(1))]);
fk=isfinite(x);
st=find(diff(fk)==1)+1;
ed=[find(diff(fk)==-1);nx];
if length(st)<length(ed), st=[1;st]; end
else
ed=[ed;nx];
st=[1;st];
end;
end;
%ed
%st
% Get rid of 2-point curves (since often these are out-of-range lines with
% both endpoints outside the region of interest)
k2=(ed-st)<3;
ed(k2)=[]; st(k2)=[];
%%[XX,YY]=m_ll2xy(x(st),y(st),'clip','off');
%line(x,y,'color','r','linestyle','-');
%line(x(st),y(st),'marker','o','color','r','linestyle','none');
%line(x(ed),y(ed),'marker','o','color','g','linestyle','none');
edge1=c_edge(x(st),y(st));
edge2=c_edge(x(ed),y(ed));
%-edge1*180/pi
%-edge2*180/pi
mi=1;
while length(st)>0,
if mi==1,
xx=x(st(1):ed(1));
yy=y(st(1):ed(1));
end;
estart=edge2(1);
s_edge=edge1;
s_edge(s_edge<estart)=s_edge(s_edge<estart)+oncearound;
%s_edge,estart
[md,mi]=min(s_edge-estart);
switch MAP_VAR_LIST.rectbox,
case {'on','off'},
for e=floor(estart):floor(s_edge(mi)),
if e==floor(s_edge(mi)), xe=x(st([mi mi])); ye=y(st([mi mi]));
else xe=xl; ye=yl; end;
switch rem(e,4),
case 0,
xx=[xx; xx(end*ones(10,1))];
yy=[yy; yy(end)+(ye(2)-yy(end))*[1:10]'/10 ];
case 1,
xx=[xx; xx(end)+(xe(2)-xx(end))*[1:10]'/10 ];
yy=[yy; yy(end*ones(10,1))];
case 2,
xx=[xx; xx(end*ones(10,1))];
yy=[yy; yy(end)+(ye(1)-yy(end))*[1:10]'/10;];
case 3,
xx=[xx; xx(end)+(xe(1)-xx(end))*[1:10]'/10 ];
yy=[yy; yy(end*ones(10,1))];
end;
end;
case 'circle',
if estart~=9999,
%s_edge(mi),estart
xx=[xx; rl*cos(-[(estart:.1:s_edge(mi))]')];
yy=[yy; rl*sin(-[(estart:.1:s_edge(mi))]')];
end;
end;
if mi==1, % joined back to start
if strcmp(optn,'patch'),
if strcmp(MAP_VAR_LIST.rectbox,'off'),
[xx,yy]=m_ll2xy(xx,yy,'clip','off');
end;
if Area(i)<0,
p_hand(i)=patch(xx,yy,varargin{2:end},'facecolor',get(gca,'color'));
else
p_hand(i)=patch(xx,yy,varargin{2:end});
end;
else % speckle
if ~strcmp(MAP_VAR_LIST.rectbox,'off'), % If we were clipping in
[xx,yy]=m_xy2ll(xx,yy); % screen coords go back
end;
if Area(i)>0,
p_hand(i)=m_hatch(xx,yy,'speckle',varargin{2:end});
else
p_hand(i)=m_hatch(xx,yy,'outspeckle',varargin{2:end});
end;
end;
%%%if i>921, disp(['paused-2 ' int2str(i)]);pause; end;
ed(1)=[];st(1)=[];edge2(1)=[];edge1(1)=[];
else
xx=[xx;x(st(mi):ed(mi))];
yy=[yy;y(st(mi):ed(mi))];
ed(1)=ed(mi);st(mi)=[];ed(mi)=[];
edge2(1)=edge2(mi);edge2(mi)=[];edge1(mi)=[];
end;
%%if i>921, disp(['paused-2 ' int2str(i)]);pause; end;
end;
end;
end;
otherwise,
% This handles the odd points required at the south pole by any Antarctic
% coastline by setting them to NaN (for lines only)
ii=ncst(:,2)<=-89.9;
if any(ii), ncst(ii,:)=NaN; end;
[X,Y]=m_ll2xy(ncst(:,1),ncst(:,2),'clip','on');
% Get rid of 2-point lines (these are probably clipped lines spanning the window)
fk=isfinite(X);
st=find(diff(fk)==1)+1;
ed=find(diff(fk)==-1);
k=find((ed-st)==1);
X(st(k))=NaN;
p_hand=line(X,Y,varargin{:});
end;
ncst=p_hand;
%-----------------------------------------------------------------------
function edg=c_edge(x,y);
% C_EDGE tests if a point is on the edge or not. If it is, it is
% assigned a value representing it's position oon the perimeter
% in the clockwise direction. For x/y or lat/long boxes, these
% values are
% 0 -> 1 on left edge
% 1 -> 2 on top
% 2 -> 3 on right edge
% 3 -> 4 on bottom
% For circular boxes, these values are the -ve of the angle
% from center.
global MAP_VAR_LIST
switch MAP_VAR_LIST.rectbox,
case 'on',
xl=MAP_VAR_LIST.xlims;
yl=MAP_VAR_LIST.ylims;
case 'off',
xl=MAP_VAR_LIST.longs;
yl=MAP_VAR_LIST.lats;
case 'circle',
rl2=MAP_VAR_LIST.rhomax^2;
end;
edg=9999+zeros(length(x),1);
tol=1e-10;
switch MAP_VAR_LIST.rectbox,
case {'on','off'},
i=abs(x-xl(1))<tol;
edg(i)=(y(i)-yl(1))/diff(yl);
i=abs(x-xl(2))<tol;
edg(i)=2+(yl(2)-y(i))/diff(yl);
i=abs(y-yl(1))<tol;
edg(i)=3+(xl(2)-x(i))/diff(xl);
i=abs(y-yl(2))<tol;
edg(i)=1+(x(i)-xl(1))/diff(xl);
case 'circle',
i=abs(x.^2 + y.^2 - rl2)<tol;
edg(i)=-atan2(y(i),x(i)); % use -1*angle so that numeric values
% increase in CW direction
end;
%%
function [ncst,k,Area]=get_coasts(optn,file);
%
% GET_COASTS Loads various GSHHS coastline databases and does some preliminary
% processing to get things into the form desired by the patch-filling
% algorithm.
%
% Changes; 3/Sep/98 - RP: better decimation, fixed bug in limit checking.
global MAP_PROJECTION MAP_VAR_LIST
llim=rem(MAP_VAR_LIST.longs(1)+360,360)*1e6;
rlim=rem(MAP_VAR_LIST.longs(2)+360,360)*1e6;
tlim=MAP_VAR_LIST.lats(2)*1e6;
blim=MAP_VAR_LIST.lats(1)*1e6;
mrlim=rem(MAP_VAR_LIST.longs(2)+360+180,360)-180;
mllim=rem(MAP_VAR_LIST.longs(1)+360+180,360)-180;
mtlim=MAP_VAR_LIST.lats(2);
mblim=MAP_VAR_LIST.lats(1);
% decfac is for decimation of areas outside the lat/long bdys.
% Sizes updated for gshhs v1.3
% Sizes updated for v1.10, and for river/border databases.
switch optn(1),
case 'f', % 'full' (undecimated) database
ncst=NaN+zeros(10561669,2);Area=zeros(188611,1);k=ones(188612,1);
decfac=12500;
case 'h',
ncst=NaN+zeros(2063513,2);Area=zeros(153545,1);k=ones(153546,1);
decfac=2500;
case 'i',
ncst=NaN+zeros(493096,2);Area=zeros(41529,1);k=ones(41530,1);
decfac=500;
case 'l',
ncst=NaN+zeros(124871,2);Area=zeros(20776,1);k=ones(27524,1);
decfac=100;
case 'c',
ncst=NaN+zeros(110143,2);Area=zeros(20871,1);k=ones(27524,1);
decfac=20;
end;
fid=fopen(file,'r','ieee-be');
if fid==-1,
warning(sprintf(['Coastline file ' file ...
' not found \n(Have you installed it? See the M_Map User''s Guide for details)' ...
'\n ---Using default coastline instead']));
load m_coasts
return
end;
%%size(ncst)
Area2=Area;
% Read the File header
%%[A,cnt]=fread(fid,9,'int32');
[A,cnt]=get_gheader(fid);
l=0;
while cnt>0,
% A: 1:ID, 2:num points, 3:land/lake etc., 4-7:w/e/s/n, 8:area, 9:greenwich crossed.
C=fread(fid,A(2)*2,'int32'); % Read all points in the current segment.
%For Antarctica the lime limits are 0 to 360 (exactly), thus c==0 and the
%line is not chosen for (e.g. a conic projection of part of Antarctica)
% Fix 30may/02
if A(5)==360e6, A(5)=A(5)-1; end;
a=rlim>llim; % Map limits cross longitude jump? (a==1 is no)
b=A(9)<65536; % Cross boundary? (b==1 if no).
c=llim<rem(A(5)+360e6,360e6);
d=rlim>rem(A(4)+360e6,360e6);
e=tlim>A(6) & blim<A(7);
% This test checks whether the lat/long box containing the line overlaps that of
% the map. There are various cases to consider, depending on whether map limits
% and/or the line limits cross the longitude jump or not.
%% if e & ( a&( b&c&d | ~b&(c|d)) | ~a&(~b | (b&(c|d))) ),
if e & ( (a&( (b&c&d) | (~b&(c|d)) )) | (~a&(~b | (b&(c|d))) ) ),
l=l+1;
x=C(1:2:end)*1e-6;y=C(2:2:end)*1e-6;
%% plot(x,y);pause;
% make things continuous (join edges that cut across 0-meridian)
dx=diff(x);
%%fprintf('%f %f\n', max(dx),min(dx))
% if A(9)>65536 | any(dx)>356 | any(dx<356),
% if ~b | any(dx>356) | any(dx<-356),
x=x-360*cumsum([x(1)>180;(dx>356) - (dx<-356)]);
% end;
% Antarctic is a special case - extend contour to make nice closed polygon
% that doesn't surround the pole.
if abs(x(1))<1 & abs(y(1)+68.9)<1,
y=[-89.9;-78.4;y(x<=-180);y(x>-180); -78.4;-89.9*ones(18,1)];
x=[ 180; 180 ;x(x<=-180)+360;x(x>-180);-180; [-180:20:160]'];
end;
% First and last point should be the same IF THIS IS A POLYGON
% if the Area=0 then this is a line, and don't add points!
if A(8)>0,
if x(end)~=x(1) | y(end)~=y(1), x=[x;x(1)];y=[y;y(1)]; end;
% get correct curve orientation for patch-fill algorithm.
Area2(l)=sum( diff(x).*(y(1:(end-1))+y(2:end))/2 );
Area(l)=A(8)/10;
if rem(A(3),2)==0;
Area(l)=-abs(Area(l));
if Area2(l)>0, x=x(end:-1:1);y=y(end:-1:1); end;
else
if Area2(l)<0, x=x(end:-1:1);y=y(end:-1:1); end;
end;
else
% Later on 2 point lines are clipped so we want to avoid that
if length(x)==2,
x=[x(1);mean(x);x(2)];y=[y(1);mean(y);y(2)];
end;
% disp('0');
% line(x,y);pause;
end;
% Here we try to reduce the number of points.
xflag=0;
if max(x)>180, % First, save original curve for later if we anticipate
sx=x;sy=y; % a 180-problem.
xflag=1;
end;
% Look for points outside the lat/long boundaries, and then decimate them
% by a factor of about 'decfac' (don't get rid of them completely because that
% can sometimes cause problems when polygon edges cross curved map edges).
tol=.2;
% Do y limits, then x so we can keep corner points.
nn=(y>mtlim+tol) | (y<mblim-tol);
% keep one extra point when crossing limits, also the beginning/end point.
nn=logical(nn-min(1,([0;diff(nn)]>0)+([diff(nn);0]<0)));
nn([1 end])=0;
% decimate vigorously
nn=nn & rem(1:length(nn),decfac)'~=0;
x(nn)=[];y(nn)=[];
if mrlim>mllim, % no wraparound
% sections of line outside lat/long limits
nn=(x>mrlim+tol | x<mllim-tol) & y<mtlim & y>mblim;
else % wraparound case
nn=(x>mrlim+tol & x<mllim-tol ) & y<mtlim & y>mblim;
end;
nn=logical(nn-min(1,([0;diff(nn)]>0)+([diff(nn);0]<0)));nn([1 end])=0;
nn=nn & rem(1:length(nn),decfac)'~=0;
x(nn)=[];y(nn)=[];
% Move all points "near" to map boundaries.
% I'm not sure about the wisdom of this - it might be better to clip
% to the boundaries instead of moving. Hmmm.
y(y>mtlim+tol)=mtlim+tol;
y(y<mblim-tol)=mblim-tol;
if mrlim>mllim, % Only clip long bdys if I can tell I'm on the right
% or left (i.e. not in wraparound case)
x(x>mrlim+tol)=mrlim+tol;
x(x<mllim-tol)=mllim-tol;
end;
%% plot(x,y);pause;
k(l+1)=k(l)+length(x)+1;
ncst(k(l)+1:k(l+1)-1,:)=[x,y];
ncst(k(l+1),:)=[NaN NaN];
% This is a little tricky...the filling algorithm expects data to be in the
% range -180 to 180 deg long. However, there are some land parts that cut across
% this divide so they appear at +190 but not -170. This causes problems later...
% so as a kludge I replicate some of the problematic features at 190-360=-170.
% Small islands are just duplicated, for the Eurasian landmass I just clip
% off the eastern part.
if xflag,
l=l+1;Area(l)=Area(l-1);
if abs(Area(l))>1e5,
nn=find(sx>180);nn=[nn;nn(1)];
k(l+1)=k(l)+length(nn)+1;
ncst(k(l)+1:k(l+1)-1,:)=[sx(nn)-360,sy(nn)];
else % repeat the island at the other edge.
k(l+1)=k(l)+length(sx)+1;
ncst(k(l)+1:k(l+1)-1,:)=[sx-360,sy];
end;
ncst(k(l+1),:)=[NaN NaN];
end;
end;
%%[A,cnt]=fread(fid,9,'int32');
[A,cnt]=get_gheader(fid);
end;
fclose(fid);
%%plot(ncst(:,1),ncst(:,2));pause;clf;
%size(ncst)
%size(Area)
%size(k)
ncst((k(l+1)+1):end,:)=[]; % get rid of unused part of data matrices
Area((l+1):end)=[];
k((l+2):end)=[];
%size(ncst)
%size(Area)
%size(k)
%%%
function [A,cnt]=get_gheader(fid);
% Reads the gshhs file header
%
% A bit of code added because header format changed with version 1.3.
%
% 17/Sep/2008 - added material to handle latest GSHHS version.
%
% For version 1.1 this is the header ( 9*4 = 36 bytes long)
%
%int id; /* Unique polygon id number, starting at 0 */
%int n; /* Number of points in this polygon */
%int level; /* 1 land, 2 lake, 3 island_in_lake, 4 pond_in_island_in_lake */
%int west, east, south, north; /* min/max extent in micro-degrees */
%int area; /* Area of polygon in 1/10 km^2 */
%short int greenwich; /* Greenwich is 1 if Greenwich is crossed */
%short int source; /* 0 = CIA WDBII, 1 = WVS */
%
% For version 1.3 of GMT format was changed to this ( 10*4 = 40 bytes long)
%
%int id; /* Unique polygon id number, starting at 0 */
%int n; /* Number of points in this polygon */
%int level; /* 1 land, 2 lake, 3 island_in_lake, 4 pond_in_island_in_lake */
%int west, east, south, north; /* min/max extent in micro-degrees */
%int area; /* Area of polygon in 1/10 km^2 */
%int version; /* Polygon version, set to 3
%short int greenwich; /* Greenwich is 1 if Greenwich is crossed */
%short int source; /* 0 = CIA WDBII, 1 = WVS */
%
% For version 1.4, we have (8*4 = 32 bytes long)
%
%int id; /* Unique polygon id number, starting at 0 */
%int n; /* Number of points in this polygon */
%int flag; /* level + version << 8 + greenwich << 16 + source << 24
%int west, east, south, north; /* min/max extent in micro-degrees */
%int area; /* Area of polygon in 1/10 km^2 */
%
%Here, level, version, greenwhich, and source are
%level: 1 land, 2 lake, 3 island_in_lake, 4 pond_in_island_in_lake
%version: Set to 4 for GSHHS version 1.4
%greenwich: 1 if Greenwich is crossed
%source: 0 = CIA WDBII, 1 = WVS
%
% For version 2.0 it all changed again, we have (11*4 = 44 bytes)
%
% int id; /* Unique polygon id number, starting at 0 */
% int n; /* Number of points in this polygon */
% int flag; /* = level + version << 8 + greenwich << 16 + source << 24 + river << 25 */
% /* flag contains 5 items, as follows:
% * low byte: level = flag & 255: Values: 1 land, 2 lake, 3 island_in_lake, 4 pond_in_island_in_lake
% * 2nd byte: version = (flag >> 8) & 255: Values: Should be 7 for GSHHS release 7 (i.e., version 2.0)
% * 3rd byte: greenwich = (flag >> 16) & 1: Values: Greenwich is 1 if Greenwich is crossed
% * 4th byte: source = (flag >> 24) & 1: Values: 0 = CIA WDBII, 1 = WVS
% * 4th byte: river = (flag >> 25) & 1: Values: 0 = not set, 1 = river-lake and level = 2
% */
% int west, east, south, north; /* min/max extent in micro-degrees */
% int area; /* Area of polygon in 1/10 km^2 */
% int area_full; /* Area of original full-resolution polygon in 1/10 km^2 */
% int container; /* Id of container polygon that encloses this polygon (-1 if none) */
% int ancestor; /* Id of ancestor polygon in the full resolution set that was the source of this polygon (-1 if none)
% Now, in the calling code I have to use A(2),A(3),A(5-7), A(8), A(9) from original.
[A,cnt]=fread(fid,8,'int32');
if cnt<8, % This gets triggered by the EOF
return;
end;
ver=bitand(bitshift(A(3),-8),255);
if ver==0, % then its an old version
% This works for version 1.2, but not 1.3.
[A2,cnt2]=fread(fid,1,'int32');
A=[A;A2];
if (cnt+cnt2)==9 & A(9)==3, % we have version 1.3, this would be one of 0,1,65535,65536 in v 1.2
% Read one more byte
A2=fread(fid,1,'int32');
% This is the easiest way not to break existing code.
A(9)=A2; % one of 0,1,65536,65537
end;
%%fprintf('%d ',A(9));
else % a newest versions
level=bitand(A(3),255);
greenwich=bitand(bitshift(A(3),-16),255);
source=bitand(bitshift(A(3),-24),255);
A(3)=level;
A(9)=greenwich*65536;
if ver>=7, % After v2.0 some more bytes around
A2=fread(fid,3,'int32');
end;
end;
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
mu_util.m
|
.m
|
BEHR-core-utils-master/Utils/m_map/private/mu_util.m
| 12,820 |
utf_8
|
be5db1c1bc7465b648f42f12205f8d0d
|
function varargout=mu_util(optn,varargin);
% MU_UTIL Various utility routines
% This function should not be used directly; instead it is
% is accessed by other high- and low-level functions.
% MU_UTIL is basically a driver for a number of lower-level routines collected
% together for convenience. They are specified by the first argument:
% 'clip' - clipping routine
% 'axisticks' - generates a "nice" set of ticks, optimized for degrees/minutes on maps
% angles of the circle.
% 'x/ygrid' - generates the lines for axis grids
% 'xylimits' - finds the x/y limits for a given map
% 'lllimits' - finds the lat/long limits for a given map (usually for rectboxes)
% 'box' - returns a line around the boundaries of the map.
% Rich Pawlowicz ([email protected]) 4/April/97
%
% This software is provided "as is" without warranty of any kind. But
% it's mine, so you can't sell it.
% 31/Mar/04 - added a fix in m_rectgrid that caused problems when a map
% boundary coincided with a grid line.
% 26/Oct/07 - fixed the same problem when it occurred near SOUTH pole!
% 8/Sep/13 - added 'tickstyle' to grid generation
switch optn,
case 'clip',
[varargout{1},varargout{2}]=m_clip(varargin{:});
case 'axisticks',
varargout{1}=m_getinterval(varargin{:});
case {'xgrid','ygrid'}
[varargout{1},varargout{2},varargout{3},varargout{4}]=m_rectgrid(optn,varargin{:});
case 'xylimits',
m_getxylimits;
case 'lllimits',
m_getlllimits;
case 'box',
[varargout{1},varargout{2}]=m_box(varargin{:});
end;
%---------------------------------------------------------
function [Xc,Yc]=m_clip(cliptype,X,Xedge,indx,Y);
% M_CLIP performs clipping of data. Columns of points are
% assumed to be lines; the first points outside the
% clip area are recomputed to lie on the edge of the
% region; others are converted to either NaN or
% edge points depending on CLIPTYPE.
%
% indx = 0 for points inside the clip region, 1
% for those outside
%
% 'on' - replaces points outside with NaN, but interpolates
% to provide points right on the border.
% 'patch' - replaces points outside with nearest border point
% 'point' - does no interpolation (just checks in/out)
%
% In general m_clip will be called 4 times, since it solves a 1-edge problem.
% Rich Pawlowicz ([email protected]) 4/April/97
Xc=X;
Yc=Y;
if ~strcmp(cliptype,'point'),
% Find regions where we suddenly come into the area
% (indices go from 1 to 0)
[i,j]=find(diff(indx)==-1);
if any(i),
I=i+(j-1)*size(X,1); % 1-d addressing
% Linearly interpolate to boundary
bt=(X(I+1)-X(I));
ibt=abs(bt)<5*eps;
if any(ibt), bt(ibt)=1*eps; end; % In these cases the delta(Y) also = 0, so we just want
% to avoid /0 warnings.
Yc(I)=Y(I)+(Xedge-X(I)).*(Y(I+1)-Y(I))./bt;
Yc(I(ibt))=(Y(I(ibt))+Y(I(ibt)+1))/2;
Xc(I)=Xedge;
indx(I(isfinite(Yc(I))))=0;
end;
% Find regions where we suddenly come out of the area
% (indices go from 0 to 1)
[i,j]=find(diff(indx)==1);
if any(i),
I=i+(j-1)*size(X,1);
bt=(X(I+1)-X(I));
ibt=abs(bt)<5*eps;
if any(ibt), bt(ibt)=eps; end; % In these cases the delta(Y) also = 0, so we just want
% to avoid /0 warnings.
Yc(I+1)=Y(I)+(Xedge-X(I)).*(Y(I+1)-Y(I))./bt;
Yc(I(ibt)+1)=(Y(I(ibt))+Y(I(ibt)+1))/2;
Xc(I+1)=Xedge;
indx(I(isfinite(Yc(I+1)))+1)=0;
end;
end;
switch cliptype,
case {'on','point'}
Xc(indx)=NaN;
Yc(indx)=NaN;
case 'patch',
Xc(indx)=Xedge;
end;
%--------------------------------------------------------------------------
function gval=m_getinterval(gmin,gmax,gtick,gtickstyle);
% M_GETINTERVAL picks nice spacing for grid ticks
% This occurs when the following call is made:
% TICKS=M_GRID('axisticks',MIN,MAX,APPROX_NUM_TICKS)
%
% Rich Pawlowicz ([email protected]) 2/Apr/1997
%
% 9/Apr/98 - changed things so that max/min limits are not automatically
% added (this feature made map corners messy sometimes)
% If ticks are specified, we just make sure they are within the limits
% of the map.
if length(gtick)>1,
gval=[gtick(gtick(:)>=gmin & gtick(:)<=gmax)];
% Otherwise, we try to fit approximately gtick ticks in the interval
else
if gtick>2,
exactint=(gmax-gmin)/(gtick-1)*60; %interval in minutes
if strcmp(gtickstyle,'dm'),
% These are the intervals which we will allow (they are "nice" in the sense
% that they come to various even multiples of minutes or degrees)
niceints=[0.1 0.2 0.25 0.5 ...
1 2 3 4 5 6 10 12 15 20 30 ...
60*[1 2 3 4 5 6 8 9 10 12 15 18 20 25 30 40 50 60 100 120 180]];
elseif strcmp(gtickstyle,'dd'),
% these are decimal intervals
niceints=60*[1/500 1/400 1/250 1/200 1/100 ...
1/50 1/40 1/25 1/20 1/10 1/5 1/4 1/3 1/2 ...
1 2 3 4 5 6 8 9 10 12 15 18 20 25 30 40 50 60 100 120 180];
else
error(['bad tickstyle - ''' gtickstyle '''']);
end;
[dun,I]=min(abs(niceints-exactint));
gval=niceints(I)/60*[ceil(gmin*60/niceints(I)):fix(gmax*60/niceints(I))];
gval=[gval(gval>=gmin & gval<=gmax) ];
else
gval=[gmin gmax];
end;
end;
%--------------------------------------------------------------
function [X,Y,vals,labI]=m_rectgrid(direc,Xlims,Ylims,Nx,Ny,label_pos,tickstyle);
% M_RECTGRID This handles some of the computations involved in creating grids
% for rectangular maps. Essentially we make our "first guess" using the
% lat/long limits. Then these curves are clipped to the boundaries, after
% which we use the clip points as "new" boundaries and recompute the lines.
% Rich Pawlowicz ([email protected]) 4/April/97
global MAP_PROJECTION MAP_VAR_LIST
Ny1=Ny-1;
Ny2=Ny*2;
Ny21=Ny2-1;
% First try some wildly oversampled lines (not including the boundaries)
vals=mu_util('axisticks',Xlims(1),Xlims(2),Nx,tickstyle);
if strcmp(MAP_VAR_LIST.rectbox,'on') | strcmp(MAP_VAR_LIST.rectbox,'circle'),
% We don't want the end limits here.
if vals(end) == Xlims(2), vals(end) = []; end
if vals(1) == Xlims(1), vals(1) = []; end
if direc(1)=='x',
[lg,lt]=meshgrid(vals,Ylims(1)+diff(Ylims)*[0:1/Ny1:1]);
else
[lt,lg]=meshgrid(vals,Ylims(1)+diff(Ylims)*[0:1/Ny1:1]);
end;
% But sneakily we clip them in transforming, so we end up with finite values only
% inside the axis limits
[X,Y]=feval(MAP_PROJECTION.routine,'ll2xy',lg,lt,'clip','on');
% Now we find the first/last unclipped values; these will be our correct starting points.
% (Note I am converting to one-dimensional addressing).
istart=sum(cumsum(isfinite(X))==0)+1+[0:size(X,2)-1]*size(X,1);
iend=size(X,1)-sum(cumsum(isfinite(flipud(X)))==0)+[0:size(X,2)-1]*size(X,1);
% Now, in the case where map boundaries coincide with limits it is just possible
% that an entire column might be NaN...so in this case make up something just
% slight non-zero. (31/Mar/04)
i3=find(iend==0);
if any(i3), istart(i3)=1; iend(i3)=1; end;
% do same fix for istart (thanks Ben Raymond for finding this bug)
i3=find(istart>prod(size(X)));
if any(i3), istart(i3)=1; iend(i3)=1; end;
% Now go back and find the lat/longs corresponding to those points; these are our new
% starting points for the lines (Note that the linear interpolation for clipping at boundaries
% means that they will not *quite* be the exact longitudes due to curvature, but they should
% be very close.
if direc(1)=='x',
[lgs,lts]=feval(MAP_PROJECTION.routine,'xy2ll',X(istart),Y(istart),'clip','off');
[lgs,lte]=feval(MAP_PROJECTION.routine,'xy2ll',X(iend),Y(iend),'clip','off');
% Finally compute the lines within those limits (these *may* include some out-of-bounds points
% depending on the geometry of the situation; these are converted to NaN as usual.
[X,Y]=feval(MAP_PROJECTION.routine,'ll2xy',vals(ones(Ny2,1),:),...
lts(ones(Ny2,1),:)+[0:1/Ny21:1]'*(lte-lts),'clip','on');
else
[lgs,lts]=feval(MAP_PROJECTION.routine,'xy2ll',X(istart),Y(istart),'clip','off');
[lge,lts]=feval(MAP_PROJECTION.routine,'xy2ll',X(iend),Y(iend),'clip','off');
% Longitudes should be increasing here, but we can run into wrap problems after
% the tansformations back and forth. It is for this line that I need to make
% long-lims just a tad less than 360 when really they should be 360 (in m_lllimits)
lge(lge<=lgs)=lge(lge<=lgs)+360;
[X,Y]=feval(MAP_PROJECTION.routine,'ll2xy',lgs(ones(Ny2,1),:)+[0:1/Ny21:1]'*(lge-lgs),...
vals(ones(Ny2,1),:),'clip','on');
end;
else
if direc(1)=='x',
[lg,lt]=meshgrid(vals,Ylims(1)+diff(Ylims)*[0:1/Ny1:1]);
else
[lt,lg]=meshgrid(vals,Ylims(1)+diff(Ylims)*[0:1/Ny1:1]);
end;
[X,Y]=feval(MAP_PROJECTION.routine,'ll2xy',lg,lt,'clip','off');
end;
switch label_pos
case {'left','bottom','west','south'}
labI=1;
case 'middle',
labI=round(size(X,1)/2+1/2);
case {'right','top','east','north'}
labI=size(X,1);
end;
%--------------------------------------------------------------------------------
function m_getxylimits;
% M_GET_LIMITS Converts X/Y limits to lat/long limits
% This is a chunk of code that is needed for most projections.
% Rich Pawlowicz ([email protected]) 4/April/97
global MAP_PROJECTION MAP_VAR_LIST
% Start with the user-specified lat/longs.
MAP_VAR_LIST.lats=MAP_VAR_LIST.ulats;
MAP_VAR_LIST.longs=MAP_VAR_LIST.ulongs;
% Now, let's get the map x/ylims
bX=MAP_VAR_LIST.longs(1)+diff(MAP_VAR_LIST.longs)*[0:1/30:1];
bY=MAP_VAR_LIST.lats(1)+diff(MAP_VAR_LIST.lats)*[0:1/30:1];
bX=[bX MAP_VAR_LIST.longs(2*ones(1,31)) fliplr(bX) MAP_VAR_LIST.longs(ones(1,31)) ];
bY=[MAP_VAR_LIST.lats(ones(1,31)) bY MAP_VAR_LIST.lats(2*ones(1,31)) fliplr(bY) ];
[X,Y]=feval(MAP_PROJECTION.routine,'ll2xy',bX,bY,'clip','off');
MAP_VAR_LIST.xlims=[min(X) max(X)];
MAP_VAR_LIST.ylims=[min(Y) max(Y)];
%-------------------------------------------------------------------------------
function m_getlllimits;
% M_GET_LIMITS Converts X/Y limits to lat/long limits
% This is a chunk of code that is needed for most projections.
% Rich Pawlowicz ([email protected]) 4/April/97
global MAP_PROJECTION MAP_VAR_LIST
[bX,bY]=mu_util('box',31);
% Get its lat/longs.
[lg,lt]=feval(MAP_PROJECTION.routine,'xy2ll',bX,bY,'clip','off');
% Take real part because otherwise funny things might happen if the box is very large
MAP_VAR_LIST.lats=[min(real(lt)) max(real(lt))];
% Are the poles within the axis limits? (Test necessary for oblique mercator and azimuthal)
[px,py]=feval(MAP_PROJECTION.routine,'ll2xy',[0 0],[-90 90],'clip','point');
if isfinite(px(1)), MAP_VAR_LIST.lats(1)=-90; end;
if isfinite(px(2)), MAP_VAR_LIST.lats(2)= 90; end;
if any(isfinite(px)),
MAP_VAR_LIST.longs=[-179.9 180]+exp(1); % we add a weird number (exp(1)) to get away from
% anything that might conceivably be desired as a
% boundary - it makes grid generation easier.
% Also make the limits just a little less than 180, this
% is necessary because I have to have the first and last points
% of lines just a little different in order to figure out orientation
% in 'm_rectgrid'
else
MAP_VAR_LIST.longs=[min(lg) max(lg)];
if all(isnan(px)) & diff(MAP_VAR_LIST.longs)>360*30/31,
ii=lg<mean(MAP_VAR_LIST.longs);
lg(ii)=lg(ii)+360;
MAP_VAR_LIST.longs=[min(lg) max(lg)];
end;
end;
%------------------------------------------------------------------------
function [X,Y]=m_box(npts);
% M_BOX Computes coordinates of the map border.
%
% Rich Pawlowicz ([email protected]) 4/April/97
global MAP_PROJECTION MAP_VAR_LIST
n1=npts-1;
switch MAP_VAR_LIST.rectbox,
case 'on',
X=MAP_VAR_LIST.xlims(1)+diff(MAP_VAR_LIST.xlims)*[0:1/n1:1];
Y=MAP_VAR_LIST.ylims(1)+diff(MAP_VAR_LIST.ylims)*[0:1/n1:1];
X=[X MAP_VAR_LIST.xlims(2*ones(1,npts)) fliplr(X) MAP_VAR_LIST.xlims(ones(1,npts))];
Y=[MAP_VAR_LIST.ylims(ones(1,npts)) Y MAP_VAR_LIST.ylims(2*ones(1,npts)) fliplr(Y)];
case 'off',
lg=MAP_VAR_LIST.longs(1)+diff(MAP_VAR_LIST.longs)*[0:1/n1:1];
lg=[lg MAP_VAR_LIST.longs(2*ones(1,npts)) fliplr(lg) MAP_VAR_LIST.longs(ones(1,npts))]';
lt=MAP_VAR_LIST.lats(1)+diff(MAP_VAR_LIST.lats)*[0:1/n1:1];
lt=[MAP_VAR_LIST.lats(ones(1,npts)) lt MAP_VAR_LIST.lats(2*ones(1,npts)) fliplr(lt)]';
[X,Y]=feval(MAP_PROJECTION.routine,'ll2xy',lg,lt,'clip','off');
case 'circle',
n1=npts*3-1;
X=MAP_VAR_LIST.rhomax*cos([0:n1]/n1*pi*2);
Y=MAP_VAR_LIST.rhomax*sin([0:n1]/n1*pi*2);
end;
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
find_wrf_path.m
|
.m
|
BEHR-core-utils-master/Utils/Constants/find_wrf_path.m
| 2,796 |
utf_8
|
7809e1038bdfbb11c945ea575366fefd
|
function [ wrf_path ] = find_wrf_path( region, profile_mode, this_date, varargin )
%FIND_WRF_PATH Returns the path to WRF profiles for the given date
% WRF_PATH = FIND_WRF_PATH( REGION, PROFILE_MODE, THIS_DATE ) Returns the
% proper path to the WRF-Chem profiles as WRF_PATH. Given PROFILE_MODE =
% 'monthly', will just return behr_paths.wrf_monthly_profiles. Given
% PROFILE_MODE = 'daily', it will search all paths defined in the cell
% array behr_paths.wrf_profiles for the year and month subdirectories
% that match THIS_DATE. If it finds one, it will return it. Otherwise, an
% error is thrown. It does not verify that the required wrfout files are
% actually present. THIS_DATE must be either a date number or date string
% implicitly understood by Matlab.
%
% WRF_PATH = FIND_WRF_PATH( REGION, PROFILE_MODE, THIS_DATE, 'fullpath' )
% will include the file corresponding to the given date. Note that it
% offers no guarantee that file exists; it will return the file for the
% exact hour/minute/second requested.
E = JLLErrors;
p = advInputParser;
p.addFlag('fullpath');
p.parse(varargin{:});
pout = p.AdvResults;
find_exact_file = pout.fullpath;
this_date = validate_date(this_date);
if strcmpi(profile_mode, 'monthly')
wrf_path = behr_paths.wrf_monthly_profiles;
if find_exact_file
wrf_path = fullfile(wrf_path, monthly_file_name(this_date));
end
return
elseif strcmpi(profile_mode, 'daily')
yr_str = datestr(this_date, 'yyyy');
mn_str = datestr(this_date, 'mm');
wrf_dirs = behr_paths.wrf_profiles;
for a=1:numel(wrf_dirs)
if ~exist(wrf_dirs{a}, 'dir')
E.dir_dne('The root WRF-Chem profile directory %s does not exist;\n Is the file server mounted?\n Is the directory defined correctly in behr_paths.m?', wrf_dirs{a});
end
wrf_path = fullfile(wrf_dirs{a}, region, yr_str, mn_str);
if exist(wrf_path, 'dir')
if find_exact_file
wrf_path = fullfile(wrf_path, daily_file_name(this_date));
end
return
end
end
% If we've gotten here, we haven't found the directory
E.dir_dne('No WRF-Chem daily output directory exists for %s in region %s', datestr(this_date, 'mmm yyyy'), upper(region));
else
E.badinput('No paths defined for PROFILE_MODE = ''%s''', profile_mode);
end
end
function filename = monthly_file_name(this_date)
filename = sprintf('WRF_BEHR_monthly_%s.nc', datestr(this_date, 'mm'));
end
function filename = daily_file_name(this_date)
% Need to round this_date to the nearest hour
time_component = mod(this_date,1)*24;
this_date = floor(this_date) + round(time_component)/24;
filename = sprintf('wrfout_d01_%s', datestr(this_date, 'yyyy-mm-dd_HH-00-00'));
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
temperature_prof_unit_test.m
|
.m
|
BEHR-core-utils-master/Tests/temperature_prof_unit_test.m
| 2,499 |
utf_8
|
3385cf53eef51962fe4d836fceccaaed
|
function [ success ] = temperature_prof_unit_test( test_data_input_dir )
%TEMPERATURE_PROF_UNIT_TEST Tests rNmcTmp2 against previous output
% SUCCESS = TEMPERATURE_PROF_UNIT_TEST() Reads the file
% "temperature_prof_test_data.mat" from the same directory as this
% function and runs rNmcTmp2 with the latitude, longitude, and month data
% stored in that file. It compares the resulting temperature profiles
% against those stored in that mat file, they must be equal according to
% ISEQUALN() in order for the test to pass. SUCCESS will be true if all
% temperature profiles are equal, false otherwise.
%
% TEMPERATURE_PROF_UNIT_TEST( TEST_DATA_INPUT_DIR ) will generate
% temperature_prof_test_data.mat from the OMI_SP*.mat files found in
% TEST_DATA_INPUT_DIR. I generally recommend that the directory be a unit
% tests data directory in the BEHR-core repository, since those have a
% good selection of days.
save_dir = fileparts(mfilename('fullpath'));
save_file = fullfile(save_dir, 'temperature_prof_test_data.mat');
if exist('test_data_input_dir', 'var')
make_test_data(test_data_input_dir, save_file);
else
success = run_test(save_file);
end
end
function make_test_data(data_dir, save_file)
F = dirff(fullfile(data_dir, 'OMI_SP*.mat'));
n = min(5, numel(F)); % limit to 5 files to keep the test data to something we can store on GitHub (< 100 MB)
lon = cell(n,1);
lat = cell(n,1);
mon = cell(n,1);
temp = cell(n,1);
id_str = sprintf('Produced from %d files:\n\t%s', numel(F), strjoin({F.name},'\n\t')); %#ok<NASGU>
fileTmp = fullfile(behr_paths.amf_tools_dir,'nmcTmpYr.txt');
for a=1:n
fprintf('Calculating temperatures for file %d of %d\n', a, n);
D = load(F(a).name);
Data = D.Data;
lon{a} = cat_sat_data(Data, 'Longitude');
lat{a} = cat_sat_data(Data, 'Latitude');
mon{a} = repmat(month(Data(1).Date), size(lon{a})); % each file is one day, so the month had better be the same for each orbit
temp{a} = rNmcTmp2(fileTmp, behr_pres_levels, lon{a}, lat{a}, mon{a});
end
save(save_file, 'id_str', 'lon', 'lat', 'mon', 'temp');
end
function success = run_test(data_file)
D = load(data_file);
fileTmp = fullfile(behr_paths.amf_tools_dir,'nmcTmpYr.txt');
success = true;
for a=1:numel(D.lon)
fprintf('Testing day %d of %d\n', a, numel(D.lon));
test_temp = rNmcTmp2(fileTmp, behr_pres_levels, D.lon{a}, D.lat{a}, D.mon{a});
if ~isequaln(test_temp, D.temp{a})
success = false;
return
end
end
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
check_myd06_files.m
|
.m
|
BEHR-core-utils-master/Downloading/check_myd06_files.m
| 1,412 |
utf_8
|
7338823c858168e63c52820a1c5fa917
|
function check_myd06_files
% CHECK_MYD06_FILES Checks which MODIS cloud files cannot be opened
%
% I've been having trouble with certain MODIS cloud files being corrupted and
% unopenable using MATLAB's hdfinfo command, so this function will go through
% all the MYD06 files, try to open them, and if that fails, write them out to a
% file in the home directory.
%
% Josh Laughner <[email protected]> 16 Aug 2015
moddir = '/mnt/sat/SAT/MODIS/MYD06_L2/';
startyear = 2011;
startday = 248;
firsttime = true;
fid = fopen('~/bad_myd06.txt','w');
cleanupObj = onCleanup(@() closeFile(fid));
D = dir(fullfile(moddir,'20*'));
for a=1:numel(D)
yr = D(a).name;
if str2double(yr) < startyear
continue
end
fprintf('Now checking folder %s\n',yr);
F = dir(fullfile(moddir,yr,'*.hdf'));
for b=1:numel(F)
if str2double(F(b).name(15:17)) < startday && firsttime
continue
end
firsttime = false;
fprintf('\tFile = %s\n',F(b).name);
try
hdfinfo(fullfile(moddir,yr,F(b).name));
catch err
% if strcmpi(err.identifier, 'MATLAB:imagesci:validate:fileOpen')
fprintf('\t%s bad, saving\n',F(b).name);
fprintf(fid, 'MYD06_L2/%s/%s\n', yr, F(b).name);
% else
% rethrow(err)
% end
end
end
end
end
function closeFile(fid)
fclose(fid);
end
|
github
|
CohenBerkeleyLab/BEHR-core-utils-master
|
rNmcTmp2.m
|
.m
|
BEHR-core-utils-master/AMF_tools/rNmcTmp2.m
| 2,924 |
utf_8
|
06c0a3f86e9770b545c4e816c66977ac
|
%%rNmcTmp2
%%arr 07/23/2008
%..........................................................................
% Returns vector of temperatures on input pressure grid,
% for nearest longitude and latitude in geographic grid
%
% New, simplified version (without write capability) that
% also interpolates profile onto input pressure grid (2008-05-30)
%
% Inputs:
% fileTmp = Complete directory/filename of temperature file
% pressure = vector of pressures (hPa) monotonically decreasing
% lon and lat are scalars (deg)
%
% Outputs (optional: Return these to avoid having to re-read fileTmp on each call):
% presSAVE = pressure grid (vector) from fileTmp (hPA)
% lonSAVE = vector of longitudes from fileTmp (deg)
% latSAVE = vector of latitudes from fileTmp (deg)
% monSAVE = vector of month numbers
% tmpSAVE = large array of temperatures from fileTmp
%
%..........................................................................
function [temperature, tmpSAVE] = rNmcTmp2(fileTmp, pressure, lon, lat, mon)
% Longitude in the temperature profile file is defined as degrees east of
% 0, so -90 in OMI data == 270 here, while +90 in OMI data == +90 here.
lon=mod(lon,360);
if any(diff(pressure) > 0);
E.badinput('pressure must be a monotonically decreasing vector of pressures');
else
if exist('tmpSAVE','var')==0;
fid = fopen(fileTmp,'r');
header = fgets(fid);
nPres = fscanf(fid,'%g',[1 1]);
LON = fscanf(fid,'%g',[1 3]);
nLon = LON(1); lonStart = LON(2); lonEnd = LON(3);
LAT = fscanf(fid,'%g',[1 3]);
nLat = LAT(1); latStart = LAT(2); latEnd = LAT(3);
MON = fscanf(fid,'%g',[1 3]);
nMon = MON(1); monStart = MON(2); monEnd = MON(3);
presSAVE = zeros(nPres,1); %pressure grid
presSAVE = fscanf(fid,'%g',[1 18]);
tmpSAVE = zeros(nPres, nLon, nLat, nMon); %temperature array
tmpSAVE_vec = fscanf(fid,'%g',inf);
tmpSAVE = reshape(tmpSAVE_vec, [nPres nLon nLat nMon]);
lonSAVE = lonStart + ((0:nLon-1) + 0.5) * (lonEnd - lonStart) ./ nLon; %%GOOD
latSAVE = latStart + ((0:nLat-1) + 0.5) * (latEnd - latStart) ./ nLat; %%GOOD
monSAVE = monStart + ((0:nMon-1) + 0) * (monEnd - monStart) ./ nMon;
end
%Interpolate onto input pressure grid
temperature_interp_horiz = nan([numel(presSAVE), size(lon)]);
for pres_i=1:length(presSAVE)
temperature_slice = reshape(tmpSAVE(pres_i,:,:,:), [nLon, nLat, nMon]);
temperature_interp_horiz(pres_i,:,:)=(interpn(lonSAVE, latSAVE, monSAVE, temperature_slice, lon, lat, mon,'linear'));
end
temperature=exp(interp1(log(presSAVE),log(temperature_interp_horiz), log(pressure),'linear','extrap'));
end
status = fclose(fid);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.