text stringlengths 8 6.12M |
|---|
function [p_f, p_a] = find_peaks(freq,amp)
% [p_f(k), p_a(k)] = find_peaks(freq(n),amp(n))
%
% Select local maximums on fft output, find correct frequencies
% and amplitudes using three nearest points quadratic fit.
%
% -- slazav, feb 2012.
mm=1;
p_f = 0;
p_a = 0;
for (m=2:length(freq)-1)
% fit amp(freq) near maximum by Ax^2+Bx+C.
f1 = freq(m-1);
f2 = freq(m);
f3 = freq(m+1);
a1 = amp(m-1);
a2 = amp(m);
a3 = amp(m+1);
if (a2<a1) || (a2<=a3); continue; end
AA = ((a2-a1)/(f2-f1)-(a3-a1)/(f3-f1))/...
((f2^2-f1^2)/(f2-f1)-(f3^2-f1^2)/(f3-f1));
BB = (a2-a1)/(f2-f1) - AA*(f2^2-f1^2)/(f2-f1);
CC = a1 - AA * f1^2 - BB * f1;
f0 = -BB/2.0/AA;
a0 = AA*f0^2 + BB*f0 + CC;
p_f(mm) = f0;
p_a(mm) = a0;
mm=mm+1;
end
end
|
%
% Nilsson's sequence score for puzzle T
%
function nilsson = trees_nls(T)
% Picking up puzzle tiles in clockwise order from a given puzzle T
Ns = [T(1,:) T(2,3) T(3,3:-1:1) T(2,1)]; % 1D array for 8 tiles
% The right sequence of tiles in Ns is: 1 2 3 4 5 6 7 8
% That is: Ns(2)-Ns(1) = 1, Ns(3)-Ns(2) = 1, …, Ns(8) - Ns(7)
% Add 2 for each tile which follows in a wrong sequence
nilsson = 0;
for i = 2:8
if Ns(i) - Ns(i - 1) ~= 1
nilsson = nilsson + 2;
end
end
% Add 1 if the centre is not empty
if T(2,2) ~= 0
nilsson = nilsson + 1;
end
return |
clear all;
Image=imread('watermarked_image.tif');
% initialization of the watermark sequence to be extracted from each sub-band.
watermark_H3=[];
watermark_V3=[];
watermark_D3=[];
watermark_A3=[];
load key_file; % now Matlab knows a variable named 'key' containing the locations at which the watermark will be embedded
%********************* DWT transform
[A1,H1,V1,D1] = dwt2(double(Image),'haar','mode','per'); % four sub-bands in the first decomposition
[A2,H2,V2,D2] = dwt2(double(A1),'haar','mode','per'); % second decomposition
[A3,H3,V3,D3] = dwt2(double(A2),'haar','mode','per'); % Third decomposition
% Embed the watermark in A3
% Each coefficient is identified by its location from key. Remember that key is a
% matrix of size 8x2 containing the coordinates (row number and column number) for each of the eight coefficients
% Loop 'for' can be used.
Quantization_step=30;
for i=1:8,% there are 8 coefficients to embed 8 bits in A3
%Now get the location of the coeffficient to hold one bit
row_number=key(i,1); column_number=key(i,2);
% get each wavelet coefficient in A3.
coefficient_A3=A3(row_number,column_number);
% Apply the extraction equation for each coefficient.
Q_coefficient_A3=round(coefficient_A3/Quantization_step); % quantization
if mod(Q_coefficient_A3,2)==0, % get the watermark bit. If the quantized coefficient is even, then watermark bit is 0
watermark_A3=[watermark_A3,0];
else
watermark_A3=[watermark_A3,1]; % If the quantized coefficient is odd, then watermark bit is 1
end
end
disp('extracted watermark in A3: '),watermark_A3 |
function sol = mysvmAll()
k=9
%k = 6;
%tag = 'nopartial-';
tag = '';
timefile=[int2str(k),'-features-',tag,'training-time','.txt'];
% for ii=2:2
% myfun = @()mysvm(ii);
% t = timeit(myfun);
% dlmwrite(timefile,[ii, t],'-append','delimiter',' ','precision','%.4f');
% end
for ii=2:8
tic;
display(tic);
mysvm(ii);
toc;
display(toc);
dlmwrite(timefile,[ii, toc],'-append','delimiter',' ','precision','%.4f');
end
end
|
%m_LU([1 1 -3 4; 6 4 -6 2; 3 -6 4 1; -6 3 3 4],[1;-2;8;4])
% Método de descomposición LU
% A debe ser una matriz cuadrada mxn, o sea m=n (m filas, n columnas)
% Esta función nos devolverá los valores de x, al ingresar una matriz A
% b es un vector columna, que corresponde al resultado del producto Ax
function [x] = m_LU(A,b)
clc
format short
[n,n] = size (A);
% Esto nos ayudará, para que podamos trabajar
% con distintos tamaños de matriz, por lo cual,
% es importante conocer el tamaño de A
for k = 1:n
L (k,k) = 1;
for i = k+1:n
L (i,k) = A(i,k) / A(k,k);
for j = k+1:n
A(i,j) = A(i,j) - L(i,k)*A(k,j);
end
end
for j=k:n
U(k,j) = A (k,j);
end
end
y = inv(L)*b; % Valor auxiliar para encontrar valores de x
x = inv(U)*y;
L
U
fprintf('Los valores para x son:')
|
function varargout = ManualPick(varargin)
% MANUALPICK MATLAB code for ManualPick.fig
% MANUALPICK, by itself, creates a new MANUALPICK or raises the existing
% singleton*.
%
% H = MANUALPICK returns the handle to a new MANUALPICK or the handle to
% the existing singleton*.
%
% MANUALPICK('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MANUALPICK.M with the given input arguments.
%
% MANUALPICK('Property','Value',...) creates a new MANUALPICK or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before ManualPick_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to ManualPick_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Coded by Stephen Zhang
% Edit the above text to modify the response to help ManualPick
% Last Modified by GUIDE v2.5 10-Feb-2014 22:00:14
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @ManualPick_OpeningFcn, ...
'gui_OutputFcn', @ManualPick_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before ManualPick is made visible.
function ManualPick_OpeningFcn(hObject, ~, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to ManualPick (see VARARGIN)
% Choose default command line output for ManualPick
handles.output = hObject;
YesNo = evalin('base','exist(''ica_segments'',''var'')');
if YesNo==1
handles.ica_segments=evalin('base','ica_segments');
%handles.segcentroid=evalin('base','segcentroid');
handles.fn=evalin('base','fn');
handles.totalfilters=size(handles.ica_segments,1);
sampleim=mat2gray(imread(handles.fn,1));
else
msgbox('Please make sure CellSort data are loaded to workspace','Need data to initiate');
end
% Set the range of display
handles.maxpixel = double(0.9 * max(sampleim(:)));
% Set the strengths of red and blue colors
handles.maxpixelmod = 1;
YesNo = evalin('base','exist(''pass_or_fail'',''var'')');
if YesNo==1
handles.pass_or_fail=evalin('base','pass_or_fail');
else
handles.pass_or_fail=zeros(handles.totalfilters,2);
handles.pass_or_fail(:,1)=1:handles.totalfilters;
end
handles.filtertoshow=repmat(sampleim,[1,1,3]);
handles.allfilters=handles.filtertoshow;
handles.filtertoshow(:,:,3)=0;
handles.allfilters(:,:,3)=squeeze(sum(handles.ica_segments>0,1))*handles.maxpixel * handles.maxpixelmod;
handles.filterindex=1;
handles.overlapcleared=0;
set(handles.text1,'String',handles.fn);
set(handles.filterslider,'Max',handles.totalfilters);
set(handles.filterslider,'SliderStep',[1/handles.totalfilters,0.1]);
txtspaceholder = repmat({' '}, handles.totalfilters, 1);
handles.txtspaceholder=txtspaceholder;
set(handles.edit1,'String',[num2str(handles.filterindex),'/',num2str(handles.totalfilters)]);
handles.filtertoshow(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
handles.allfilters(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
imshow(handles.filtertoshow, 'Parent', handles.axes1)
imshow(handles.allfilters, 'Parent', handles.axes2)
set(handles.listbox1,'String',strcat(num2str(handles.pass_or_fail(:,1)),txtspaceholder,num2str(handles.pass_or_fail(:,2))));
handles.checked=0;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes ManualPick wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = ManualPick_OutputFcn(~, ~, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in pushbuttonpass.
function pushbuttonpass_Callback(hObject, ~, handles)
% hObject handle to pushbuttonpass (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.pass_or_fail(handles.filterindex,2)=2;
currentfilter=squeeze(handles.ica_segments(handles.filterindex,:,:)>0);
pastfilters=handles.filtertoshow(:,:,3)>0;
handles.pastfilters=(currentfilter+pastfilters)>0;
handles.filtertoshow(:,:,3)=handles.maxpixel * handles.maxpixelmod*handles.pastfilters;
if handles.filterindex~=handles.totalfilters
handles.filterindex=handles.filterindex+1;
else
undone=sum(handles.pass_or_fail(:,2)==0);
if undone <=0
msgbox('Scoring is complete','Complete')
set(handles.text1,'String',[handles.fn,' - complete']);
else
msgbox([num2str(undone),' to go.'],'Incomplete')
end
end
handles.filtertoshow(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
handles.allfilters(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
imshow(handles.filtertoshow, 'Parent', handles.axes1)
imshow(handles.allfilters, 'Parent', handles.axes2)
set(handles.edit1,'String',[num2str(handles.filterindex),'/',num2str(handles.totalfilters)]);
set(handles.filterslider,'Value',handles.filterindex);
assignin('base', 'pass_or_fail', handles.pass_or_fail);
set(handles.listbox1,'String',strcat(num2str(handles.pass_or_fail(:,1)),handles.txtspaceholder,num2str(handles.pass_or_fail(:,2))));
set(handles.listbox1,'Value',handles.filterindex);
set( handles.pushbuttonpass, 'Enable', 'off');
drawnow;
set( handles.pushbuttonpass, 'Enable', 'on');
guidata(hObject, handles);
% --- Executes on button press in pushbuttonfail.
function pushbuttonfail_Callback(hObject, ~, handles)
% hObject handle to pushbuttonfail (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.pass_or_fail(handles.filterindex,2)=1;
if handles.filterindex~=handles.totalfilters
handles.filterindex=handles.filterindex+1;
else
undone=sum(handles.pass_or_fail(:,2)==0);
if undone <=0
msgbox('Scoring is complete','Complete')
set(handles.text1,'String',[handles.fn,' - complete']);
else
msgbox([num2str(undone),' to go.'],'Incomplete')
end
end
handles.filtertoshow(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
handles.allfilters(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
imshow(handles.filtertoshow, 'Parent', handles.axes1)
imshow(handles.allfilters, 'Parent', handles.axes2)
set(handles.edit1,'String',[num2str(handles.filterindex),'/',num2str(handles.totalfilters)]);
set(handles.filterslider,'Value',handles.filterindex);
assignin('base', 'pass_or_fail', handles.pass_or_fail);
set(handles.listbox1,'String',strcat(num2str(handles.pass_or_fail(:,1)),handles.txtspaceholder,num2str(handles.pass_or_fail(:,2))));
set(handles.listbox1,'Value',handles.filterindex);
set( handles.pushbuttonfail, 'Enable', 'off');
drawnow;
set( handles.pushbuttonfail, 'Enable', 'on');
guidata(hObject, handles);
% --- Executes on button press in pushbuttonexit.
function pushbuttonexit_Callback(~, ~, ~)
% hObject handle to pushbuttonexit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(gcf)
function edit1_Callback(~, ~, ~)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, ~, ~)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on slider movement.
function filterslider_Callback(hObject, ~, handles)
% hObject handle to filterslider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.filterindex=round(get(hObject,'Value'));
handles.filtertoshow(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
handles.allfilters(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
imshow(handles.filtertoshow, 'Parent', handles.axes1)
imshow(handles.allfilters, 'Parent', handles.axes2)
set(handles.edit1,'String',[num2str(handles.filterindex),'/',num2str(handles.totalfilters)]);
set(handles.listbox1,'Value',handles.filterindex);
set( handles.filterslider, 'Enable', 'off');
drawnow;
set( handles.filterslider, 'Enable', 'on');
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function filterslider_CreateFcn(hObject, ~, ~)
% hObject handle to filterslider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, ~, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
handles.filterindex=get(handles.listbox1,'Value');
handles.filtertoshow(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
handles.allfilters(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
imshow(handles.filtertoshow, 'Parent', handles.axes1)
imshow(handles.allfilters, 'Parent', handles.axes2)
set(handles.edit1,'String',[num2str(handles.filterindex),'/',num2str(handles.totalfilters)]);
set(handles.filterslider,'Value',handles.filterindex);
set( handles.listbox1, 'Enable', 'off');
drawnow;
set( handles.listbox1, 'Enable', 'on');
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, ~, ~)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbuttonclear.
function pushbuttonclear_Callback(hObject, ~, handles)
% hObject handle to pushbuttonclear (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.pass_or_fail=zeros(handles.totalfilters,2);
handles.pass_or_fail(:,1)=1:handles.totalfilters;
handles.filterindex=1;
set(handles.edit1,'String',[num2str(handles.filterindex),'/',num2str(handles.totalfilters)]);
set(handles.filterslider,'Value',handles.filterindex);
set(handles.listbox1,'String',strcat(num2str(handles.pass_or_fail(:,1)),handles.txtspaceholder,num2str(handles.pass_or_fail(:,2))));
set(handles.listbox1,'Value',handles.filterindex);
assignin('base', 'pass_or_fail', handles.pass_or_fail);
handles.pastfilters=0;
handles.filtertoshow(:,:,3)=handles.pastfilters;
imshow(handles.filtertoshow, 'Parent', handles.axes1)
set( handles.pushbuttonclear, 'Enable', 'off');
drawnow;
set( handles.pushbuttonclear, 'Enable', 'on');
guidata(hObject, handles);
% --- Executes on button press in pushbuttoncheck.
function pushbuttoncheck_Callback(hObject, ~, handles)
% hObject handle to pushbuttoncheck (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
undone=sum(handles.pass_or_fail(:,2)==0);
if undone <=0
set(handles.text1,'String',[handles.fn,' - complete']);
pass_filter_numbers=handles.pass_or_fail(handles.pass_or_fail(:,2)==2,1);
if handles.overlapcleared<1
real_ica_segments=handles.ica_segments(pass_filter_numbers,:,:);
handles.real_ica_segments=weirdmatrearrange3(real_ica_segments);
end
handles.finalfilters=handles.allfilters;
handles.finalfilters(:,:,3)=0;
handles.finalfilters(:,:,1)=squeeze(sum(handles.real_ica_segments>0,3))*100;
imshow(handles.finalfilters, 'Parent', handles.axes1)
set(handles.pushbuttonoverlap,'Enable','on')
set(handles.pushbuttongen,'Enable','on')
handles.checked=1;
else
msgbox([num2str(undone),' to go.'],'Incomplete')
end
set( handles.pushbuttoncheck, 'Enable', 'off');
drawnow;
set( handles.pushbuttoncheck, 'Enable', 'on');
guidata(hObject, handles)
% --- Executes on button press in pushbuttonoverlap.
function pushbuttonoverlap_Callback(hObject, ~, handles)
% hObject handle to pushbuttonoverlap (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
overlappixels=squeeze(sum(handles.real_ica_segments>0,3))>1;
for i=1:size(handles.real_ica_segments,3)
temp_ica_seg=squeeze(handles.real_ica_segments(:,:,i));
temp_ica_seg(overlappixels)=0;
handles.real_ica_segments(:,:,i)=temp_ica_seg;
end
handles.finalfilters(:,:,1)=squeeze(sum(handles.real_ica_segments>0,3))*100;
imshow(handles.finalfilters, 'Parent', handles.axes1)
handles.overlapcleared=1;
set( handles.pushbuttonoverlap, 'Enable', 'off');
drawnow;
set( handles.pushbuttonoverlap, 'Enable', 'on');
guidata(hObject, handles)
% --- Executes on button press in pushbuttongen.
function pushbuttongen_Callback(~, ~, handles)
% hObject handle to pushbuttongen (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
real_ica_segments=handles.real_ica_segments>0;
real_ica_segments2=real_ica_segments;
% real_ica_count=1;
% for i=1:size(real_ica_segments,3)
% [labeled_objects,num_of_objects]=bwlabel(real_ica_segments(:,:,i),4);
% if num_of_objects>1
%
% for j=1:num_of_objects
% real_ica_segments2(:,:,real_ica_count)=labeled_objects==j;
% real_ica_count=real_ica_count+1;
% end
% elseif num_of_objects==1
% real_ica_segments2(:,:,real_ica_count)=labeled_objects>0;
% real_ica_count=real_ica_count+1;
% end
% end
set( handles.pushbuttongen, 'Enable', 'off');
drawnow;
set( handles.pushbuttongen, 'Enable', 'on');
assignin('base', 'real_ica_segments', real_ica_segments2);
% --- Executes on button press in pushbuttoncut.
function pushbuttoncut_Callback(hObject, ~, handles)
% hObject handle to pushbuttoncut (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
cutpixels=getlinepixels(handles.filtertoshow,0);
currentfilter=squeeze(handles.ica_segments(handles.filterindex,:,:)>0);
currentfilter(cutpixels>0)=0;
handles.ica_segments(handles.filterindex,:,:)=currentfilter;
handles.filtertoshow(:,:,1)=handles.maxpixel * handles.maxpixelmod*(handles.ica_segments(handles.filterindex,:,:)>0);
imshow(handles.filtertoshow, 'Parent', handles.axes1)
set( handles.pushbuttoncut, 'Enable', 'off');
drawnow;
set( handles.pushbuttoncut, 'Enable', 'on');
guidata(hObject, handles)
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata structure with the following fields (see FIGURE)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
switch eventdata.Key
case 'd'
pushbuttonpass_Callback(hObject, [], handles);
case 'f'
pushbuttonfail_Callback(hObject, [], handles);
case 's'
pushbuttoncut_Callback(hObject, [], handles);
case 'c'
pushbuttoncheck_Callback(hObject, [], handles);
case 'e'
if handles.checked==1
pushbuttonoverlap_Callback(hObject, [], handles);
end
case 'g'
if handles.checked==1
pushbuttongen_Callback([], [], handles)
end
case 'p'
pushbuttonclear_Callback(hObject, [], handles) % Ctrl+c
case 'a'
pushbuttonexit_Callback([], [], []) %Ctrl+e
end
|
function [ qref ] = motionplan_with_rep( q0,qf,t1,t2,myrobot,obs,accur )
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
q = q0;
q_temp = q0;
while (norm(q_temp(end,1:5)-qf(end,1:5))>accur)
q_temp = q_temp + 0.01*att(q_temp,qf,myrobot) + 0.01*rep(q_temp,myrobot,obs);
q = vertcat(q,q_temp);
t = linspace(t1,t2,size(q,1));
qref = spline(t,q');
end
|
% drug_struct = [sch20, sch50, skf20, skf50];
function plot_attend_svm( drug_struct )
figure()
for i = 1:4
ctrl_vec = [1 3 5 7];
drug_vec = [2 4 6 8];
ctrl_unscram = [drug_struct.avg_perc_corr];
ctrl_unscram = ctrl_unscram( ctrl_vec(i) );
ctrl_scram = [drug_struct.avg_scrambled_perc_corr];
ctrl_scram = ctrl_scram( ctrl_vec(i) );
ctrl_perc_corr = [ctrl_unscram ctrl_scram];
drug_unscram = [drug_struct.avg_perc_corr];
drug_unscram = drug_unscram( drug_vec(i) );
drug_scram = [drug_struct.avg_scrambled_perc_corr];
drug_scram = drug_scram( drug_vec(i) );
drug_perc_corr = [drug_unscram drug_scram];
subplot( 1,4,i);
hold on;
bar([ctrl_perc_corr; drug_perc_corr] * 100);
%xlabel( 'Contrast' );
TickLabel_FontSize = 12;
ylabel( 'Classifier Performance (% Correct)' );
set( gca, 'YTick', [40 50 60 70], 'XTick', [1, 2], 'XTickLabel', {'Control', 'Drug'}, 'FontSize', TickLabel_FontSize, ...
'FontWeight', 'Bold' );
xlim([0 3]);
ylim([40 70] );
box( gca, 'off');
hold off;
end
end |
% openStreamingFile( fileName, open )
% fileName - file name to save data
% open - 1 = open, 0 = close
function openStreamingFile( fileName, open )
global DMBufferSizePV
rootPath = [getSMuRFenv('SMURF_EPICS_ROOT')]
C = strsplit(rootPath, ':');
root = C{1};
C1 = strsplit(fileName, '/');
if length(C1) == 1
currentFolder = pwd;
fullPath = [currentFolder, '/', fileName];
else
fullPath = fileName;
end
if open
disp('Setting file name...')
% must write full array here
charArray = double(fullPath);
writeData = zeros(1,300);
writeData(1:length(charArray)) = charArray;
lcaPut([root, ':AMCc:streamingInterface:dataFile'], writeData)
disp(['Opening file...',fullPath])
lcaPut([root, ':AMCc:streamingInterface:open'], 'True')
else
disp(['Closing file...',fullPath])
lcaPut([root, ':AMCc:streamingInterface:open'], 'False')
end
|
% Script: Esfera
% Juan P Aguilera 136078
% Luis M Román 117077
% Madeleine León 125154
%------------------------------------------
clear all; close all; clc;
fname = 'funelectron';
funh = 'funesfera';
%------------------------------------------
% Almacenamos los resultados para la comparación
maxiter = 500; % Número máximo de iteraciones.
resfmincon = zeros(5,4);
respscg = zeros(5,5);
%------------------------------------------
% Iteración
for np = 10:10:50
% Puntos aleatorios
x0 = rand(3*np,1);
% Evaluamos desempeño de fmincon (optimizador
% con restricciónes interno de MATLAB)
tic
[~,fval,~,output,~,~]=fmincon(@funelectron,x0,[],[],...
[],[],[],[],@funesfera2);
time = toc;
resfmincon(np/10,1) = np;
resfmincon(np/10,2) = output.firstorderopt;
resfmincon(np/10,3) = fval;
resfmincon(np/10,4) = time;
%------------------------------------------
% Evaluamos desemepeño de nuestro optimizador
tic
[x,fval,iter,lambda, fin] = pscglobal(fname, funh, x0, maxiter);
time = toc;
respscg(np/10,1) = np;
respscg(np/10,2) = fin;
respscg(np/10,3) = fval;
respscg(np/10,4) = time;
respscg(np/10,5) = iter;
end
%------------------------------------------
% Imprimimos resultados fmincon
fprintf(1,' no. puntos \t ||L aum|| \t f(x) \t time \n')
fprintf(1,' %2.0f \t %2.8f \t %3.2f \t %3.2f \n', resfmincon')
fprintf(1,'\n\n')
%------------------------------------------
% Imprimimos resultados de nuestro optimizador
fprintf(1,'| no. puntos \t ||L aum|| \t f(x) \t time \t iter \n')
fprintf(1,'| %2.0f \t %2.8f \t %3.2f \t %3.2f \t %2f \n', respscg')
%------------------------------------------
% Grafícamos resultados para la última iteración
figure
sphere(50);
axis equal
hold on
for j=1:np
plot3(x(3 * (j - 1) + 1),x(3 * (j - 1) + 2),x(3 * (j - 1) + 3), 'sk', 'LineWidth', 6);
end
|
function [Acmm,hG,IG,vG,Acmm_dot,Sys_h,i_V_i,Jc_dot] = DynFun_Centroidal_Momentum_Matrix(RobotLinks,RobotParam,RobotFrame,q,dq)
NB = RobotParam.NB;
O_X_G = STconstructor_SpatialTransform(eye(3),-RobotFrame.O_p_COM);
i_X_G = RobotFrame.i_X_O*O_X_G;
% %Selection Matrix
% Selection = [ones(6) zeros(6) zeros(6);
% zeros(6) ones(6) zeros(6);
% zeros(6) zeros(6) ones(6)];
% i_Ic_i = (RobotFrame.P_dual*RobotParam.i_DI_i*RobotFrame.P).*Selection;
% IG = O_X_G'*i_Ic_i(1:6,1:6)*O_X_G;
% Acmm = (i_X_G)' * i_Ic_i*RobotFrame.S;
Acmm = (i_X_G)' * RobotParam.i_DI_i*RobotFrame.Ji;
hG1 = Acmm*dq;
IG = i_X_G'*RobotParam.i_DI_i*i_X_G;
vG = (IG)\hG1;
%Calculate velocities for Acmm_dot
i_V_G = i_X_G*vG;
i_V_i = RobotFrame.Ji*dq;
i_Vx_i = eye(6*NB);
i_Vxdual_i = eye(6*NB);
i_Vx_G = eye(6*NB);
spots = @(i) [6*i-5:6*i];
for i = 1:NB
i_Vx_i(spots(i),spots(i)) = STfun_SpatialCross(i_V_i(spots(i),:));
i_Vxdual_i(spots(i),spots(i)) = STfun_SpatialCross_dual(i_V_i(spots(i),:));
i_Vx_G(spots(i),spots(i)) = STfun_SpatialCross(i_V_G(spots(i),:));
end
% Acmm_dot = (i_Vx_G*i_X_G)'*RobotParam.i_DI_i*RobotFrame.Ji + ...
% (i_X_G)'*RobotParam.i_DI_i*RobotFrame.P*i_Vx_i*RobotFrame.S;
Acmm_dot = (i_X_G)'*i_Vxdual_i*RobotParam.i_DI_i*RobotFrame.Ji + ...
(i_X_G)'*RobotParam.i_DI_i*RobotFrame.P*i_Vx_i*RobotFrame.S;
Sys_h = RobotParam.i_DI_i*i_V_i;
hG = i_X_G'*Sys_h;
% Jc_dot = 0;
% Jc_dot = RobotFrame.ZIc*RobotFrame.O_DX_i*i_Vx_i*RobotFrame.i_DX_ci*RobotFrame.ZIc';
i_Vcx_i = zeros(6*RobotParam.c,6*RobotParam.c);
for c = 1:RobotParam.c
ic = RobotParam.ic(c);
spots_ic = [6*ic-5:6*ic];
spots_c = [6*c-5:6*c];
i_Vcx_i(spots_c,spots_c) = i_Vx_i(spots_ic,spots_ic);
end
Jc_dot = RobotFrame.ZIc*RobotFrame.O_DX_ci*( i_Vcx_i*RobotFrame.ci_DX_i*RobotFrame.P + RobotFrame.ci_DX_i*RobotFrame.P*i_Vx_i)*RobotFrame.S;
end |
function [icl opl ipl] = segmentInnerLayersLin(bscan, Params, onh, rpe, infl, medline, bv)
% SEGMENtONFLAUTO Segments some inner retinal layers from a BScan.
% Intended for use on
% circular OCT B-Scans.
% BSCAN: Unnormed BScan image
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PARAMS: Parameter struct for the automated segmentation
% In this function, the following parameters are currently used:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% RPE: Segmentation of the RPE in OCTSEG line format
% INFL: Segmentation of the INFL in OCTSEG line format
%
% The algorithm (of which this function is a part) is described in
% Markus A. Mayer, Joachim Hornegger, Christian Y. Mardin, Ralf P. Tornow:
% Retinal Nerve Fiber Layer Segmentation on FD-OCT Scans of Normal Subjects
% and Glaucoma Patients, Biomedical Optics Express, Vol. 1, Iss. 5,
% 1358-1383 (2010). Note that modifications have been made to the
% algorithm since the paper publication.
%
% Writen by Markus Mayer, Pattern Recognition Lab, University of
% Erlangen-Nuremberg
%
% First final Version: June 2010
% 1) Normalize intensity values and align the image to the RPE
%bscan(bscan > 1) = 0;
%bscan = sqrt(bscan);
rpe = round(rpe);
infl = round(infl);
[alignedBScan flatRPE transformLine] = alignAScans(bscan, Params, [rpe; infl]);
flatINFL = infl - transformLine;
medline = round(medline - transformLine);
alignedBScanDSqrt = sqrt(alignedBScan); % double sqrt for denoising
% 3) Find blood vessels for segmentation and energy-smooth
idxBV = find(extendBloodVessels(bv, Params.INNERLIN_EXTENDBLOODVESSELS_ADDWIDTH, ...
Params.INNERLIN_EXTENDBLOODVESSELS_MULTWIDTHTHRESH, ...
Params.INNERLIN_EXTENDBLOODVESSELS_MULTWIDTH));
averageMask = fspecial('average', Params.INNERLIN_SEGMENT_AVERAGEWIDTH);
alignedBScanDen = imfilter(alignedBScanDSqrt, averageMask, 'symmetric');
idxBVlogic = zeros(1,size(alignedBScan, 2), 'uint8') + 1;
idxBVlogic(idxBV) = idxBVlogic(idxBV) - 1;
idxBVlogic(1) = 1;
idxBVlogic(end) = 1;
idxBVlogicInv = zeros(1,size(alignedBScan, 2), 'uint8') + 1 - idxBVlogic;
alignedBScanWoBV = alignedBScanDen(:, find(idxBVlogic));
alignedBScanInter = alignedBScanDen;
runner = 1:size(alignedBScanDSqrt, 2);
runnerBV = runner(find(idxBVlogic));
for k = 1:size(alignedBScan,1)
alignedBScanInter(k, :) = interp1(runnerBV, alignedBScanWoBV(k,:), runner, 'linear');
end
alignedBScanDSqrt(:, find(idxBVlogicInv)) = alignedBScanInter(:, find(idxBVlogicInv)) ;
averageMask = fspecial('average', Params.INNERLIN_SEGMENT_AVERAGEWIDTH);
alignedBScanDenAvg = imfilter(alignedBScanDSqrt, averageMask, 'symmetric');
% 4) We try to find the CL boundary.
% This is pretty simple - it lies between the medline and the RPE and has
% rising contrast. It is the uppermost rising border.
extrICLChoice = findRetinaExtrema(alignedBScanDenAvg, Params,2, 'max', ...
[medline; flatRPE - Params.INNERLIN_SEGMENT_MINDIST_RPE_ICL]);
extrICL = min(extrICLChoice,[], 1);
extrICL(idxBV) = 0;
extrICL = linesweeter(extrICL, Params.INNERLIN_SEGMENT_LINESWEETER_ICL);
extrICLEstimate = ransacEstimate(extrICL, 'poly', ...
Params.INNERLIN_RANSAC_NORM_BOUNDARIES, ...
Params.INNERLIN_RANSAC_MAXITER, ...
Params.INNERLIN_RANSAC_POLYNUMBER_BOUNDARIES, ...
onh);
extrICL = mergeLines(extrICL, extrICLEstimate, 'discardOutliers', [Params.INNERLIN_MERGE_THRESHOLD ...
Params.INNERLIN_MERGE_DILATE ...
Params.INNERLIN_MERGE_BORDER]);
flatICL = round(extrICL);
% 5) OPL Boundary: In between the ICL and the INFL
oplInnerBound = flatINFL;
extrOPLChoice = findRetinaExtrema(alignedBScanDenAvg, Params,3, 'min', ...
[oplInnerBound; flatICL - Params.INNERLIN_SEGMENT_MINDIST_ICL_OPL]);
extrOPL = max(extrOPLChoice,[], 1);
extrOPL(idxBV) = 0;
extrOPL = linesweeter(extrOPL, Params.INNERLIN_SEGMENT_LINESWEETER_OPL);
extrOPLEstimate = ransacEstimate(extrOPL, 'poly', ...
Params.INNERLIN_RANSAC_NORM_BOUNDARIES, ...
Params.INNERLIN_RANSAC_MAXITER, ...
Params.INNERLIN_RANSAC_POLYNUMBER_BOUNDARIES, ...
onh);
extrOPL = mergeLines(extrOPL, extrOPLEstimate, 'discardOutliers', [Params.INNERLIN_MERGE_THRESHOLD ...
Params.INNERLIN_MERGE_DILATE ...
Params.INNERLIN_MERGE_BORDER]);
flatOPL = round(extrOPL);
% 5) IPL Boundary: In between the OPL and the INFL
iplInnerBound = flatINFL;
extrIPLChoice = findRetinaExtrema(alignedBScanDenAvg, Params,2, 'min pos', ...
[iplInnerBound; flatOPL - Params.INNERLIN_SEGMENT_MINDIST_OPL_IPL]);
extrIPL = extrIPLChoice(2,:);
extrIPL(idxBV) = 0;
extrIPL = linesweeter(extrIPL, Params.INNERLIN_SEGMENT_LINESWEETER_IPL);
extrIPLEstimate = ransacEstimate(extrIPL, 'poly', ...
Params.INNERLIN_RANSAC_NORM_BOUNDARIES, ...
Params.INNERLIN_RANSAC_MAXITER, ...
Params.INNERLIN_RANSAC_POLYNUMBER_BOUNDARIES, ...
onh);
extrIPL = mergeLines(extrIPL, extrIPLEstimate, 'discardOutliers', [Params.INNERLIN_MERGE_THRESHOLD ...
Params.INNERLIN_MERGE_DILATE ...
Params.INNERLIN_MERGE_BORDER]);
% 6) Bring back to non-geometry corrected space
icl = extrICL + transformLine;
opl = extrOPL + transformLine;
ipl = extrIPL + transformLine;
% 7) Some final constraints
icl(icl < 1) = 1;
opl(opl < 1) = 1;
ipl(ipl < 1) = 1;
ipl(ipl < infl) = infl(ipl < infl);
icl(icl > rpe) = rpe(icl > rpe);
opl(opl > icl) = icl(opl > icl);
opl(opl < ipl) = ipl(opl < ipl);
icl(icl < opl) = opl(icl < opl);
end |
%% Stelling 19
%
% De NOT-operator heeft twee vormen:
%
% 1 - Het symbool ~
% 2 - De functie vorm: not()
%
Antwoord = 1;
|
function sub_entrust_checkbox_limitpx(hObject, eventdata, handles)
% 期权交易Table的期权标的选择
% 吴云峰 20170329
global QMS_INSTANCE;
set(hObject, 'Value', true)
% 将代码进行设置
px_infos_ = cell(0, 8);
% 进行代码的扫描
[nT, nK] = size(QMS_INSTANCE.callQuotes_.data);
opt_entrustinfo_ = get(handles.sub_entrust.table_optcode, 'Data');
for t = 1:nT
for k = 1:nK
% Call
optQuote_ = QMS_INSTANCE.callQuotes_.data(t, k);
if optQuote_.is_obj_valid
entrust_amount = opt_entrustinfo_{k, 6*t-3};
if isempty(entrust_amount)
else
entrust_amount = str2double(entrust_amount);
if isnan(entrust_amount)
else
if entrust_amount > 0
entrust_direction = '1';
else
entrust_direction = '2';
end
future_direction = opt_entrustinfo_{k, 6*t-1};
if strcmp(future_direction, '开')
future_direction = '1';
else
future_direction = '2';
end
entrust_amount = abs(entrust_amount);
px_info_ = cell(1, 8);
px_info_{1} = [ '<html><font color=#8B4513>', optQuote_.code, '</font></html>'];
px_info_{2} = 'call';
px_info_{3} = t;
px_info_{4} = optQuote_.K;
px_info_{5} = entrust_direction;
px_info_{6} = future_direction;
px_info_{7} = entrust_amount;
px_info_{8} = '';
px_infos_ = [px_infos_ ; px_info_];
end
end
end
% Put
optQuote_ = QMS_INSTANCE.putQuotes_.data(t, k);
if optQuote_.is_obj_valid
entrust_amount = opt_entrustinfo_{k, 6*t-2};
if isempty(entrust_amount)
else
entrust_amount = str2double(entrust_amount);
if isnan(entrust_amount)
else
if entrust_amount > 0
entrust_direction = '1';
else
entrust_direction = '2';
end
future_direction = opt_entrustinfo_{k, 6*t};
if strcmp(future_direction, '开')
future_direction = '1';
else
future_direction = '2';
end
entrust_amount = abs(entrust_amount);
px_info_ = cell(1, 8);
px_info_{1} = [ '<html><font color=#8B4513>', optQuote_.code, '</font></html>'];
px_info_{2} = 'put';
px_info_{3} = t;
px_info_{4} = optQuote_.K;
px_info_{5} = entrust_direction;
px_info_{6} = future_direction;
px_info_{7} = entrust_amount;
px_info_{8} = '';
px_infos_ = [px_infos_ ; px_info_];
end
end
end
end
end
set(handles.sub_entrust.table_limitprice, 'Data' , px_infos_)
set(handles.sub_entrust.checkbox_mktprice, 'Value', false)
end |
function [labels, centroids] = get_hierarchical_result(input_matrix, n)
tic
labels = clusterdata(input_matrix(:,1:2), 'Linkage', 'centroid', 'MaxClust', n);
toc
distances = zeros(n,1);
centroids = zeros(n,2);
for i = 1:n
centroids(i,1) = mean(input_matrix(labels == i,1));
centroids(i,2) = mean(input_matrix(labels == i,2));
end
disp(labels);
disp(centroids);
%%required for drawing circles in simulator
for i = 1:n
temp = pdist2(centroids(i,1:2), input_matrix(labels == i,1:2));
distances(i) = max(temp);
end
centroids = [centroids, distances];
end
|
clc;
close all;
clear all;
f=imread('wizardofoznoisesquare.pgm');
% compute FFT of the grey image
A = fft2(double(f));
% frequency scaling
A1=fftshift(A);
% Gaussian Filter Response Calculation
[M,N]=size(A); % image size
R=5; % filter radius parameter
X=0:N-1;
Y=0:M-1;
[X,Y]=meshgrid(X,Y);
Cx=0.5*N;
Cy=0.5*M;
%create low pass filter
Lo=exp(-((X-Cx).^2+(Y-Cy).^2)./(2*R).^2);
%create high pass filter
Hi=1-Lo;
% compute filtered image
J=A1.*Lo;
J1=ifftshift(J);
B1=ifft2(J1);
K=A1.*Hi;
K1=ifftshift(K);
B2=ifft2(K1);
%display results
figure(1)
imshow(f);colormap gray
title('Original image','fontsize',14)
figure(2)
imshow(abs(B1),[12 290]), colormap gray
title('Gaussian Low pass','fontsize',14)
figure(3)
imshow(abs(B2),[12 290]), colormap gray
title('Gaussian High pass','fontsize',14)
|
function flagf=oceantidef(blqfile,path)
% Function oceantidef
% ==================
%
%
% Sintaxe
% =======
%
% oceantidef(blqfile)
%
% Input
% =====
%
% blqfile -> BLQ file inputed by the user.
%
%
%
%
% Output
% ======
%
% inputOTL.txt -> input file for the executable hardisp.exe
%
%
% Created/Modified
% ================
%
% When Who What
% ---- --- ----
% 2010/11/17 Carlos Alexandre Garcia Function Created
%
% Comments
% ========
% This routine reads the coefficients from the user BLQ file.
%
% ==============================
% Copyright 2010 University of New Brunswick
% ==============================
%--------------------------------------------------------------------------
blq =fopen(fullfile(path,blqfile),'rt');
lin=fgets(blq);
header='$$ Ocean loading displacement';
flag1 = isequal(strtrim(lin(1:30)), header);
if flag1 ~= 1
fprintf('The user BLQ file is corrupted.\n')
return
end
for i=1:33
lin=fgets(blq);
end
coords='lon/lat:';
flag2 = isequal(strtrim(lin(41:49)), coords);
if flag2 ~= 1
fprintf('The user BLQ file is corrupted.\n')
return
end
fid=fopen(fullfile(path,'inputOTL.txt'), 'w');
for i=1:6
lin=fgets(blq);
fase=lin(1:77);
fprintf(fid, '%s\n', fase);
end
lin=fgets(blq);
endfile='$$ END TABLE';
flagf = isequal(strtrim(lin(1:13)), endfile);
if flagf ~= 1
fprintf('The user BLQ file is corrupted.\n')
else
fprintf('The user BLQ file has been accepted.\n')
end
fclose(fid);
fclose(blq);
end
|
function space = send_stimulus(device, Channels, stimulus)
for channel = 0:Channels - 1
space = device.GetDataQueueSpace(channel);
while space > 1000
% Calc Sin-Wave (16 bits) lower bits will be removed according resolution
sinVal = 30000 * sin(2.0 * (1:5000) * pi / 5000 * (channel + 1));
unit = [linspace(300000, 300000, 5000) 0];
zeroVal = 0*(1:1000);
data = NET.convertArray(sinVal, 'System.Int16');
% if channel ~= 0
% data = NET.convertArray(zeroVal, 'System.Int16');
% end
device.EnqueueData(channel, data);
space = device.GetDataQueueSpace(channel);
end
end
end
|
% Arnold Lab, University of Michigan
% Melissa Lemke, PhD Candidate
% Last edit: October 5th, 2021
%% make sure you move your results from personal simulations and
%% surface simulation into this folder!
clear
%choose the output complex
com_id = 33;
%Choose which FcR: FcR3aV = 1 FcR3aF = 2 FcR2aH = 3 FcR2aR = 4
% fcr_id = 1;
% load personal data just to set the size of x1 and x2 - will load again
% later
personal_data_path = 'A244_personal_baseline_all_fcrs_addition*.mat';
d = dir(personal_data_path);
file_name = d.name;
load(file_name);
group_names = ["Post Vaccination" "Post 145 nM IgG1 Boost"];
adds = [0 145];
color = [0 0 0; 0 0 1; 1 0 0; 1 0 1; 0 1 1]; % group color
fcr_names = ["FcR3a-V158" "FcR3a-F158"];
x1 = nan(length(patient_id),length(group_names)*length(fcr_names));
x2 = nan(length(patient_id),length(group_names)*length(fcr_names));
%choose the strain
strain = 'A244';
for fcr_id = 1:length(fcr_names)
%load the surface data
d = dir(['*_2D_IgG1_conc*'+fcr_names(fcr_id)+'*']);
file_name = d.name;
load(file_name);
%shorten fcr_names loaded from 2D file to only FcR3
fcr_names = ["FcR3a-V158" "FcR3a-F158"];% "FcR2a-H131" "FcR2a-R131"];
disp([paramnames(p1)+" "+paramnames(p2)])
x = dParams*params(p1);%nM
y = dParams*params(p2);%nM
z = yfull(:,:,com_id);%nM
z_fcrs(fcr_id,:,:) = z;
%% Load the personal baseline data!!! Move it to this folder
% try % will only run if you've moved the personal baseline data into this folder
d = dir(personal_data_path);
file_name = d.name;
load(file_name);
com_name = complexname(com_id);
all_run_full = all_run;
all_run = all_run{1};%baseline
% Prep data
FcR_model = squeeze(all_run(:,:,com_id))';
%plot the surface
surfacefig(p1,p2,FcR_model,fcr_id,patient_id, com_name,...
fcr_names,param_idv{1},x,y,z,paramnames,"", group_names,color);
end
figure(1)
%Add the lines and dots for each person
for fcr_id = 1:length(fcr_names)
for group_ind = 1:length(group_names)
addition = adds(group_ind);
[zs_pers(fcr_id,group_ind,:)] = getzpers(p1,p2,fcr_id,patient_id,param_idv{group_ind},x,y,squeeze(z_fcrs(fcr_id,:,:)));
end
end
for group_ind = 1:2%length(group_names)
addition = adds(group_ind);
param_idv_g = param_idv{group_ind};
for pers = 1:length(patient_id)
pers_color = color(group_ind,:);
line([param_idv_g(fcr_id,pers,p1)' param_idv_g(fcr_id,pers,p1)'],[param_idv_g(fcr_id,pers,p2)',...
param_idv_g(fcr_id,pers,p2)'],[min(squeeze(zs_pers(:,group_ind,pers)))' max(squeeze(zs_pers(:,group_ind,pers)))'],'Color',pers_color,...
'Marker','.','MarkerSize',20)
end
end
legend(fcr_names)
%plot the dot plot showing change between polymorphisms before and after
%boosting
for i = 1:length(all_run_full)
diff_btwn_polys(:,i) = all_run_full{i}(1,:,com_id)-all_run_full{i}(2,:,com_id);
end
dot_plot_data = diff_btwn_polys;
xlabels = ["Post vaccination" "Post IgG1 boost"];
med_dot_data = median(dot_plot_data);
figure()
x_val_dot_plot = rand(size(dot_plot_data))+(1:length(xlabels))-0.5;
scatter(x_val_dot_plot,dot_plot_data)
hold on
line([0.5 1.5;1.5 2.5]',[med_dot_data' med_dot_data']')
xticks(1:length(xlabels))
xticklabels(xlabels)
ylabel(["Change in complex"; "formation from FcR3aF";"to FcR3aV (nM)"])
%% Surface fig
function [zs_pers] = surfacefig(p1,p2,FcR_model,fcr_id,patient_id, com_name, FcR_names,param_idv,x,y,z,paramnames, groups, group_name,color)
figure(1)
surf_color = [1 1 1;0 0 0];
%plot surface - > currently everyother line to prevent crowding
surface(x(1:2:end),y(1:2:end),z(1:2:end,1:2:end),'LineStyle','-','FaceAlpha',0.5,'FaceColor',surf_color(fcr_id,:))%
ylabel([paramnames(p2)+" (nM)"])
xlabel([paramnames(p1)+" (nM)"])
xs = [min(x)*1 max(x)*1];
ys = [min(y)*1 max(y)*1];
zs = [min(min(z))*1 max(max(z))*1];
xlim(xs)
ylim(ys)
zlabel(["Complex", "Formation (nM)"])
set(gca, 'YScale', 'log','XScale','log')%,'Zscale','log'
set(gca,'FontSize',8)
hold on
end
function [zs_pers] = getzpers(p1,p2,fcr_id,patient_id,param_idv,x,y,z)
for pers = 1:length(patient_id)
[xplace xind] = min(abs(x-(param_idv(fcr_id,pers,p1))));
[yplace yind] = min(abs(y-param_idv(fcr_id,pers,p2)));
zs_pers(pers) = z(yind,xind);
end
end |
function shade(TR, run)
global b f W k
% Dimention of each vector
D = b*f + 1;
% Population size
NP = 50; % Edit here for adjusting the population size.
% Number of generations
Gen = 200; % Edit here for adjusting the number of generations.
% The limiting values of elements of vectors
x_min = 0;
x_max = 1;
% Size of Archieve
H=20; % Edit here for adjusting the size of archieve.
% Initializing variables and vectors
G = 1;
k1 = 1;
M_Cr = 0.5*ones(1,H);
M_F = 0.5*ones(1,H);
U = zeros(1,D);
X = zeros(NP,D);
prev_func_value = zeros(NP,1);
A=[];
% Initialization of chromosome
for i = 1:NP
X(i,:) = (x_min + (x_max-x_min).*rand(1,D));
% Extracting Weight matrix and value of k from the chromosome
parameter = extract(X(i,:));
W = parameter.W;
% Retaining the value of k
k = ceil(parameter.k * sqrt(size(TR,1)));
% Calling fitness function
prev_func_value(i) = fitness(TR);
end
min_func_value = inf;
while G<=Gen && min_func_value>0
SCR=[];
SF=[];
delta_f=[];
for i=1:NP
r_i=randi([1,H],1,1);
cr_i = normrnd(M_Cr(r_i), 0.1);
cr_i = max(cr_i, 0);
cr_i = min(cr_i, 1);
while true
F = cauchy_rand(M_F(r_i), 0.1, 1);
if 0<F && F<=1
break;
end
end
p = 2/NP + rand()*(0.2-2/NP);
p = round(p*NP);
[~, I] = sort(prev_func_value);
p_best = randi([1,p],1,1);
p_best = I(p_best);
while true
r1 = randi([1,NP],1,1);
if r1 ~= i
break;
end
end
if isempty(A)
A_union_P = X;
else
A_union_P = union(A, X, 'rows');
end
r2 = randi([1,size(A_union_P,1)], 1, 1);
% Mutation
V = X(i,:) + F*(X(p_best,:)-X(i,:)) + F*(X(r1,:)-A_union_P(r2,:));
if V(end) <= 0
V(end) = rand(1,1);
end
% Crossover
j_rand = randi([1 D], 1, 1);
l = rand(1, D);
U(l<=cr_i) = V(l<=cr_i);
U(j_rand) = V(j_rand);
U(l>cr_i) = X(i, l>cr_i);
% Selection
parameter = extract(U);
W = parameter.W;
k = ceil(parameter.k * sqrt(size(TR,1)));
func_val_U = fitness(TR);
% Updating parameter archive
if func_val_U < prev_func_value(i)
SCR = [SCR, cr_i];
SF = [SF, F];
A = [A; X(i,:)];
delta_f = [delta_f, abs(prev_func_value(i)-func_val_U)];
X(i,:) = U;
prev_func_value(i) = func_val_U;
end
if min_func_value > prev_func_value(i)
min_func_value = prev_func_value(i);
ans_vector = X(i,:);
end
if size(A,1) > NP
temp = randi([1,NP],1,1);
A(temp,:) = [];
end
end
if isempty(SCR)==0 && isempty(SF)==0
M_Cr(k1) = wt_Mean(SCR, delta_f);
M_F(k1) = wt_Lehmer_Mean(SF, delta_f);
k1 = k1+1;
if k1>H
k1 = 1;
end
end
membership_assignment(TR);
h = sprintf('Run %d Gen %d: Error= %f',run,G,min_func_value);
disp(h);
G = G+1;
end
% Extracting the final values of parameters
parameter = extract(ans_vector);
W = parameter.W;
k = ceil(parameter.k * sqrt(size(TR,1)));
|
%% Stelling 12
%
% Het Command Window is een van de mogelijkheden om een
% functie aan te roepen.
%
Antwoord = 1;
|
function [CPE] = presetCPE(varargin)
% Last Update: 31/03/2019
%% Input Parser
nOptionalArgs = length(varargin);
for n=1:2:nOptionalArgs
varName = varargin{n};
varValue = varargin{n+1};
if any(strncmpi(varName,{'method'},4))
method = varValue;
elseif any(strncmpi(varName,{'decision'},6))
decision = varValue;
elseif any(strncmpi(varName,{'mQAM'},4))
mQAM = varValue;
elseif any(strncmpi(varName,{'demodQAM'},5))
demodQAM = varValue;
elseif any(strncmpi(varName,{'segChangeDetect','segmentChangeDetect','detectSegmentChange'},10))
segChangeDetect = varValue;
elseif any(strcmpi(varName,{'p'}))
p = varValue;
elseif any(strncmpi(varName,{'QAM_classes','classesQAM','QAMclasses'},9))
QAM_classes = varValue;
elseif any(strcmpi(varName,{'nSpS'}))
nSpS = varValue;
elseif any(strcmpi(varName,{'ts0'}))
ts0 = varValue;
elseif any(strcmpi(varName,{'nTaps'}))
nTaps = varValue;
elseif any(strncmpi(varName,{'debugPlots','plotsDebug'},7))
debugPlots = varValue;
elseif any(strncmpi(varName,{'convMethod'},4))
convMethod = varValue;
elseif any(strncmpi(varName,{'nTestPhases'},7))
nTestPhases = varValue;
elseif any(strncmpi(varName,{'angleInterval'},8))
angleInterval = varValue;
elseif any(strncmpi(varName,{'rmvEdgeSamples'},8))
rmvEdgeSamples = varValue;
elseif strncmpi(varName,'CPE',3)
CPE_old = varValue;
end
end
%% Check for pre-defined CPE
if exist('CPE_old','var')
CPE = CPE_old;
end
%% Check Method
if ~exist('method','var') && isfield(CPE,'method')
method = CPE.method;
end
if exist('method','var')
switch method
case {'Viterbi','Viterbi&Viterbi','V&V','VV','VV:optimized'}
CPE.method = method;
if exist('nTaps','var')
CPE.nTaps = nTaps;
elseif ~isfield(CPE,'nTaps')
CPE.nTaps = 50;
end
if exist('segChangeDetect','var')
CPE.segChangeDetect = segChangeDetect;
elseif ~isfield(CPE,'segChangeDetect')
CPE.segChangeDetect = true;
end
if exist('rmvEdgeSamples','var')
CPE.rmvEdgeSamples = rmvEdgeSamples;
elseif ~isfield(CPE,'rmvEdgeSamples')
CPE.rmvEdgeSamples = false;
end
if exist('convMethod','var')
CPE.convMethod = convMethod;
elseif ~isfield(CPE,'convMethod')
CPE.convMethod = 'filter';
end
if exist('mQAM','var')
CPE.mQAM = mQAM;
elseif ~isfield(CPE,'mQAM')
CPE.mQAM = 'QPSK';
end
if ~strcmpi(CPE.mQAM,'QPSK')
if exist('demodQAM','var')
CPE.demodQAM = demodQAM;
elseif ~isfield(CPE,'demodQAM')
CPE.demodQAM = 'QPSKpartition';
end
if exist('QAM_classes','var')
CPE.QAM_classes = QAM_classes;
elseif ~isfield(CPE,'QAM_classes')
CPE.QAM_classes = 'A';
end
if exist('p','var')
CPE.p = p;
elseif ~isfield(CPE,'p')
CPE.p = 1;
end
end
if exist('debugPlots','var')
CPE.debugPlots = debugPlots;
elseif ~isfield(CPE,'debugPlots')
CPE.debugPlots = {};
end
if exist('nSpS','var')
CPE.nSpS = nSpS;
end
if exist('ts0','var')
CPE.ts0 = ts0;
elseif ~isfield(CPE,'ts0')
CPE.ts0 = 1;
end
case {'MaximumLikelihood','Maximum-Likelihood','maxLike','ML'}
CPE.method = method;
if exist('nTaps','var')
CPE.nTaps = nTaps;
elseif ~isfield(CPE,'nTaps')
CPE.nTaps = 50;
end
if exist('rmvEdgeSamples','var')
CPE.rmvEdgeSamples = rmvEdgeSamples;
elseif ~isfield(CPE,'rmvEdgeSamples')
CPE.rmvEdgeSamples = true;
end
if exist('decision','var')
CPE.decision = decision;
elseif ~isfield(CPE,'decision')
CPE.decision = 'DD';
end
if exist('convMethod','var')
CPE.convMethod = convMethod;
elseif ~isfield(CPE,'convMethod')
CPE.convMethod = 'filter';
end
case {'decision-directed','DecisionDirected','DD'}
CPE.method = method;
if exist('nTaps','var')
CPE.nTaps = nTaps;
elseif ~isfield(CPE,'nTaps')
CPE.nTaps = 50;
end
if exist('rmvEdgeSamples','var')
CPE.rmvEdgeSamples = rmvEdgeSamples;
elseif ~isfield(CPE,'rmvEdgeSamples')
CPE.rmvEdgeSamples = true;
end
if exist('ts0','var')
CPE.ts0 = ts0;
elseif ~isfield(CPE,'ts0')
CPE.ts0 = 1;
end
if exist('nSpS','var')
CPE.nSpS = nSpS;
end
CPE.convMethod = 'vector';
case {'blind phase-search','blindPhaseSearch','BPS'}
CPE.method = method;
if exist('nTaps','var')
CPE.nTaps = nTaps;
elseif ~isfield(CPE,'nTaps')
CPE.nTaps = 50;
end
if exist('rmvEdgeSamples','var')
CPE.rmvEdgeSamples = rmvEdgeSamples;
elseif ~isfield(CPE,'rmvEdgeSamples')
CPE.rmvEdgeSamples = true;
end
if exist('nTestPhases','var')
CPE.nTestPhases = nTestPhases;
elseif ~isfield(CPE,'nTestPhases')
CPE.nTestPhases = 32;
end
if exist('angleInterval','var')
CPE.angleInterval = angleInterval;
elseif ~isfield(CPE,'angleInterval')
CPE.angleInterval = pi/4;
end
case 'phaseRotation'
CPE.method = method;
end
elseif ~exist('method','var') && ~exist('presetConfig','var')
warning('To preset the CPE parameters you must indicate either the CPE method or a CPE preset configuration. Without any of these, all other parameters cannot be assigned. CPE will be now preset to simple QPSK-based Viterbi&Viterbi estimation.');
CPE.method = 'VV';
CPE.nTaps = 50;
CPE.mQAM = 'QPSK';
CPE.p = 1;
CPE.segChangeDetect = true;
CPE.ts0 = 1;
CPE.convMethod = 'filter';
CPE.debugPlots = {};
end
|
% environment.m
% this program sets the default parameters for the model
clear all;
global alpha beta sigma delta BYbar gamma psi Gbar0 phi0 rhoz0 rhog0 use_uhlig impulse_response;
% Setting parameters:
alpha=0.68; % labor share
beta=1/1.02; % discount factor for quarterly
sigma=2; % risk aversion
delta=0.1/2; % depreciation
BYbar=0.1; % steady state bond holdings
gamma=.36; % consumption coef in Cobb-Douglas utility
psi=0.001; % risk premium parameter on debt
use_uhlig=0; %if ==1, use altered version of Uhlig's moments.m program
impulse_response=0; %if ==1, plots impulse responses when using key_moments.m
%default parameters
Gbar0 = 1.006;
rhoz0 = 0.95;
rhog0 = 0.01;
phi0 = 4;
%column number for moments when using gmm.m
sd_y=1;
sd_dy=2;
sd_i=3;
sd_c=4;
sd_nx=5;
rho_y=6;
rho_dy=7;
rho_nx=8;
rho_c=9;
rho_i=10;
mu_g=11;
|
function [b2v, bdedgs, edgmap, v2b] = extract_border_curv_tri...
(nv, tris, flabel, sibhes, inwards) %#codegen
%EXTRACT_BORDER_CURV_TRI Extract border vertices and edges.
% [B2V,BDEDGS,EDGMAP] = EXTRACT_BORDER_CURV_TRI(NV,TRIS,FLABEL,SIBHES,INWARDS)
% Extract border vertices and edges of triangle mesh. Return list of border
% vertex IDs and list of border edges. Edges between faces with different
% labels are also considered as border edges, and in this case only the
% halfedge with smaller label IDs are returned. The following explains the
% input and output arguments.
%
% [B2V,BDEDGS,EDGMAP] = EXTRACT_BORDER_CURV_TRI(NV,TRIS)
% [B2V,BDEDGS,EDGMAP] = EXTRACT_BORDER_CURV_TRI(NV,TRIS,FLABEL)
% [B2V,BDEDGS,EDGMAP] = EXTRACT_BORDER_CURV_TRI(NV,TRIS,FLABEL,SIBHES)
% [B2V,BDEDGS,EDGMAP] = EXTRACT_BORDER_CURV_TRI(NV,TRIS,FLABEL,SIBHES,INWARDS)
% NV: specifies the number of vertices.
% TRIS: contains the connectivity.
% FLABEL: contains a label for each face.
% SIBHES: contains the opposite half-edges.
% INWARDS: specifies whether the edge normals should be inwards (false by default)
% B2V: is a mapping from border-vertex ID to vertex ID.
% BDEDGS: is connectivity of border edges.
% EDGMAP: stores mapping to halfedge ID
%
% See also EXTRA_BORDER_CURV
isborder = false(nv,1);
visited=false(nv,1);
if nargin>=5 && inwards
% List vertices in counter-clockwise order, so that edges are inwards.
he_tri = int32([1,2; 2,3; 3,1]);
else
% List vertices in counter-clockwise order, so that edges are outwards.
he_tri = int32([2,1; 3,2; 1,3]);
end
if nargin<3; flabel=0; end
if nargin<4; sibhes = determine_sibling_halfedges(nv, tris); end
nbdedgs = 0; ntris=int32(size(tris,1));
for ii=1:ntris
if tris(ii,1)==0; ntris=ii-1; break; end
for jj=1:3
if sibhes(ii,jj) == 0 || size(flabel,1)>1 && ...
flabel(ii)~=flabel(heid2fid(sibhes(ii,jj)))
if(~visited(tris(ii,he_tri(jj,1))))
visited(tris(ii,he_tri(jj,1)))=true;
isborder( tris(ii,he_tri(jj,1))) = true; nbdedgs = nbdedgs +1;
end
if(~visited(tris(ii,he_tri(jj,2))))
visited(tris(ii,he_tri(jj,2)))=true;
isborder( tris(ii,he_tri(jj,2))) = true; nbdedgs = nbdedgs +1;
end
end
end
end
% Define new numbering for border vertices
v2b = zeros(nv,1,'int32'); % Allocate and initialize to zeros.
b2v = nullcopy(zeros(sum(isborder),1,'int32'));
k = int32(1);
if nv<ntris*3
for ii=1:nv
if isborder(ii);
b2v(k) = ii; v2b(ii) = k; k = k+1;
end
end
else
% If there are too many vertices, then loop through connectivity table
for ii=1:ntris
for jj=1:3
v = tris(ii,jj);
if isborder(v) && v2b(v)==0
b2v(k) = v; v2b(v) = k; k = k+1;
end
end
end
end
if nargout>1
bdedgs = nullcopy(zeros(nbdedgs,2,'int32'));
if nargout>2; edgmap = nullcopy(zeros(size(bdedgs,1),1,'int32')); end
count = int32(1);
for ii=1:ntris
for jj=1:3
if sibhes(ii,jj) == 0 || size(flabel,1)>1 && ...
flabel(ii)<flabel(heid2fid(sibhes(ii,jj)))
bdedgs(count, :) = v2b(tris(ii,he_tri(jj,:)));
if nargout>2; edgmap(count) = ii*4+jj-1; end
count = count + 1;
end
end
end
end
|
JA=0;JB=0;JC=0;JD=0;JE=0;JF=0;JG=0;
NJA=0;NJB=0;NJC=0;NJD=0;NJE=0;NJF=0;NJG=0;
for i=1:4
JA=JA+X{i}{8};
JB=JA+X{i}{9};
JC=JC+X{i}{10};
JD=JD+X{i}{11};
JE=JE+X{i}{12};
JF=JF+X{i}{13};
JG=JG+X{i}{7};
end
JA=JA/4;JB=JB/4;JC=JC/4;JD=JD/4;JE=JE/4;JF=JF/4;JG=JG/4;
for i=5:10
NJA=NJA+X{i}{8};
NJB=NJA+X{i}{9};
NJC=NJC+X{i}{10};
NJD=NJD+X{i}{11};
NJE=NJE+X{i}{12};
NJF=NJF+X{i}{13};
NJG=NJG+X{i}{7};
end
NJA=NJA/6;NJB=NJB/6;NJC=NJC/6;NJD=NJD/6;NJE=NJE/6;NJF=NJF/6;NJG=NJG/14;
JA2=0;JB2=0;JC2=0;JD2=0;JE2=0;JF2=0;JG2=0;
NJA2=0;NJB2=0;NJC2=0;NJD2=0;NJE2=0;NJF2=0;NJG2=0;
for i=1:4
JA2=JA2+X{i}{14};
JB2=JB2+X{i}{15};
JC2=JC2+X{i}{16};
JD2=JD2+X{i}{17};
JE2=JE2+X{i}{18};
JF2=JF2+X{i}{19};
JG2=JG2+X{i}{20};
end
JA2=JA2/4;JB2=JB2/4;JC2=JC2/4;JD2=JD2/4;JE2=JE2/4;JF2=JF2/4;JG2=JG2/4;
for i=5:10
NJA2=NJA2+X{i}{14};
NJB2=NJB2+X{i}{15};
NJC2=NJC2+X{i}{16};
NJD2=NJD2+X{i}{17};
NJE2=NJE2+X{i}{18};
NJF2=NJF2+X{i}{19};
NJG2=NJG2+X{i}{20};
end
NJA2=NJA2/6;NJB2=NJB2/6;NJC2=NJC2/6;NJD2=NJD2/6;NJE2=NJE2/6;NJF2=NJF2/6;NJG2=NJG2/4; |
% TU-Dresden Institut für Automatisierungstechnik
% 9.12.1997-T.Boge / 4.10.2002-K.Janschek
% EXPERIMENT FRAME: Simulations Control PARAMETER
% === Simulation Control ===================================
% simulation duration [s]
tmax = 1000000000000000000000;
|
% defining relevant parameters
T = 1;
T1 = 1/4;
N = 10;
syms t;
% defining relevant expressions
xt = abs(t);
% function call to fourierCoeff which returns array of fourier coefficients
F = fourierCoeff(N,T,t,xt,-T1,T1);
%displaying all the coefficients
disp(F);
% plotting the FS coeff.
k = -N:N;
figure; stem(k, F); grid on;
%labels for axes and title of the plot
xlabel('k');
ylabel('ak (kth FS coeff.');
title('FS coeff. of x1(t)'); |
function [ Diff ] = ShapeContextEMDCalcDist( WP1Contour, WP2Contour )
%ShapeContextEMDCalcDist: Takes 2 WordParts Contours and return the
%distance between them using ShapeContext Feature and And Approx EMD as the
%metric.
% Detailed explanation goes here
WPT1FeaureVector= CreateFeatureVectorFromContour(WP1Contour,2);
WPT2FeaureVector= CreateFeatureVectorFromContour(WP2Contour,2);
[f,Diff] = EmdContXY(WPT1FeaureVector,WPT2FeaureVector);
end |
%% Electric
clear all
clc
SetAdvisorPath;
% initiate timer
tic
%Pass the vehicle
input.init.saved_veh_file='ev_small_in';
[error_code,resp]=adv_no_gui('initialize',input);
% % Define the Vehicle
% input.init.comp_files.comp={'vehicle'};
% input.init.comp_files.name= {'VEH_SMCAR'};
% input.init.comp_files.ver={''};
% input.init.comp_files.type ={''};
% [error_code,resp]=adv_no_gui('initialize',input);
% Modify the Vehicle Parameters
input.modify.param = {'veh_cargo_mass','veh_glider_mass','veh_FA','veh_CD'};
input.modify.value = {100,756,1.8,0.22};
[error_code,resp] = adv_no_gui('modify',input);
% % Change to a Lithium Ion Battery
% input.init.comp_files.comp={'energy_storage'};
% input.init.comp_files.name= {'ESS_LI7_temp'};
% input.init.comp_files.ver={'rint'};
% input.init.comp_files.type ={'li'};
% [error_code,resp]=adv_no_gui('initialize',input);
% Modify the number of Battery Modules
input.modify.param = {'ess_module_num'};
input.modify.value = {44};
[error_code,resp] = adv_no_gui('modify',input);
% % Change the Motor
% input.init.comp_files.comp = {'motor_controller'};
% input.init.comp_files.name = {'MC_PM58'};
% input.init.comp_files.ver = {''};
% input.init.comp_files.type = {''};
% [error_code,resp]=adv_no_gui('initialize',input);
% Scale the trq and spd of the Motor
input.modify.param = {'mc_trq_scale','mc_spd_scale'};
input.modify.value = {1,1};
[a,b] = adv_no_gui('modify',input);
% % Define the Accessory Load
% input.init.comp_files.comp = {'accessory'};
% input.init.comp_files.name = {'ACC_HYBRID'};
% input.init.comp_files.ver = {'Const'};
% input.init.comp_files.type = {'Const'};
% [error_code,resp]=adv_no_gui('initialize',input);
%
% % Modify the Accesory load
% input.modify.param = {'acc_elec_pwr'};
% input.modify.value = {700};
% [error_code,resp] = adv_no_gui('modify',input)
% Modify the Final Drive Ratio
input.modify.param = {'fd_ratio'};
input.modify.value = {1.0476};
[error_code,resp] = adv_no_gui('modify',input);
dv_names={'mc_trq_scale','mc_spd_scale','ess_module_num','ess_cap_scale','fd_ratio'};
resp_names={'MPGGE___small_electric'};
con_names={'delta_soc','delta_trace','vinf.accel_test.results.time(1)','vinf.accel_test.results.time(2)','vinf.accel_test.results.time(3)','vinf.grade_test.results.grade'};
% define the problem
cont_bool=0;
p_f='obj';
p_c='const';
% mc_trq_scale mc_spd_scale ess_module_num ess_cap_scale
x_L=[0.5*mc_trq_scale, 0.5*mc_spd_scale, 0.5*ess_module_num, 0.5, 0.5*fd_ratio]';
x_U=[1.5*mc_trq_scale, 1.5*mc_spd_scale, 1.5*ess_module_num, 1.5, 1.5*fd_ratio]';
A=[];
b_L=[];
b_U=[];
% delta_soc delta_trace vinf.accel_test.results.time(1) vinf.accel_test.results.time(2) vinf.accel_test.results.time(3) vinf.grade_test.results.grade
c_L=[ 0; 0; 0; 0; 0; 6.5];
c_U=[ -1; 2; 12; 5.4; 23.8; 6.6];
I=[];
PriLev=2;
MaxEval=6;
MaxIter=5;
GLOBAL.epsilon=1e-6;
prev_results_filename='small_electric___results';
if cont_bool==1
eval(['load(''',prev_results_filename,''')'])
GLOBAL = small_electric___optimization.GLOBAL;
GLOBAL.MaxEval = MaxEval;
GLOBAL.MaxIter = MaxIter;
else
GLOBAL.MaxEval = MaxEval;
GLOBAL.MaxIter = MaxIter;
end
plot_info.var_label=dv_names;
plot_info.var_ub=num2cell(x_U);
plot_info.var_lb=num2cell(x_L);
plot_info.con_label=con_names;
plot_info.con_ub=num2cell(c_U);
plot_info.con_lb=num2cell(c_L);
plot_info.fun_label=resp_names;
% start the optimization
small_electric___optimization = gclSolve(p_f, p_c, x_L, x_U, A, b_L, b_U, c_L, c_U, I, GLOBAL, PriLev, plot_info, dv_names, resp_names, con_names);
% save the results
eval(['save(''',prev_results_filename,''',','''small_electric___optimization'');'])
% save the vehicle
input.save.filename='small_electric__';
[a,b]=adv_no_gui('save_vehicle',input);
% plot the optimization results
PlotOptimResults(small_electric___optimization.GLOBAL.f_min_hist, plot_info)
% end timer
toc |
%% ---- R200e1/3
% Run these one section at a time with the Run Section button. Ensure
% pro3.m and pro5.m are included in the current folder and are on the path.
% Sections are denoted by double percentage signs %%
% For a more accurate analytical solution, change the timestep
% e.g. line 121 t = 0:4:55000; where the 16 -> 4 for 4x accuracy
% For a more accurate numerical solution, change the options
% of the odeset: higher refinement and lower tolerance
% both lead to higher accuracy.
% -- Variables
M = 1;
R = 395;
e = 1/3;
p = 266.0+2/3;
s = 0.1;
Art = 2*M/(R^2)*((1-2*M/R)^(-1))*((1-3*M/R)^(-1/2));
Atr = 2*M/(R^2)*(1-2*M/R)*((1-3*M/R)^(-1/2));
Arr = (-3*M/(R^3)*((1-3*M/R)^(-1)))*(1-2*M/R);
Apr = -2*R*((M/(R^3))^(1/2))*(1-2*M/R)*((1-3*M/R)^(-1/2));
Arp = 2/R*((M/(R^3))^(1/2))*((1-3*M/R)^(-1/2));
wt = (1 - 3*M/R)^(-1/2);
w = ((M/(R^3))^(1/2))*((1 - 3*M/R)^(-1/2))*((1 - 6*M/R)^(1/2));
wp = ((M/(R^3))^(1/2))*((1 - 3*M/R)^(-1/2));
nr0 = -950;
nt0 = Art/w*nr0;
np0 = Arp/w*nr0;
Nr0 = 1000;
Nt0 = -3/2*M/(R^2)*((1 - 3*M/R)^(-3/2))*Nr0;
Np0 = -3/2*((M/R)^(1/2))/(R^2)*(1 - 2*M/R)*((1 - 3*M/R)^(-3/2))*Nr0;
% -- Our solution
t = 0:10:100000;
y = zeros(length(t), 4);
y(:,1) = wt*t - s*(nt0*sin(w*t) + Nt0*t);
y(:,2) = R + s*(nr0*cos(w*t) - Nr0);
y(:,3) = pi/2;
y(:,4) = wp*t - s*(np0*sin(w*t) + Np0*t);
ycart = zeros(length(t),2);
ycart(:,1) = y(:,2).*cos(y(:,4)); % convert from polar to cartesian
ycart(:,2) = y(:,2).*sin(y(:,4));
% -- Numerical solution
options = odeset('Refine',512,'RelTol',0.0001);
[X1,q1] = ode45(@(X1,q1,e,p,a)pro3(X1,q1,0.2,12,M), [0 12.5], [0], options);
[X3,q3] = ode45(@(X3,q3,e,p,a)pro5(X3,q3,0.2,12,M), [0 12.5], [0], options);
q = zeros(length(q1), 3);
q(:,1) = q1;
%q(:,2) = (1./(1+e*cos(X1)))*(p);
zabadabadoo = 1./(1+e*cos(X1));
zabadabadee = p*M*zabadabadoo;
q(:,2) = zabadabadee;
q(:,3) = spline(X3,q3,X1);
qcart = zeros(length(q(:,1)),2);
qcart(:,1) = q(:,2).*cos(q(:,3)); % convert from polar to cartesian
qcart(:,2) = q(:,2).*sin(q(:,3));
% -- Plotting
viscircles([0 0], 3, 'Color', 'y'); hold on; % Event horizon * 1.5
plot(0,0,'k.'); hold on; % Black hole
axis([-400 400 -400 400]);
l1 = animatedline('Color','b'); % Animated lines to draw the paths
l2 = animatedline('Color','g'); % Animated lines to draw the paths
for k = 1:max(length(qcart(:,1)), length(ycart(:,1)))
if k <= length(qcart(:,1))
addpoints(l1, qcart(k,1), qcart(k,2));
end
if k <= length(ycart(:,1))
addpoints(l2, ycart(k,1), ycart(k,2));
end
pause(0.00005);
drawnow;
end
%% ---- R200e1/11 with error
% -- Variables
M = 1;
R = 320.6;
e = 1/11;
p = 2400/11;
s = 0.1;
Art = 2*M/(R^2)*((1-2*M/R)^(-1))*((1-3*M/R)^(-1/2));
Atr = 2*M/(R^2)*(1-2*M/R)*((1-3*M/R)^(-1/2));
Arr = (-3*M/(R^3)*((1-3*M/R)^(-1)))*(1-2*M/R);
Apr = -2*R*((M/(R^3))^(1/2))*(1-2*M/R)*((1-3*M/R)^(-1/2));
Arp = 2/R*((M/(R^3))^(1/2))*((1-3*M/R)^(-1/2));
wt = (1 - 3*M/R)^(-1/2);
w = ((M/(R^3))^(1/2))*((1 - 3*M/R)^(-1/2))*((1 - 6*M/R)^(1/2));
wp = ((M/(R^3))^(1/2))*((1 - 3*M/R)^(-1/2));
nr0 = -206;
nt0 = Art/w*nr0;
np0 = Arp/w*nr0;
Nr0 = 1000;
Nt0 = -3/2*M/(R^2)*((1 - 3*M/R)^(-3/2))*Nr0;
Np0 = -3/2*((M/R)^(1/2))/(R^2)*(1 - 2*M/R)*((1 - 3*M/R)^(-3/2))*Nr0;
% -- Our solution
t = 0:16:55000;
y = zeros(length(t), 4);
y(:,1) = wt*t - s*(nt0*sin(w*t) + Nt0*t);
y(:,2) = R + s*(nr0*cos(w*t) - Nr0);
y(:,3) = pi/2;
y(:,4) = wp*t - s*(np0*sin(w*t) + Np0*t);
ycart = zeros(length(t),2);
ycart(:,1) = y(:,2).*cos(y(:,4)); % convert from polar to cartesian
ycart(:,2) = y(:,2).*sin(y(:,4));
% -- Numerical solution
options = odeset('Refine',512,'RelTol',0.00001);
[X1,q1] = ode45(@(X1,q1,e,p,a)pro3(X1,q1,0.2,12,M), [0 10], [0], options);
[X3,q3] = ode45(@(X3,q3,e,p,a)pro5(X3,q3,0.2,12,M), [0 10], [0], options);
q = zeros(length(q1), 3);
q(:,1) = q1;
%q(:,2) = (1./(1+e*cos(X1)))*(p*M);
zabadabadoo = 1./(1+e*cos(X1));
zabadabadee = p*M*zabadabadoo;
q(:,2) = zabadabadee;
q(:,3) = spline(X3,q3,X1);
qcart = zeros(length(q(:,1)),2);
qcart(:,1) = q(:,2).*cos(q(:,3)); % convert from polar to cartesian
qcart(:,2) = q(:,2).*sin(q(:,3));
% -- Finding the error
qatt = zeros(length(t),3);
iHateMatlab = spline(X1, q(:,2), t/(200000/10));
qatt(:,2) = iHateMatlab;
qatt(:,3) = spline(X3, q3, t/(200000/10));
errorr = (y(:,2)-qatt(:,2))./qatt(:,2);
errorp = (y(:,4)-qatt(:,3))./qatt(:,3);
% -- Plotting
figure('units','normalized','outerposition',[0 0 1 1]);
%set(gca,'Position',[0.1 0.1 0.75 0.85]);
leftPlot = subplot(1,2,1);
viscircles([0 0], 3, 'Color', 'y'); hold on; % Event horizon * 1.5
plot(0,0,'k.'); hold on; % Black hole
axis([-250 250 -250 250]);
title("The Orbit");
rightPlot = subplot(1,2,2);
plot(1:length(t), zeros(length(t),1), 'k'); hold on; % black line
axis([0 length(t) -0.2 0.4]);
title("Error in R");
xticklabels({});
xlabel("Time");
ylabel("Relative Error");
l1 = animatedline('Color','b','Parent',leftPlot); % Animated lines to draw the paths
l2 = animatedline('Color','r','Parent',leftPlot);
l3 = animatedline('Color','k','Parent',rightPlot);
for k = 1:max([length(qcart(:,1)), length(ycart(:,1)), length(errorr)])
subplot(1,2,1);
if k+1000 <= length(qcart(:,1))
addpoints(l1, qcart(k+1000,1), qcart(k+1000,2));
end
if k <= length(ycart(:,1))
addpoints(l2, ycart(k,1), ycart(k,2));
end
subplot(1,2,2);
if (k-500 <= length(errorr) && k > 500)
addpoints(l3, k-500, errorr(k-500))
end
%pause(0.0001);
drawnow; hold on;
end
%{
for l = k:(k+84)
subplot(1,2,2);
addpoints(l3, l-500, errorr(l-500));
drawnow; hold on;
end
%}
%% ---- R1000e1/100
% -- Variables
M = 1;
R = 1119.5;
e = 2/100;
p = 1020;
s = 0.1;
Art = 2*M/(R^2)*((1-2*M/R)^(-1))*((1-3*M/R)^(-1/2));
Atr = 2*M/(R^2)*(1-2*M/R)*((1-3*M/R)^(-1/2));
Arr = (-3*M/(R^3)*((1-3*M/R)^(-1)))*(1-2*M/R);
Apr = -2*R*((M/(R^3))^(1/2))*(1-2*M/R)*((1-3*M/R)^(-1/2));
Arp = 2/R*((M/(R^3))^(1/2))*((1-3*M/R)^(-1/2));
wt = (1 - 3*M/R)^(-1/2);
w = ((M/(R^3))^(1/2))*((1 - 3*M/R)^(-1/2))*((1 - 6*M/R)^(1/2));
wp = ((M/(R^3))^(1/2))*((1 - 3*M/R)^(-1/2));
nr0 = -195;
nt0 = Art/w*nr0;
np0 = Arp/w*nr0;
Nr0 = 1000;
Nt0 = -3/2*M/(R^2)*((1 - 3*M/R)^(-3/2))*Nr0;
Np0 = -3/2*((M/R)^(1/2))/(R^2)*(1 - 2*M/R)*((1 - 3*M/R)^(-3/2))*Nr0;
% -- Our solution
t = 0:40:200000;
y = zeros(length(t), 4);
y(:,1) = wt*t - s*(nt0*sin(w*t) + Nt0*t);
y(:,2) = R + s*(nr0*cos(w*t) - Nr0);
y(:,3) = pi/2;
y(:,4) = wp*t - s*(np0*sin(w*t) + Np0*t);
ycart = zeros(length(t),2);
ycart(:,1) = y(:,2).*cos(y(:,4)); % convert from polar to cartesian
ycart(:,2) = y(:,2).*sin(y(:,4));
% -- Numerical solution
options = odeset('Refine',128,'RelTol',0.0001);
[X1,q1] = ode45(@(X1,q1,e,p,a)pro3(X1,q1,0.02,1020,M), [0 10], [0], options);
[X3,q3] = ode45(@(X3,q3,e,p,a)pro5(X3,q3,0.02,1020,M), [0 10], [0], options);
q = zeros(length(q1), 3);
q(:,1) = q1;
%q(:,2) = (1./(1+e*cos(X1)))*(p);
zabadabadoo = 1./(1+e*cos(X1));
zabadabadee = p*M*zabadabadoo;
q(:,2) = zabadabadee;
q(:,3) = spline(X3,q3,X1);
qcart = zeros(length(q(:,1)),2);
qcart(:,1) = q(:,2).*cos(q(:,3)); % convert from polar to cartesian
qcart(:,2) = q(:,2).*sin(q(:,3));
% -- Plotting
viscircles([0 0], 3, 'Color', 'y'); hold on; % Event horizon * 1.5
plot(0,0,'k.'); hold on; % Black hole
axis([-1100 1100 -1100 1100]);
l1 = animatedline('Color','b'); % Animated lines to draw the paths
l2 = animatedline('Color','g'); % Animated lines to draw the paths
for k = 1:max(length(qcart(:,1)), length(ycart(:,1)))
if k <= length(qcart(:,1))
addpoints(l1, qcart(k,1), qcart(k,2));
end
if k <= length(ycart(:,1))
addpoints(l2, ycart(k,1), ycart(k,2));
end
pause(0.001);
drawnow;
end
|
function csiMatrixExtract = getElemFromCsiMatrix(csiMatrix,csiMatrixInfo,varargin)
%% Get the elements of the csiMatrix
% ===========================================================================
%% Syntax:
% elem = getElemFromCsiMatrix(csiMatrix) - Default case extracts all csi value
% elem = getElemFromCsiMatrix(csiMatrix,csiMatrixInfo,'Ntx',[1 3],'Nrx',[2 3]) - Link selection
%
% Tips:
% csiMatrixInfo - a necessary argument providing the broundaries to check
% the selection configs.
%
% Updating:
% Parsing 12/4/2020 - Created by Credo
% ===========================================================================
%% Input validation
p = inputParser; % Parser generation
% Adding csiMatrix validation rules
validFunCsiMatrix = @(x) ~isempty(x) && isstruct(x);
addRequired(p,'csiMatrix',validFunCsiMatrix);
% Adding csiMatrixInfo validation rules
validFunCsiMatrixInfo = @(x) ~isempty(x) && isstruct(x);
addRequired(p,'csiMatrixInfo',validFunCsiMatrixInfo);
% Adding timestamp_low validation rules
% - should be an increasing numeric array with size of [1,2]
% - should be in the range of timestamp_low refering to csiMatrixInfo
validFunTimestampLow = @(x) validateattributes(x, ...
'numeric', {'size', [1,2], 'increasing', ...
'>=',csiMatrixInfo.timestamp_low(1),'<=',csiMatrixInfo.timestamp_low(2)}, 'Rankings');
defaultTimestampLow = [0 0]; % Default value of 'timestamp_low'
addParameter(p,'timestamp_low',defaultTimestampLow,validFunTimestampLow); % timestamp_low
% Adding bfee_count validation rules
% - should be an increasing numeric array with size of [1,2]
% - should be in the range of bfee_count refering to csiMatrixInfo
validFunBfeeCount = @(x) validateattributes(x, ...
'numeric', {'size', [1,2], 'increasing', ...
'>=',csiMatrixInfo.bfee_count(1),'<=',csiMatrixInfo.bfee_count(2)}, 'Rankings');
defaultBfeeCount = [0 0]; % Default value of optional arg 'bfee_count'
addParameter(p,'bfee_count',defaultBfeeCount,validFunBfeeCount); % bfee_count
% Adding Nrx validation rules
nrxValidFun = @(x) validateattributes(x, ...
'numeric',{'>=',1,'<=',csiMatrixInfo.Nrx},'Rankings');
defaultNrx = 1:csiMatrixInfo.Nrx; % Default value of optional arg 'Nrx'
addParameter(p,'Nrx',defaultNrx,nrxValidFun);
% Adding Ntx validation rules
ntxValidFun = @(x) validateattributes(x, ...
'numeric',{'>=',1,'<=',csiMatrixInfo.Ntx},'Rankings');
defaultNtx = 1:csiMatrixInfo.Ntx; % Default value of optional arg 'Ntx'
addParameter(p,'Ntx',defaultNtx,ntxValidFun);
% Adding signal validation rules
defaultSignal = 'csi'; % Default value of optional arg 'signal'
expectedSignal = {'csi','rssi','all'};
addParameter(p,'signal',defaultSignal,...
@(x) any(validatestring(x,expectedSignal)));
% Adding MAC address validation rules
defaultMacAdd = "00:00:00:00:00:00"; % Default value of MAC_Des/MAC_Src
addParameter(p,'MAC_Des',defaultMacAdd,...
@(x) any(validatestring(x,csiMatrixInfo.MAC_Des))); % MAC_Des
addParameter(p,'MAC_Src',defaultMacAdd,...
@(x) any(validatestring(x,csiMatrixInfo.MAC_Src))); % MAC_Src
% Adding Payloads validation rules
defaultPayloads = "000000";
addParameter(p,'Payloads',defaultPayloads,...
@(x) any(validatestring(x,csiMatrixInfo.Payloads)));
parse(p,csiMatrix,csiMatrixInfo,varargin{:}); % Validation
%% Elements extraction
% Step 1. determine the satisfying sub-csiMatrix
csiMatrixCutoff = cutoffCsiMatrixBasedOnParser(csiMatrix,p);
% Step 2. extract the satifying elements from the csiMatrixCutoff
csiMatrixExtract = extractCsiMatrixBasedOnParser(csiMatrixCutoff,p);
end
function csiMatrixExtract = extractCsiMatrixBasedOnParser(csiMatrixCutoff,p)
% Determine the target antennas and signal
ntx = sort(unique(p.Results.Ntx));
nrx = sort(unique(p.Results.Nrx));
signal = p.Results.signal;
% Extracting the elements in the order of [tsl, bfee] - [csi] - [rssi]
csiMatrixExtract = [[csiMatrixCutoff.timestamp_low]',[csiMatrixCutoff.bfee_count]'];
switch signal
case 'csi'
csiMatrixExtract = [csiMatrixExtract, extractCsi(csiMatrixCutoff,ntx,nrx)];
case 'rssi'
csiMatrixExtract = [csiMatrixExtract, extractRssi(csiMatrixCutoff,nrx)];
case 'all'
csiMatrixExtract = [csiMatrixExtract, extractCsi(csiMatrixCutoff,ntx,nrx)];
csiMatrixExtract = [csiMatrixExtract, extractRssi(csiMatrixCutoff,nrx)];
end
end
function csiMatrixExtract = extractCsi(csiMatrixCutoff,ntx,nrx)
% Cellfun has some unkown bug that cannot successfully generate
% the csi matrix. Hence, we now uses a loop framework to get the
% csi matrix.
csiMatrixExtract = ...
zeros(length(csiMatrixCutoff),numel(ntx)*numel(nrx)*30);
for i = 1:length(csiMatrixCutoff)
idxInsert = 1;
for t = ntx
for r = nrx
csiMatrixExtract(i,idxInsert:idxInsert+30-1) = ...
csiMatrixCutoff(i).csi(t,csiMatrixCutoff(i).perm(r),:);
idxInsert = idxInsert + 30;
end
end
end
end
function csiMatrixExtract = extractRssi(csiMatrixCutoff,nrx)
% Only conforms to nrx
csiMatrixExtract = [];
if ismember(1,nrx)
csiMatrixExtract = [csiMatrixExtract, [csiMatrixCutoff.rssi_a]'];
end
if ismember(2,nrx)
csiMatrixExtract = [csiMatrixExtract, [csiMatrixCutoff.rssi_b]'];
end
if ismember(3,nrx)
csiMatrixExtract = [csiMatrixExtract, [csiMatrixCutoff.rssi_c]'];
end
csiMatrixExtract = [csiMatrixExtract, [csiMatrixCutoff.noise]'];
end
function csiMatrixCut = cutoffCsiMatrixBasedOnParser(csiMatrix,p)
idxCsiMatrixCut = ones(1,length(csiMatrix));
% timestamp_low
if ~ismember('timestamp_low',p.UsingDefaults)
idxTsl = arrayfun( ...
@(x) (x>=p.Results.timestamp_low(1) && x<=p.Results.timestamp_low(2)), ...
[csiMatrix(:).timestamp_low]);
idxCsiMatrixCut = idxCsiMatrixCut & idxTsl;
end
% bfee_count
if ~ismember('bfee_count',p.UsingDefaults)
idxBfee = arrayfun( ...
@(x) (x>=p.Results.bfee_count(1) && x<=p.Results.bfee_count(2)), ...
[csiMatrix(:).bfee_count]);
idxCsiMatrixCut = idxCsiMatrixCut & idxBfee;
end
% MAC_Des
if ~ismember('MAC_Des',p.UsingDefaults)
idxMacDes = arrayfun( ...
@(x) (contains(x,p.Results.MAC_Des)), {csiMatrix(:).MAC_Des});
idxCsiMatrixCut = idxCsiMatrixCut & idxMacDes;
end
% MAC_Src
if ~ismember('MAC_Src',p.UsingDefaults)
idxMacSrc = arrayfun( ...
@(x) (contains(x,p.Results.MAC_Src)), {csiMatrix(:).MAC_Src});
idxCsiMatrixCut = idxCsiMatrixCut & idxMacSrc;
end
% Payloads
if ~ismember('Payloads',p.UsingDefaults)
idxPayloads = arrayfun( ...
@(x) (contains(x,p.Results.Payloads)), {csiMatrix(:).Payloads});
idxCsiMatrixCut = idxCsiMatrixCut & idxPayloads;
end
csiMatrixCut = csiMatrix(idxCsiMatrixCut==1);
end |
function E = tdiffuse(I, N, lambda)
% function TDIFFUSE apply isotropic diffusion filtering on image I
% This function is written by VU Anh Tuan, so it's called tdiffuse
% set default value to lambda
if nargin == 2
lambda = 0.2;
end
% initial
E = double(I);
dims = size(E,3);
switch dims
case 1 % grayscale image
for i = 1:N
E = E + lambda*lapla(E);
end
if max(E(:)) > 1 % E is out of range [0;1]
E = E/max(E(:));
end
case 3 % color image
E(:,:,1) = tdiffuse(E(:,:,1), N, lambda);
E(:,:,2) = tdiffuse(E(:,:,2), N, lambda);
E(:,:,3) = tdiffuse(E(:,:,3), N, lambda);
end |
function [ feat, featNames ] = extractFeatures_IDGait(rightAcc,leftAcc,sf,windowSize,overlap)
%Reed Gurchiek, 2018
% extract features from left and right anterior thigh accelerometer data.
%
%---------------------------INPUTS-----------------------------------------
%
% rightAcc, leftAcc:
% 3xn accelerometer data from left and right anterior thigh in thigh
% frame. acceleration along segment long axis should be row 3
%
% sf:
% sampling frequency
%
% windowSize:
% size of the window in seconds
%
% overlap:
% 0 < x < 1. percent overlap of windows (e.g. 0 means data is not
% shared between windows, 1 means 1 sample of data is not shared
% between windows, 0.5 means 50% of data is shared between windows
%
%--------------------------OUTPUTS-----------------------------------------
%
% feat:
% pxm, m windows and p features characterizing each window
%
% featNames:
% px1, name of feature in corresponding column of feat
%
%--------------------------------------------------------------------------
%% extractFeatures_IDGait
% data loop
i = 1; %window index
feat = zeros(48,1);
featNames = {'rzrm' 'lzrm' 'rhrm' 'lhrm' 'rzrv' 'lzrv' 'rhrv' 'lhrv' 'rzrs' 'lzrs' 'rhrs' 'lhrs' 'rzrk' 'lzrk' 'rhrk' 'lhrk' 'rzlm' 'lzlm' 'rzlv' 'lzlv' 'rzls' 'lzls' 'rzlk' 'lzlk'...
'rzrp1' 'rzrw1' 'rzrp2' 'rzrw2' 'lzrp1' 'lzrw1' 'lzrp2' 'lzrw2' 'rhrp1' 'rhrw1' 'rhrp2' 'rhrw2' 'lhrp1' 'lhrw1' 'lhrp2' 'lhrw2'...
'xrzrlzr' 'lagrzrlzr' 'xrzrlzl' 'lagrzrlzl' 'xrzllzr' 'lagrzllzr' 'xrzllzl' 'lagrzllzl'};
ns = round(sf*windowSize); %samples per window
s1 = 1; %window starting index
s2 = ns; %window ending index
inc = ns - overlap*ns; %samples to slide between windows
if inc < 1; inc = 1; end
nsamp = min([length(rightAcc) length(leftAcc)]); %total samples
w = fftfreq(sf,ns); %frequencies for fft
w([1 round(ns/2):end]) = []; %remove negative and DC frequency
nw = length(w);
while s2 <= nsamp
% window data and extract signals
rz = rightAcc(3,s1:s2);
lz = leftAcc(3,s1:s2);
rzl = filtmat_class(1/sf,1,rz',1,2)';
lzl = filtmat_class(1/sf,1,lz',1,2)';
rh = resultant(rightAcc(1:2,s1:s2));
lh = resultant(leftAcc(1:2,s1:s2));
% raw z/horizontal acc mean, variance, skewness, kurtosis
feat(1:4,i) = [mean(rz); mean(lz); mean(rh); mean(lh)];
feat(5:8,i) = [var(rz); var(lz); var(rh); var(lh)];
feat(9:12,i) = [skewness(rz); skewness(lz); skewness(rh); skewness(lh)];
feat(13:16,i) = [kurtosis(rz); kurtosis(lz); kurtosis(rh); kurtosis(lh)];
% low pass z acc mean, variance, skewness, kurtosis
feat(17:18,i) = [mean(rzl); mean(lzl)];
feat(19:20,i) = [var(rzl); var(lzl)];
feat(21:22,i) = [skewness(rzl); skewness(lzl)];
feat(23:24,i) = [kurtosis(rzl); kurtosis(lzl)];
% raw z/horizontal in frequency domain (without negative or 0 freq)
frz = fft(rz); frz(nw+1:end) = []; frz(1) = [];
flz = fft(lz); flz(nw+1:end) = []; flz(1) = [];
frh = fft(rh); frh(nw+1:end) = []; frh(1) = [];
flh = fft(lh); flh(nw+1:end) = []; flh(1) = [];
% raw z/horizontal top 3 most dominant frquencies and their percentage power
[frzm,ifrzm] = extrema(abs(frz)); [frzm,isort] = sort(frzm,'descend'); frzm = frzm(1:3)./sum(abs(frz)); isort(4:end) = []; frzmw = w(ifrzm(isort));
[flzm,iflzm] = extrema(abs(flz)); [flzm,isort] = sort(flzm,'descend'); flzm = flzm(1:3)./sum(abs(flz)); isort(4:end) = []; flzmw = w(iflzm(isort));
[frhm,ifrhm] = extrema(abs(frh)); [frhm,isort] = sort(frhm,'descend'); frhm = frhm(1:3)./sum(abs(frh)); isort(4:end) = []; frhmw = w(ifrhm(isort));
[flhm,iflhm] = extrema(abs(flh)); [flhm,isort] = sort(flhm,'descend'); flhm = flhm(1:3)./sum(abs(flh)); isort(4:end) = []; flhmw = w(iflhm(isort));
% include in feature set
feat(25:28,i) = [frzm(1); frzmw(1); frzm(2); frzmw(2)];
feat(29:32,i) = [flzm(1); flzmw(1); frzm(2); flzmw(2)];
feat(33:36,i) = [frhm(1); frhmw(1); frhm(2); frhmw(2)];
feat(37:40,i) = [flhm(1); flhmw(1); flhm(2); flhmw(2)];
% cross correlation
[x,lag] = xcorr(rz,lz);
[feat(41,i),imax] = max(x); feat(42,i) = abs(lag(imax));
[x,lag] = xcorr(rz,lzl);
[feat(43,i),imax] = max(x); feat(44,i) = abs(lag(imax));
[x,lag] = xcorr(rzl,lz);
[feat(45,i),imax] = max(x); feat(46,i) = abs(lag(imax));
[x,lag] = xcorr(rzl,lzl);
[feat(47,i),imax] = max(x); feat(48,i) = abs(lag(imax));
% next window
s1 = s1 + inc;
s2 = s2 + inc;
i = i + 1;
end |
function [psth_final,fras] = get_fras(data_root,grid,sorted_root)
start_time_s = 0;
end_time_s = 2100;
chunk_s = 50;
synch_ch = load_synch(data_root,start_time_s,end_time_s,chunk_s);
trig_min_length = 3000; %The minimum length of one trigger in samples
qualityOpt = 'nonoise';
Y = get_spike_times(sorted_root,qualityOpt);
sweep_duration_ms = 200; %The duration of one time interval of interest in ms. Actual Benware sweep duration is around 105.2ms
t_bin_ms = 5; %Time bin in ms
fs_s = 30000; %Sampling rate in samples/s
num_dB_levels = 5; %The number of different dB levels that were presented
num_freq = 15; %The number of different freq
num_stim = num_dB_levels*num_freq; %Totla number of stimuli
% t_ms = [0:t_bin_ms:sweep_duration_ms]; %The edges of the histogram
t_ms = [-50:t_bin_ms:sweep_duration_ms]; %The edges of the histogram
diff_sig = diff(synch_ch); %Find the difference between every n+1 sample - n sample. This tells us the the beginning/end of each sweep
%Find the sample no for the beginning of each sweep
start_ix = find(diff_sig==1); %Note that this diff will differ depending on which sync channel we use so always check it before analyzing
end_ix = find(diff_sig==-1); %Note that this diff will differ depending on which sync channel we use so always check it before analyzing
start_ix = start_ix(1:length(end_ix));
diff_ix = end_ix - start_ix; %Find the length of each sweep in samples
start_ix = start_ix(diff_ix >= trig_min_length); %Keep only the triggers which have length >= minimum triger length
start_ix_ms = (start_ix/fs_s).*1000; %Convert the starting sample numbers to times in ms
num_triggers = length(start_ix);
spike_times_ms = Y(:,1).*1000; % Get the spike times in ms
clusters = Y(:,2);
cluster_id = unique(clusters); %Sort the clusters which are good in ascending order
total_no_clusters = length(cluster_id); %The total number of unqiue clusters
psth = cell(num_stim,total_no_clusters); %Initialize the psth variable
%Find the psths for every cluster, stimulus and repetition and store
%them in a cell array
parfor cluster = 1:total_no_clusters
current_cluster_id = cluster_id(cluster);
fprintf('== Processing cluster %.0f/%.0f ==\n',cluster,total_no_clusters);
for stim = 1:num_stim
ix_rep = find(grid.randomisedGridSetIdx(1:num_triggers,1)==stim);
ix_rep_ms = start_ix_ms(ix_rep);
for rep = 1:length(ix_rep)
psth{stim,cluster}(rep,:) = histc(spike_times_ms(clusters == current_cluster_id),ix_rep_ms(rep) + t_ms);
end
psth{stim,cluster} = psth{stim,cluster}(:,1:end-1); %Delete the last bin which is weird
end
end
avg_psth = cellfun(@(x)(mean(x,1)),psth,'UniformOutput',false); %Find the average across repetitions
%Convert the cell array into 3D array with dimesnions stimuli x
%clusters x time bins
int_mat = cellfun(@(x)reshape(x,1,1,[]),avg_psth,'un',0);
psth_final(:,:,:) = cell2mat(int_mat);
fras = reshape(psth_final,num_dB_levels,num_freq,total_no_clusters,length(t_ms)-1); %Reshape the mean_psth into an fra
end
|
function [A,B,C,freq,varargout] = cosFit(t,P,...
A0,ABnd,...
B0,BBnd,...
C0,CBnd,...
freq0,freqBnd)
% SinDecayFit fits curve P = P(t) with a Sinusoidal Decay function:
% P = A*(cos(2*pi*freq*t+B)+C));
%
% varargout{1}: ci, 4 by 2 matrix, ci(4,1) is the lower bound of 'freq'
%
% Yulin Wu, SC5,IoP,CAS. mail4ywu@gmail.com
% $Revision: 1.1 $ $Date: 2012/10/18 $
Coefficients(1) = A0;
Coefficients(2) = B0;
Coefficients(3) = C0;
Coefficients(4) = freq0;
lb = [ABnd(1),BBnd(1),CBnd(1),freqBnd(1)];
ub = [ABnd(2),BBnd(2),CBnd(2),freqBnd(2)];
for ii = 1:3
[Coefficients,~,residual,~,~,~,J] = lsqcurvefit(@cos_,Coefficients,t,P,lb,ub);
end
A = Coefficients(1);
B = Coefficients(2);
C = Coefficients(3);
freq = Coefficients(4);
if nargout > 4
varargout{1} = nlparci(Coefficients,residual,'jacobian',J);
end
function [P]=cos_(Coefficients,t)
A = Coefficients(1);
B = Coefficients(2);
C = Coefficients(3);
freq = Coefficients(4);
P = A*(cos(2*pi*freq*t+B)+C);
|
function R=MyBTST_V4(LongPrice,ShortPrice,OpenLongPosNum,OpenShortPosNum,Cash,CloseLongPosNum,CloseShortPosNum)
%% Long
% OL = Open long Position Price
% CL = Close long Position Price
% CountLW = Count long win times
% CountLL = Count long lose times
% LPL = long Profit and lost
% LMaxW = long maximum win
% LMaxL = long maximum win
% LT = long tades
% LWR = long win ratio
% LD = Long Duration
% SD = Short Duration
% AD = Average Duration
OL=LongPrice(LongPrice<0);
CL=LongPrice(LongPrice>0);
% [SBars,LBars,LSPF,SSPF,CountLW,CountLL,CountSW,CountSL,SMaxB,LMaxB]=MyCount(LongPrice,ShortPrice);
% RR=[SBars,LBars,LW,LL,SW,SL,SMaxB,LMaxB];
[RR,LSPF,SSPF]=MyCount_V2(LongPrice,ShortPrice);
SBars=RR(1);
LBars=RR(2);
CountLW=RR(3);
CountLL=RR(4);
CountSW=RR(5);
CountSL=RR(6);
SMaxB=RR(7);
LMaxB=RR(8);
LPL=sum(LSPF);
LMaxW=max(LSPF);
LMaxL=min(LSPF);
LWR=CountLW/(CountLW+CountLL);
LT=OpenLongPosNum;
LD=OpenLongPosNum/CloseLongPosNum;
%% Short
% OS = Open short Position Price
% CS = Close short Position Price
% CountSW = Count short win times
% CountSL; = Count short lose times
% SPL = Short Profit and lost
% SMaxW = long maximum win
% SMaxL = long maximum win
% ST = Short trades
% SWR = short win ratio
OS=ShortPrice(ShortPrice>0); % OS(OpenShortPosPrice==0)=[];
CS=ShortPrice(ShortPrice<0); % CS(CloseShortPosPrice==0)=[];
SPL=sum(SSPF);
SMaxW=max(SSPF);
SMaxL=min(SSPF);
SWR=CountSW/(CountSW+CountSL);
ST=OpenShortPosNum;
SD =OpenShortPosNum/CloseShortPosNum;
%% Total
% TTPL = total profit and lost
% TTW = total win times
% TTL = total lose times
% TTT = total trades
% TWR = total win ratio
% TLR = total lose ratio
% MW = max win
% ML = max lose
TTPL=sum(Cash);
TTW=CountSW+CountLW;
TTL=CountSL+CountLL;
TTT=TTW+TTL;
TWR=TTW/TTT;
TLR=TTL/TTT;
MW=max(LMaxW,SMaxW);
ML=max(LMaxL,SMaxL);
AD = (OpenLongPosNum+OpenShortPosNum)/(CloseLongPosNum+CloseShortPosNum);
%% BTST Results
R=[TTW,TTL,CountLW,CountLL,CountSW,CountSL,TTPL,LPL,SPL,TTT,LT,ST,TLR,TWR,MW,SMaxW,LMaxW,ML,LMaxL,SMaxL,SBars,LBars,AD,LD,SD];
% fprintf('Total trades times %d \n ',TTT);
% fprintf('Total win times %d \n ',TTW);
% fprintf('Total lose times %d \n ',TTL);
% fprintf('Total win ratios %d \n ',TWR);
% fprintf('Long Total Bars %d \n ',LBars);
% fprintf('Short Total Bars %d \n ',SBars);
% fprintf('Long max single Bars %d \n ',LMaxB);
% fprintf('Short max single Bars %d \n ',SMaxB);
% fprintf('Long Wins times %d \n ',CountLW);
% fprintf('Long Lose times %d \n ',CountLL);
% fprintf('Short Wins times %d \n ',CountSW);
% fprintf('Short Lose times %d \n ',CountSL);
% fprintf('Long maximum win %d \n ',LMaxW);
% fprintf('Long maximum lose %d \n ',LMaxL);
% fprintf('Short maximum wins %d \n ',SMaxW);
% fprintf('Short maximum lose %d \n ',SMaxL);
% fprintf('Total paylost %d \n ',TTPL);
% fprintf('Long paylost %d \n ',LPL);
% fprintf('Short paylost %d \n ',SPL);
% fprintf('Long trade times %d \n ',LT);
% fprintf('Short trades times %d \n ',ST);
% fprintf('Total average Duration %d \n ',AD);
% fprintf('Long Duration %d \n ',LD);
% fprintf('Short Duration %d \n ',SD); |
%%%
%%% Arguments:
%%% reaction - a KeggReaction object
%%% Returns:
%%% the CC estimation for this reaction's untransformed dG0 (i.e.
%%% using the major MS at pH 7 for each of the reactants)
function [dG0_cc, U] = getStandardGibbsEnergyUsingCC(params, reactions)
v_r = params.dG0_cc;
v_g = params.dG0_gc;
C1 = params.preprocess_C1;
C2 = params.preprocess_C2;
C3 = params.preprocess_C3;
X = zeros(shape(C1, 2), length(reactions));
G = zeros(shape(C2, 2), length(reactions));
for i = 1:length(reactions)
x, g = % use python do decompose the reaction string into x and g: self._decompose_reaction(reaction)
X(:, i) = x;
G(:, i) = g;
dG0_cc = X' * v_r + G' * v_g;
U = X' * C1 * X + X' * C2 * G + G' * C2' * X + G' * C3 * G;
|
%{
Post=process data
%}
G1 = rmnode(G, top_soc_k);
G2 = rmnode(G, top_kaz);
G3 = rmnode(G, top_deg);
A1 = G1.adjacency;
G1_ = graph(A1);
A2 = G2.adjacency;
G2_ = graph(A2);
A3 = G3.adjacency;
G3_ = graph(A3);
g1map = node_mapping_rmnode(G.numnodes, top_soc_k);
g2map = node_mapping_rmnode(G.numnodes, top_kaz);
g3map = node_mapping_rmnode(G.numnodes, top_deg);
%[soc_cover, katz_cover, deg_cover, top_kaz, top_soc_k, top_deg, install, test_nodes] = experiment_1(G,G.adjacency);
%fprintf('%.2f %.2f %.2f %5d %5d %5d %5d \n', soc_cover, katz_cover, deg_cover, ...
% G1.outdegree(g1map(test_nodes)), G2.outdegree(g2map(test_nodes)),...
% G3.outdegree(g3map(test_nodes)), test_nodes)
[soc_cover, katz_cover, deg_cover, ...
G1.outdegree(g1map(test_nodes)), G2.outdegree(g2map(test_nodes)),...
G3.outdegree(g3map(test_nodes))];
|
function [labels,dis_iou] = gen_anchor_labels(bbox_input,anchors,dis)
iou = overlap_ratio(bbox_input,anchors);
labels(iou==0) = -1;
% set pos
labels(iou>max(iou)*0.6) = 1;
labels = reshape(labels,[size(labels,2),1]);
% ignore some neg samples to keep sample balance
temp_where = find(labels == 0);
if length(temp_where) > 64
ignore = randsample(temp_where,size(temp_where,1)-64);
labels(ignore) = -1;
end
temp_where = find(labels == 1);
if length(temp_where) > 64
ignore = randsample(temp_where,size(temp_where,1)-64);
labels(ignore) = -1;
end
if dis
dis_iou(:,:,1) = reshape(iou(1:3:end),[16,16])';
dis_iou(:,:,2) = reshape(iou(2:3:end),[16,16])';
dis_iou(:,:,3) = reshape(iou(3:3:end),[16,16])';
% iou = permute(iou, [2, 1, 3]);
for i = 1:3
subplot(1,3,i);
imshow(dis_iou(:,:,i));
end
end
|
function [M] = constructMean(sampind)
%construct mean aggregation matrix
N = sum(sampind);
regionnum = length(sampind);
meanvector = 1./sampind;
ivec = zeros(N,1);
jvec = zeros(N,1);
vvec = zeros(N,1);
ind = 1;
for i = 1:regionnum;
startpoint = 1 + (i-1)*sampind(i);
endpoint = sum(sampind(1:i));
for j = startpoint:endpoint
ivec(ind,1) = i;
jvec(ind,1) = j;
vvec(ind,1) = meanvector(i);
ind = ind + 1;
end
end
M = sparse(ivec,jvec,vvec,regionnum,N);
end |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Wavelet Compression %
% - Suhong Kim - %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clc; clear all; close all;
if isfolder('./output') ~= 1, mkdir('./output'); end
g_img = imread('moon.tif');
%% Float/Integer Binary Haar Wavelet
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
level = inf; % inf is max level
isInt = true; % Integer
visible = 'off'; % plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Binary Haar starts ...');
[c_img, h, v] = haar_decomp(g_img, level, isInt, visible);
f_img = haar_reconst(c_img, h, v, level, isInt, visible);
disp('Binary Haar is Done!(All images are saved)');
% check output
g_img = imresize(g_img, size(f_img));
checkM = (g_img == uint8(f_img));
if(size(f_img,1)*size(f_img,2) == sum(checkM(:)))
disp('-->Input and Output are same!');
end
%% Float/Integer Ternary Wavelet
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
level = inf; % inf is max level
isInt = true; % Integer
visible = 'off'; % plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Ternary Wavelet starts ...');
[c_img, h, v] = ternary_decomp(g_img, level, isInt, visible);
f_img = ternary_reconst(c_img, h, v, level, isInt, visible);
disp('Ternary Wavelet is Done!(All images are saved)');
% check output
g_img = imresize(g_img, size(f_img));
checkM = (g_img == uint8(f_img));
if(size(f_img,1)*size(f_img,2) == sum(checkM(:)))
disp('-->Input and Output are same!');
end |
% Logistic regression demo on dummy 2D data
close all
clear
[X_train, X_test, y_train, y_test] = sklearn_data_2clusters();
f1 = figure; hold all
plot(X_train(y_train==0,1),X_train(y_train==0,2),'o')
plot(X_train(y_train==1,1),X_train(y_train==1,2),'o')
title('Training data')
clf = LogisticRegression;
clf.fit(X_train,y_train);
proba = clf.predict_proba(X_test);
[perfx,perfy,T,AUC] = perfcurve(y_test,proba,true);
fprintf('AUC = %.4f\n',AUC)
f2 = figure; plot(perfx,perfy)
xlabel('False positive rate')
ylabel('True positive rate')
title('ROC for Classification by Logistic Regression')
|
function [itcz_mx,itcz_cm,imeta] = itcz_lon(pr,lat,lon,lonext)
%ITCZ Compute the latitude of the ITCZ over certain longitudinal range
% [itcz_mx,itcz_cm] = itcz_lon(pr,lat,lon,lonext)
% Input: pr = annual pr field (lat,lon,time)
% lat/lon = (code currently assumes regular lat/lon grid)
% lonext = longitudinal extent (two element vector), left to
% right bounds (e.g., lonext=[343 52] for Africa)
% Output: itcz_mx = ITCZ expectation maximum latitude
% itcz_cm = ITCZ center of mass latitude
% imeta = metadata of ITCZ variable and also the two above variables
%
% ITCZ_max = latitude of expected latitudes using a weighting function of
% an integer power N=10 of the area-weighted precipitation P integrated over
% the tropics. See Adam et al 2016: https://doi.org/10.1175/JCLI-D-15-0512.1
%
% ITCZ_cent = precipitation centroid "defined as the median of the zonal
% average precipitation from 20S to 20N. The precipitation is
% interpolated to a 0.1deg grid over the tropics to allow the precipitation
% centroid to vary at increments smaller than the grid spacing."
%
% Nathan Steiger, November 2016
%
% Significantly modified by N. Steiger June 2017 to account for an
% improved definition of the ITCZ location; mods Nov 2017
%
% Create variable metadata
imeta.lon1=lonext(1);imeta.lon2=lonext(2);
%imeta.indxnm='';
% Find nearest lat/lon equal to or outside bounds
ln_a=find((abs(lon-lonext(1))-min(abs(lon-lonext(1))))<1e-5);
ln_b=find((abs(lon-lonext(2))-min(abs(lon-lonext(2))))<1e-5);
% if two equal mins, pick one outside of bounds
l1=min(ln_a);l2=max(ln_b);
% Get indices for extracting precip
if l1>l2
lon_idx=[l1:length(lon) 1:l2];
elseif l2>l1
lon_idx=l1:l2;
end
% get tropical precip (using +-30 to account for "monsoon" land areas)
trop_idx=find(lat<= 30 & lat >= -30);
trop_pr=pr(trop_idx,lon_idx,:);
% interpolate to high resolution
tlat=lat(trop_idx);
% spacing = 0.1,
%sp=0.1;x1=min(tlat);x2=max(tlat);
%npts=(sp-x1+x2)/sp;
hhlat=min(tlat):0.1:max(tlat);
%hhlat=linspace(-30,30,601); % 0.1 degree grid in latitude
[~,~,t]=size(trop_pr);
[X,Y] = meshgrid(1:length(lon(lon_idx)),hhlat);
[X1,Y1] = meshgrid(1:length(lon(lon_idx)),tlat);
cdata=zeros(length(hhlat),length(lon(lon_idx)),t);
for j=1:t
cdata(:,:,j) = interp2(X1,Y1,trop_pr(:,:,j),X,Y);
end
% Take zonal mean
P=squeeze(mean(cdata,2));
% Compute expected latitudes following equation 1 in
% Adam et al 2016
phi=hhlat(:);
itcz_mx=zeros(length(t),1);
for i=1:t
itcz_mx(i)=sum(phi.*power(cosd(phi).*P(:,i),10))/sum(power(cosd(phi).*P(:,i),10));
end
itcz_cm=zeros(length(t),1);
for i=1:t
itcz_cm(i)=sum(phi.*cosd(phi).*P(:,i))/sum(cosd(phi).*P(:,i));
end
% Put variable into the structure
imeta.itcz_mx=itcz_mx;
imeta.itcz_cm=itcz_cm;
end
|
function [ tFilter, tFilterName ] = GetFilter( varargin )
% [ tFilter tFilterName ] = GetFilter( iF, tNFr, tFilterName, tOrder )
% v.1 = v.0 + ability to handle variable tOrder parameter (and, in general,
% other parameters as well) through the magic of varargin.
tFilters = { ...
'1f1' 'ParseFilterName'; ...
'1f2' 'ParseFilterName'; ...
'2f1' 'ParseFilterName'; ...
'2f2' 'ParseFilterName'; ...
'1f1+1f2' 'ParseFilterName'; ...
'nf1' 'CustomFilter'; ...
'nf2' 'CustomFilter'; ...
'f2band' 'CustomFilter'; ...
'nf1clean' 'CustomFilter'; ...
'nf2clean' 'CustomFilter'; ...
'nf1low15' 'CustomFilter'; ...
'nf1low10' 'CustomFilter'; ...
'rbtx-nf1' 'CustomFilter'; ...
'rbtx-nf2' 'CustomFilter'; ...
'rbtx-im' 'CustomFilter'; ...
'none' 'CustomFilter' ...
};
if nargin < 2
error( 'GetFilter requires first two args: iF, tNFr');
return;
end
if nargin == 2
[ iF, tNFr ] = deal( varargin{1:2} );
tFilterName = ChooseFilterFromList( iF, tNFr );
[ tFilter tFilterName ] = GetFilter( iF, tNFr, tFilterName );
else
tFilterName = lower( varargin{ 3 } );
try
tiF = strmatch( tFilterName, tFilters( :, 1 ), 'exact' );
% tFilter = tFilters{ tiF, 2 }( varargin{:} ); v.7 uses pointers
tFStr = 'tFilter = FILTERFUNCTION( varargin{:} );';
tFStr = strrep( tFStr, 'FILTERFUNCTION', tFilters{ tiF, 2 } );
eval( tFStr );
catch
if strmatch( tFilterName, 'getfilterlist', 'exact' )
tFilter = [];
tFilterName = tFilters( :, 1 );
else
% msgbox( 'Unknown filter; Choose from following list...', 'modal' );
[ tFilter tFilterName ] = GetFilter( varargin{1:2} ); % will invoke ChooseFilterFromList
end
end
end
function [ tFilter, tFilterName ] = ParseFilterName( varargin )
% We use varargin for function handle conformity with CustomFilter
[ iF, tNFr, tFN ] = deal( varargin{1:3} );
tiF1 = str2num( tFN( findstr( 'f1', lower( tFN ) ) - 1 ) );
if isempty( tiF1 )
tiF1 = 0;
end
tiF2 = str2num( tFN( findstr( 'f2', lower( tFN ) ) - 1 ) );
if isempty( tiF2 )
tiF2 = 0;
end
tFilterCoefs = [ tiF1 tiF2 ];
tFilter = sum( iF .* tFilterCoefs );
tFilterName = tFN;
function [ tFilter, tFilterName ] = CustomFilter( varargin )
[ iF, tNFr, tFilterName ] = deal( varargin{1:3} );
tOrder = 8;
if nargin == 4
tOrder = varargin{ 4 };
end
switch lower( tFilterName )
case 'nf1'
tFilter = [ iF(1):iF(1):( min( [ tNFr iF(1)*tOrder ] ) ) ]'; % eg., RBTX1: 1 2 3 4 8
case 'nf2'
tFilter = [ iF(2):iF(2):( min( [ tNFr iF(2)*tOrder ] ) ) ]';
case 'f2band'
t1F2 = GetFilter( iF, tNFr, '1f2' );
tNF1 = GetFilter( iF, tNFr, 'nf1', tOrder );
tFilter = t1F2 + [ -tNF1(end:-1:1); 0; tNF1(:) ];
case 'nf1clean'
tNF1 = GetFilter( iF, tNFr, 'nf1', floor( tNFr / iF(1) ) );
tNF2 = GetFilter( iF, tNFr, 'nf2', floor( tNFr / iF(2) ) );
tFilter = setxor( tNF1, intersect( tNF1, tNF2 ) );
case 'nf2clean'
tNF1 = GetFilter( iF, tNFr, 'nf1', floor( tNFr / iF(1) ) );
tNF2 = GetFilter( iF, tNFr, 'nf2', floor( tNFr / iF(2) ) );
tFilter = setxor( tNF2, intersect( tNF1, tNF2 ) );
case 'nf1low15'
% low pass version of nf1; nF2 and IM terms are not removed.
% Only intended for conditions with low global/noise
% frequency and high update frequencies.
% Hard-coded cut at 15Hz if f1 = 1Hz...
tFilter = GetFilter( iF, tNFr, 'nf1', 15 );
case 'nf1low10'
% Hard-coded cut at 10Hz if f1 = 1Hz...
tFilter = GetFilter( iF, tNFr, 'nf1', 10 );
case 'rbtx-nf1'
tFilter = iF(1) * [ 1 2 3 4 8 ]';
case 'rbtx-nf2'
tFilter = iF(2) * [ 1 2 3 4 8 ]';
case 'rbtx-im'
tCoeffs = [ 2 -1; -1 2; 3 -1; 1 1; -1 3; 2 1; 1 2; 1 3; 2 2; 1 3 ];
tFilter = sum( tCoeffs .* repmat( iF, size( tCoeffs, 1 ), 1 ), 2 );
case 'none'
tFilter = [ 1:tNFr ]'; % eg., RBTX1: 1 2 3 4 8
otherwise
error( 'Unknown filter name' );
end
function tFilterName = ChooseFilterFromList( iF, tNFr )
[ tFilter tFiltNames ] = GetFilter( iF, tNFr, 'getfilterlist' );
tFilterName = tFiltNames{ ...
listdlg( 'ListString', tFiltNames, 'SelectionMode', 'single', 'PromptString', 'Choose a filter' ) };
|
% Define parameters
e_max = 0.2;
t_alpha = 1;
alpha_0 = 0.7;
% Get data
train = Y_train_F2{1,2}(1:10,:);
test = Y_test_F2{1,2}(1:10,:);
Seizure_time = seizure{1,2};
% start_seiz = floor(Seizure_time(1)/8);
% end_seiz = ceil(Seizure_time(end)/8);
% Seizure_time = start_seiz:end_seiz;
title_plot{1,2}
train_mean = mean(train,2);
train_std = std(train')';
train = (train-train_mean)./train_std;
test = (test-train_mean)./train_std;
[K_vec, y, sig2, Mahalanobis_dist_vec_train, Q_t_vec] = model2_new_cooling(train, 'e_max', e_max, 't_alpha', t_alpha, 'aplpha_0', alpha_0);
%% Plots
e_max = 0.2;
Q_t_max = 2*log(1./e_max)
outlier_index = []
clear Mahalanobis_dist_vec_test Mahalanobis_dist_vec_train
for i = 1:length(test)
x_t = test(:,i);
Mahalanobis_dist = diag((x_t - y')'*(x_t - y'))./sig2;
Mahalanobis_dist = min(Mahalanobis_dist);
Mahalanobis_dist_vec_test(i) = Mahalanobis_dist;
if Mahalanobis_dist > Q_t_max
outlier_index = [outlier_index i];
end
end
for i = 1:length(train)
x_t = train(:,i);
Mahalanobis_dist = diag((x_t - y')'*(x_t - y'))./sig2;
Mahalanobis_dist = min(Mahalanobis_dist);
Mahalanobis_dist_vec_train(i) = Mahalanobis_dist;
if Mahalanobis_dist > Q_t_max
outlier_index = [outlier_index i];
end
end
% Mahalanobis dist for both train and test
figure()
subplot(1,2,1)
plot(Mahalanobis_dist_vec_train)
hold on
plot(repmat(Q_t_max, 1,length(Mahalanobis_dist_vec_train)),'LineWidth', 1.5)
xlabel('Time (s)', 'FontSize', 16)
ylabel('Smallest Mahalanobis distance', 'FontSize', 14)
title('Training data')
yticks(Q_t_max)
yticklabels('Q_t(\epsilon_{max})')
axis([0 3600 0 50])
subplot(1,2,2)
plot(Mahalanobis_dist_vec_test)
hold on
plot(repmat(Q_t_max, 1,length(Mahalanobis_dist_vec_test)),'LineWidth', 1.5)
xlabel('Time (s)', 'FontSize', 16)
ylabel('Smallest Mahalanobis distance', 'FontSize', 14)
title('Test data')
yticks(Q_t_max)
yticklabels('Q_t(\epsilon_{max})')
axis([0 3600 0 50])
% K
figure()
plot(K_vec)
xlabel('t')
ylabel('#K')
% Log plot
ten_worst = zeros(1,length(test));
ten_worst(outlier_index) = 1;
figure()
b1 = bar(ten_worst, 'b','EdgeColor', 'b', 'EdgeAlpha', 0.05)
hold on
bar(Seizure_time, ten_worst(Seizure_time), 'r','EdgeColor', 'r')
legend('Non-Seizure','Seizure')
alpha(b1, 0.5)
b1.EdgeAlpha = 0.10
hold on
% title(['Most abnormal datapoints(' num2str(Q_t_max) '%), or outliers, for ' Plot_title])
axis([0 length(ten_worst) 0 1.2])
xlabel('Time (s)')
yticks([1])
yticklabels('Outliers')
%% Plot K vec and test mahananobis dist for different e_max
e_max = [0.1 0.4 0.7];
y_cell = {};
sig2_cell = {};
figure()
for i = 1:length(e_max)
[K_vec, y, sig2] = model2_new_cooling(train,test, 'e_max', e_max(i), 't_alpha', t_alpha, 'aplpha_0', alpha_0);
y_cell{1,i} = y;
sig2_cell{1,i} = sig2;
plot(K_vec, 'LineWidth', 2)
hold on
end
ylabel('K_t', 'FontSize', 16)
xlabel('iterations (t)', 'FontSize', 16)
legend('e_{max}: 0.1', 'e_{max}: 0.4', 'e_{max}: 0.7')
set(gca, 'FontSize', 16)
figure()
for i = 1:length(e_max)
y = y_cell{1,i};
sig2 = sig2_cell{1,i};
for t = 1:length(test)
x_t = test(:,t);
Mahalanobis_dist = diag((x_t - y')'*(x_t - y'))./sig2;
Mahalanobis_dist = min(Mahalanobis_dist);
Mahalanobis_dist_vec_test(t) = Mahalanobis_dist;
end
Q_t_max = 2*log(1./e_max(i));
subplot(3,1,i)
plot(Mahalanobis_dist_vec_test)
hold on
h1 = plot(repmat(Q_t_max, 1,length(Mahalanobis_dist_vec_test)),'LineWidth', 1.5)
legend([h1], {['e_{max}: ' num2str(e_max(i))]})
axis([0 3600 1 15]);
xlabel('Time (s)','FontSize', 16)
ylabel('Mahalanobis distance','FontSize', 16)
end
%% Log plot for many iter
Q_t_max = 2*log(1./e_max);
iter_vec = [1 10 25 50 75 100];
clear Outlier_matrix
e_max = 0.2;
opt_num_pc = num_pc(2);
train = Y_train_F2{1,2}(1:opt_num_pc,:);
test = Y_test_F2{1,2}(1:opt_num_pc,:);
Seizure_time = seizure{1,2};
% Standardise data
train_mean = mean(train,2);
train_std = std(train')';
train = (train-train_mean)./train_std;
test = (test-train_mean)./train_std;
clear Mahalanobis_dist_vec_test Mahalanobis_dist_vec_train
for q = 1:100
[K_vec, y, sig2] = model2_new_cooling(train,test, 'e_max', e_max, 't_alpha', t_alpha, 'aplpha_0', alpha_0);
outlier_index = [];
for i = 1:length(test)
x_t = test(:,i);
Mahalanobis_dist = diag((x_t - y')'*(x_t - y'))./sig2;
Mahalanobis_dist = min(Mahalanobis_dist);
Mahalanobis_dist_vec_test(i) = Mahalanobis_dist;
if Mahalanobis_dist > Q_t_max
outlier_index = [outlier_index i];
end
end
ten_worst = zeros(1,length(test));
ten_worst(outlier_index) = 1;
Outlier_matrix_p21(q,:) = ten_worst;
end
figure()
for i = 1:6
subplot(3,2,i)
Outliers = Outlier_matrix_p21(1:iter_vec(i),:);
if i > 1
ten_worst_mean = mean(Outliers);
ten_worst_mean(ten_worst_mean > 0) = 1;
else
ten_worst_mean = Outliers;
end
num_outlier = sum(ten_worst_mean>0);
num_seizure = sum(ten_worst_mean(Seizure_time)>0);
b1 = bar(ten_worst_mean, 'b','EdgeColor', 'b', 'EdgeAlpha', 0.05)
hold on
bar(Seizure_time, ten_worst_mean(Seizure_time), 'r','EdgeColor', 'r')
legend('Non-Seizure','Seizure')
alpha(b1, 0.5)
b1.EdgeAlpha = 0.10
hold on
title([title_plot{1,9} ' - ' num2str(num_outlier) ' outeliers, ' num2str(num_seizure) ' seizure points, after ' num2str(iter_vec(i)) ' iterations'])
axis([0 length(ten_worst_mean) 0 1.2])
xlabel('Time (s)')
end
%% TPR, FPR, K_vec for each patient
% Define parameters
e_max = 0.4;
t_alpha = 100;
% alpha_0= [0.3 0.5 0.7 0.9 1.5 1.9];
alpha_0= [30 50 70];
TPR_subject_cum = [];
FPR_subject_cum = [];
K_subject = {};
sig2_mean = {};
sig2_std = {};
Outlier_subject = {};
var_target = 95;
iter = 1;
for d = 1:1%length(Y_train_F2)
% Get data
var_explained = var_explained_F2{1,d};
num_prin = 1;
while sum(var_explained(1:num_prin)) < var_target
num_prin = num_prin + 1;
end
train = Y_train_F2{1,d}(1:2,:);
test = Y_test_F2{1,d}(1:2,:);
% train = Y_train_F2{1,d}(1:num_prin,:);
% test = Y_test_F2{1,d}(1:num_prin,:);
Seizure_time = seizure{1,d};
% Standardise data
train_mean = mean(train,2);
train_std = std(train')';
train = (train-train_mean)./train_std;
test = (test-train_mean)./train_std;
K_iter = [];
TPR_cum = [];
FPR_cum = [];
sig2_mean_iter = [];
sig2_std_iter = [];
for e = 1:length(alpha_0)
d
alpha_0(e)
Q_t_max = 2*log(1./e_max);
Outlier_matrix = [];
for q = 1:iter
q
[K_vec, y, sig2, Mahalanobis_dist_vec, Q_t_vec, y_cell, sig2_cell, prob_k_cell] = model2_new_cooling(train,test, 'e_max', e_max, 't_alpha', t_alpha, 'aplpha_0', alpha_0(e));
outlier_index = [];
for i = 1:length(test)
x_t = test(:,i);
Mahalanobis_dist = diag((x_t - y')'*(x_t - y'))./sig2;
Mahalanobis_dist = min(Mahalanobis_dist);
if Mahalanobis_dist > Q_t_max
outlier_index = [outlier_index i];
end
end
ten_worst = zeros(1,length(test));
ten_worst(outlier_index) = 1;
Outlier_matrix(q,:) = ten_worst;
K_iter(q,e) = K_vec(end);
sig2_mean_iter(q,e) = mean(sig2);
sig2_std_iter(q,e) = std(sig2);
end
Outlier_subject{d,e} = Outlier_matrix;
% Compute for TPR and FPR for "total outlier"
ten_worst = zeros(1,length(test));
if q == 1
ten_worst(outlier_index) = 1;
else
ten_worst(mean(Outlier_matrix) > 0) = 1;
end
true_positive = sum(ten_worst(Seizure_time));
False_postive = sum(ten_worst)-true_positive;
num_seizure = length(Seizure_time);
Condition_negative = length(test)-num_seizure;
TPR = true_positive/num_seizure;
FPR = False_postive/Condition_negative;
TPR_cum(1,e) = TPR;
FPR_cum(1,e) = FPR;
y_change{1,e} = y_cell;
sig2_change{1,e} = sig2_cell;
prob_k_change{1,e} = prob_k_cell;
end
% Outlier_subject{1,d} = Outlier_matrix;
TPR_subject_cum(d,:) = TPR_cum;
FPR_subject_cum(d,:) = FPR_cum;
sig2_mean{1,d} = sig2_mean_iter;
sig2_std{1,d} = sig2_std_iter;
K_subject{1,d} = K_iter;
end
%% Bar plot wtih TPR / FPR for different e_max
% subjects = [02 05 07 10 13 14 16 20 21 22];
figure()
subplot(2,1,1)
% TPR_bar = [TPR_subject_cum{1,1}(25,:);TPR_subject_cum{1,2}(25,:)];
bar(TPR_subject_cum)
legend('alpha_0: 0.1', 'alpha_0: 0.3','alpha_0: 0.5','alpha_0: 0.7', 'alpha_0: 0.9')
ylabel('Sensitivity')
% xlabel('Subject')
xticks(1:10)
% xticklabels(subjects)
axis([0 11 0 1])
subplot(2,1,2)
% FPR_bar = [FPR_subject_cum{1,1}(25,:);FPR_subject_cum{1,2}(25,:)];
bar(1 -FPR_subject_cum)
legend('alpha_0: 0.1', 'alpha_0: 0.3','alpha_0: 0.5','alpha_0: 0.7', 'alpha_0: 0.9')
ylabel('Specificity')
% xlabel('Subject')
xticks(1:10)
% xticklabels(subjects)
axis([0 11 0 1])
figure()
bar((TPR_subject_cum + (1 -FPR_subject_cum))/2)
K_mean = [];
for d = 1:10
K_mean = [K_mean ;mean(K_subject{1,d})];
end
for i = 1:10
for e = 1:length(alpha_0)
num_outlier(i,e) = sum(mean(Outlier_subject_emax{i,e})>0)/length(Data{1,i});
end
end
figure
subplot(2,1,1)
bar(K_mean)
legend('alpha_0: 0.1', 'alpha_0: 0.3','alpha_0: 0.5','alpha_0: 0.7', 'alpha_0: 0.9')
ylabel('Number of clusters, k')
xlabel('Subject')
xticks(1:10)
% xticklabels(subjects)
subplot(2,1,2)
bar(num_outlier)
ylabel('Number of outliers/Number of training points')
xlabel('Subject')
legend('alpha_0: 0.1', 'alpha_0: 0.3','alpha_0: 0.5','alpha_0: 0.7', 'alpha_0: 0.9')
xticks(1:10)
% xticklabels(subjects)
%%
clear TPR_cum FPR_cum TPR_matrix FPR_matrix
for i = 1:10
OutlierMatrix = Outlier_subject{i,2};
Seizure_time = seizure{1,i};
for j = 1:25
if j == 1
ten_worst = OutlierMatrix(1,:);
else
ten_worst(mean(OutlierMatrix) > 0) = 1;
end
true_positive = sum(ten_worst(Seizure_time));
False_postive = sum(ten_worst)-true_positive;
num_seizure = length(Seizure_time);
Condition_negative = length(test)-num_seizure;
TPR = true_positive/num_seizure;
FPR = False_postive/Condition_negative;
TPR_cum(1,j) = TPR;
FPR_cum(1,j) = FPR;
end
TPR_matrix(i,:) = TPR_cum;
FPR_matrix(i,:) = FPR_cum;
end
%%
Z = 1.960;
n = size(TPR_matrix,1);
mean_TPR = mean(TPR_matrix);
std_TPR = std(TPR_matrix)
conf_int = Z * std_TPR/sqrt(n);
lower_TPR = mean_TPR - conf_int;
upper_TPR = mean_TPR + conf_int;
mean_FPR = mean(FPR_matrix);
std_FPR = std(FPR_matrix)
conf_int = Z * std_FPR/sqrt(n);
lower_FPR = mean_FPR - conf_int;
upper_FPR = mean_FPR + conf_int;
figure()
subplot(2,1,1)
plot(mean_TPR)
hold on
plot(lower_TPR, '--')
hold on
plot(upper_TPR, '--')
subplot(2,1,2)
plot(mean_FPR)
hold on
plot(lower_FPR, '--')
hold on
plot(upper_FPR, '--')
%%
figure()
iter_vec = [1 10 15 25];
for i = 1:4
Seizure_time = seizure{1,3};
Outlier_matrix = Outlier_subject{1,1};
subplot(2,2,i)
Outliers = Outlier_matrix(1:iter_vec(i),:);
if i > 1
ten_worst_mean = mean(Outliers);
ten_worst_mean(ten_worst_mean > 0) = 1;
else
ten_worst_mean = Outliers;
end
num_outlier = sum(ten_worst_mean>0);
num_seizure = sum(ten_worst_mean(Seizure_time)>0);
b1 = bar(ten_worst_mean, 'b','EdgeColor', 'b', 'EdgeAlpha', 0.05)
hold on
bar(Seizure_time, ten_worst_mean(Seizure_time), 'r','EdgeColor', 'r')
legend('Non-Seizure','Seizure')
alpha(b1, 0.5)
b1.EdgeAlpha = 0.10
hold on
title([title_plot{1,3} ' - ' num2str(num_outlier) ' outeliers, ' num2str(num_seizure) ' seizure points, after ' num2str(iter_vec(i)) ' iterations'])
axis([0 length(ten_worst_mean) 0 1.2])
xlabel('Time (s)')
end
%%
Outlier_matrix_ = Outlier_subject{1,1};
Outlier_matrix_p21_5PC = Outlier_matrix_p21(1:25,:);
Test{1,1} = Outlier_matrix_;
Test{1,2} = Outlier_matrix_p21_5PC;
sum(Outlier_matrix_')
sum(Outlier_matrix_p21_5PC')
clear TPR_matrix FPR_matrix TPR_cum FPR_cum
OutlierMatrix = Outlier_matrix_p21;
Seizure_time = seizure{1,2};
for j = 1:100
if j == 1
ten_worst = OutlierMatrix(1,:);
else
ten_worst(mean(OutlierMatrix(1:j,:)) > 0) = 1;
end
true_positive = sum(ten_worst(Seizure_time));
False_postive = sum(ten_worst)-true_positive;
num_seizure = length(Seizure_time);
Condition_negative = length(test)-num_seizure;
TPR = true_positive/num_seizure;
FPR = False_postive/Condition_negative;
TPR_cum(1,j) = TPR;
FPR_cum(1,j) = FPR;
end
TPR_matrix = TPR_cum;
FPR_matrix= FPR_cum;
figure()
subplot(2,1,1)
plot(TPR_matrix)
title('TPR')
legend('PC: 6', 'PC:5')
axis([0 100 0.5 1])
subplot(2,1,2)
plot(FPR_matrix)
title('FPR')
legend('PC: 6', 'PC:5')
axis([0 100 0 0.2])
%%
figure()
for i = 1:10
var_explained = var_explained_F2{1,i}
plot(cumsum(var_explained))
hold on
end
axis([0 126 0 100])
legend('2','5','7','10','13','14','16','20','21','22')
%% LOGPLOT for optimal value
iter = 5;
for d = 1:length(Y_train_F2)
h = figure()
% Get data
var_explained = var_explained_F2{1,d};
num_prin = 1;
while sum(var_explained(1:num_prin)) < var_target
num_prin = num_prin + 1;
end
train = Y_train_F2{1,d}(1:num_prin,:);
test = Y_test_clean_F2{1,d}(1:num_prin,:);
Seizure_time = seizure{1,d};
start_seiz = floor(Seizure_time(1)/8);
end_seiz = ceil(Seizure_time(end)/8);
Seizure_time = start_seiz:end_seiz;
% Standardise data
train_mean = mean(train,2);
train_std = std(train')';
train = (train-train_mean)./train_std;
test = (test-train_mean)./train_std;
e_max = 0.2;
t_alpha = 1;
alpha_0 = 0.7;
Q_t_max = 2*log(1./e_max);
Outlier_matrix = [];
for q = 1:iter
[K_vec, y, sig2] = model2_new_cooling(train,test, 'e_max', e_max, 't_alpha', t_alpha, 'aplpha_0', alpha_0);
outlier_index = [];
for i = 1:length(test)
x_t = test(:,i);
Mahalanobis_dist = diag((x_t - y')'*(x_t - y'))./sig2;
Mahalanobis_dist = min(Mahalanobis_dist);
if Mahalanobis_dist > Q_t_max
outlier_index = [outlier_index i];
end
end
ten_worst = zeros(1,length(test));
ten_worst(outlier_index) = 1;
Outlier_matrix(q,:) = ten_worst;
end
ten_worst_mean = mean(Outlier_matrix);
ten_worst_mean(ten_worst_mean > 0) = 1;
num_outlier = sum(ten_worst_mean>0);
num_seizure = sum(ten_worst_mean(Seizure_time)>0);
b1 = bar(ten_worst_mean, 'b','EdgeColor', 'b', 'EdgeAlpha', 0.05)
hold on
bar(Seizure_time, ten_worst_mean(Seizure_time), 'r','EdgeColor', 'r')
legend('Non-Seizure','Seizure')
alpha(b1, 0.5)
b1.EdgeAlpha = 0.10
title([title_plot{1,d} ' - ' num2str(num_outlier) ' outeliers, ' num2str(num_seizure) ' seizure points'])
axis([0 length(ten_worst_mean) 0 1.2])
xlabel('Time (s)')
% saveas(h, sprintf('LogPlot_model2_subject_%s', plot_name{1,d}),'epsc')
end
|
function [x, P, K] = kfilt(x, P, b, A, F, Sigma_e, Sigma_eps)
% KALMAN FILTER
% [x, P, K] = kfilt(x, P, b, A, F, Sigma_e, Sigma_eps)
% performs a linear kalman filter
%------------
% returns:
% x : the state vector
% P : x's covariance
%------------
% arguments:
% x : the state vector
% P : x's covariance
% b : the measurement vector
% A : the observation matrix
% F : the state transformation matrix
% Sigma_e : the measurement error covariance
% Sigma_eps : the process error covariance
% predict x_k|k-1
x = F * x;
% predict P_k|k-1
P = F * P * F' + Sigma_eps;
% compute kalman gain
K = P * A' * inv(Sigma_e + A * P * A');
% correct x_k|k
x = x + K*(b - A * x);
% correct P_k|k
P = P - K * A * P;
|
%数据补全
%输入A是需要补全的数据列矢量A,输入k是补全的模式
%输出A1是补全后的数据列矢量
function [A1]=completion(A,k);
A2=A;
A2(isnan(A2(:,1)),:)=[];%补充缺失值
if k==1%平均值补全
amean=mean(A2);
A(isnan(A(:,1)),:)=amean;
elseif k==2 %众数补全
amode=mode(A2);
A(isnan(A(:,1)),:)=amode;
elseif k==3%0补全
A(isnan(A(:,1)),:)=0;
end
A1=A;
|
fmask = fileread('/media/test5/ComponentsList.txt');
Mlist = strsplit(fmask);
fdata = fileread('/media/test5/MasksFreeWalk.txt');
Dlist = strsplit(fdata);
for idx=1:length(Mlist)
file=Mlist{idx}
file2=strcat(file(1:size(file,2)-4),'thresh3std.nii');
M=MRIread(file2);
Mask=M.vol;
Dlist{idx}
D=MRIread(Dlist{idx});
Data=D.vol;
S=size(Data);
D2=Data./(max(max(max(max(Data)))));
SM2=size(Mask);
for i=1:S(4)
for j=1:SM2(4)
Av(i,j)=sum(sum(sum(Mask(:,:,:,j).*squeeze(D2(:,:,:,i)))))/sum(sum(sum(Mask(:,:,:,j))));
end
end
save(strcat(file(1:size(file,2)-4),'ICsmallRegions.mat'),'Av');
clear Av
clear Mask
clear Data
clear M2
close all
end |
close all;
input = xlsread('Input.xlsx','sheet3','B2:N32');
for i=1:13
year=1999+i;
figure(i)
h=plot(input(1:31,i),'*-');
set(h,'LineWidth',1.5)
hold off
xlabel('Time');
ylabel('TAIEX');
p=sprintf('Dec in %d',year);
legend(p)
end
% figure(1)
% plot(input(1:31,1),'*-');
% hold off
% figure(2)
% plot(input(1:31,2),'*-'); |
function fig = viewCtree(varargin)
% INPUTS
% OPTIONAL
% FileName:
% 'ModelTypes':
% 'ClassLabels':
% 'Fields':
% 'SaveDir':
% 'Args':
% OUTPUTS
p=inputParser;
addOptional(p,'ModelName','max_dose.mat' ,@istext);
addParameter(p,'ModelTypes',"treebag", @istext );
addParameter(p,'ClassLabels',"'Ligand" );
addParameter(p,'TestTypes',{'oob'} );
addParameter(p,'Args',{}, @iscell)
addParameter(p, 'SaveDir','',@ischar);
parse(p, varargin{:});
params = getNameValuePairs(p.Results, {'FileName', 'ModelTypes', 'ClassLabels', 'Args'});
codonVer = p.Results.FeatureCategory;
paths = loadpaths;
dirTree= get_dtree(paths.collaborations);
%% Load reference set for scaling
refX = loadTrainingSet('ModelName',p.Results.RefSet, 'DataVersion' , p.Results.RefDataVersion,...
'FeatureCategory',codonVer) ;
counts = table;
[featNames,codonTbl] = getCodonNames(codonVer);
toInvert = ["time2HalfMaxIntegral", "pk1_time"]; %invert the values of these features to keep semantics
invIx = any(featNames ==toInvert,2);
ex = ones(size(featNames));
ex(invIx) = ex(invIx)*-1;
dataMat =refX{:,featNames}.^(ex');
invalid = ~isfinite(dataMat);
dataMat(invalid) =0;
refX{:,featNames} = dataMat;
if p.Results.StripOutliers
[refX, counts] = rmOutlierRows(refX, ["Ligand","Dose"],featNames,...
'Method', p.Results.OutlierMethod, 'ThresholdFactor', p.Results.ThresholdFactor);
% [refX, counts] = rmOutlierRows(refX, ["Ligand","Dose"],featNames, 'Method', 'median');
end
mdlPath =dirTree.Brooks.Taylor2018.classification_models.(p.Results.DataVersion).(p.Results.FeatureCategory).name;
[~,lblS]= getLabelTbl(p.Results.Set);
classLabel = lblS.(p.Results.Set).ClassLabels(1);
mdl = loadClassificationMdl(mdlPath, 'FileName',p.Results.Set+".mat", 'Fields',["features","test"]);
if isempty(p.Results.SaveDir)
paths = loadpaths;
dTree= get_dtree(paths.collaborations);
SaveDir= dTree.Brooks.Taylor2018.classification_models.codons.name;
end
mdl = reloadTaylor2018Mdl(SaveDir, 'Fields', {'model','test'}, params{:});
data= mdl.(p.Results.ModelTypes{1}).(p.Results.ClassLabels{1});
if contains(SaveDir, 'codons')
[~, codonTbl]=getCodonNames;
codons = join(codonTbl, array2table(data.mdl.PredictorNames', 'VariableNames',{'Name'}));
end
fig = seeTree(data, 'VariableNames', codons.Category);
end |
function TwinRasters(stimA,stimB,rastA,rastB,toffset)
blank = zeros(2,2);
blank = {blank,blank};
stim = [stimA,blank,stimB];
blank = cell(1,2);
spike = [rastA,blank,rastB];
PlotValve(stim,spike,length(spike),toffset);
line(get(gca,'XLim'),[1 1]*length(rastA)+1.5,'Color','k');
function PlotValve(stim,spike,stimy,toffset)
nrpts = length(stim);
co = get(gca,'ColorOrder');
hold on
for i = 1:nrpts
tstart = stim{i}(2,1);
hline = stairs(stim{i}(2,:)-tstart+toffset,stimy+1+0.9*ceil(stim{i}(1,:)/12)); % Stimulus
set(hline,'Tag','Stim','Color','r');
colindx = mod(i-1,size(co,1))+1;
%if (length(stim{i}(2,:) < 3))
% ton = 0;
%else
% ton = stim{i}(2,3)-stim{i}(2,2);
%end
% These next line is specific for one expt! Change this!
%colindx = round(log2(ton))+3;
colindx = 1;
%set(hline,'Color',co(colindx,:));
nspikes = length(spike{i});
y1 = (nrpts-i+1)*ones(1,nspikes);
y = [y1+0.2;y1-0.2];
x = [spike{i}-tstart;spike{i}-tstart];
plot(x+toffset,y,'Color',co(colindx,:));
end
set(gca,'XLim',[toffset,stim{1}(2,end)-stim{1}(2,1)+toffset],'YLim',[0 stimy+2]);
set(gca,'YTick',[]);
|
function [basisDecRule,nextBasisId] = selectNextBasis( decOpt_EVsys,decOpt_prox_EVprox,decOpt_prox )
[decOpt_EVsys_sort, decOpt_EVsys_sortId] = sort( decOpt_EVsys );
decOpt_EVsys_prox_sort = decOpt_prox_EVprox( decOpt_EVsys_sortId );
div = -( decOpt_EVsys_prox_sort(2:end) - decOpt_EVsys_prox_sort(1:end-1) + eps )./( decOpt_EVsys_sort(2:end) - decOpt_EVsys_sort(1:end-1) +eps );
[~,nextBasisId_sort] = max( div );
nextBasisId = decOpt_EVsys_sortId( nextBasisId_sort+1 );
basisDecRule = decOpt_prox( nextBasisId,: );
|
function conf = voc_config_person_grammar()
% Set up configuration variables
% AUTORIGHTS
% -------------------------------------------------------
% Copyright (C) 2011-2012 Ross Girshick
%
% This file is part of the voc-releaseX code
% (http://people.cs.uchicago.edu/~rbg/latent/)
% and is available under the terms of an MIT-like license
% provided in COPYING. Please retain this notice and
% COPYING if you use this file (or a portion of it) in
% your project.
% -------------------------------------------------------
conf.pascal.year = '2007';
conf.project = 'voc-dpm/person-grammar';
conf.training.train_set_fg = 'trainval';
conf.training.train_set_bg = 'train';
conf.training.C = 0.006;
conf.training.wlssvm_M = 1;
% PASCAL > 2007 requires a larger cache (7GB cache size works well)
conf.training.cache_byte_limit = 7*2^30;
conf.training.lbfgs.options.optTol = 0.0001;
conf.training.interval_fg = 4;
conf.eval.interval = 8;
conf.eval.test_set = 'test';
conf.eval.max_thresh = -1.4;
conf.features.extra_octave = true;
|
% convert a polynomial from representation as a sum of symbolic terms into
% a matrix representing coefficients and a matrix representing monomials
%
% coeffMat is a single row vector
% monoMat has one row for every term. Rows of monoMat are multi-indices
function [coeffMat , monoMat] = polyStrToCoeffs(poly, allVars)
[c, m] = coeffs(poly);
numTerms = size(c,2);
numVars = size(allVars,2);
coeffMat = c;
monoMat = zeros( numTerms, numVars );
for i= 1: numTerms
monoMat(i, :) = multiindex(m(1,i) , allVars);
end
end
|
clc
clear
load('../Normalize Threshold/result_5tx_SP.mat');
addpath('../../');
import param_vals.*;
monte_carlo = param_vals.monte_carlo;
symbol_no = param_vals.symbol_no;
mod_type = param_vals.mod_type;
snr_value = param_vals.snr;
training_data_no = param_vals.training_data_no;
numfiles = param_vals.numfiles;
pfa = param_vals.pfa;
n_fft = param_vals.n_fft;
snr = param_vals.snr_mtx;
ms = param_vals.multiscale;
% n_fft = [1024 2048];
% snr = 0:10:40;
% ms = 1:3;
user_num = 5;
for fft_no = 1 : length(n_fft)
for ms_no = 1 : length(ms)
for snr_no = 1:length(snr)
data = zeros(param_vals.numfiles, 1);
for i = 1:param_vals.numfiles
data(i) = result(i).multi_scale(ms_no).fft(fft_no).snr(snr_no).time;
% data = [data result(i).multi_scale(ms_no).fft(fft_no).snr(snr_no).time];
end
data_mean(snr_no) = mean(data);
end
data_all_mean_sp(fft_no,ms_no) = mean(data_mean);
end
end
save('data_sp.mat','data_all_mean_sp');
|
dudt = @(t, u) f(t,u);
[t, w] = rk4(dudt, 0, 1/2, [1/3,1/3], 20);
tt = linspace(0, 1/2);
u1 = @(t) 2/3 * t + 2/3 * exp(-t) - 1/3 * exp(-100 * t);
u2 = @(t) -1/3 * t - 1/3 * exp(-t) + 2/3 * exp(-100 * t);
y1 = u1(tt);
y2 = u2(tt);
hold on
plot(tt, y1)
plot(t, w(:,1))
hold off
function du = f(t,u)
u1 = u(1);
u2 = u(2);
du1_dt = 32 * u1 + 66 * u2 + 2/3 * t + 2/3;
du2_dt = -66 * u1 - 133 * u2 - 1/3 * t - 1/3;
du = [du1_dt, du2_dt];
end |
function MipButtonMotion( hObject,callbackdata )
global MipAxesHandle MipDragRectangleHandle MipDragLineHandle MipTextHandle
ud = get(MipAxesHandle,'UserData');
if (ud.IsDown)
oldPnt_xy = ud.PointDown_xy;
mousePnt = get(MipAxesHandle,'CurrentPoint');
newPnt_xy = mousePnt(1,:);
dists_xy = newPnt_xy-oldPnt_xy;
if (any(abs(dists_xy)>1023))
% making too big of an ROI to send to D3d viewer
if (dists_xy(1)>1023)
oldPnt_xy(1) = min(ud.ImData.Dimensions(1), oldPnt_xy(1) + (dists_xy(1) - 1023));
elseif (dists_xy(1)<-1023)
oldPnt_xy(1) = max(1, oldPnt_xy(1) + (dists_xy(1) + 1023));
end
if (dists_xy(2)>1023)
oldPnt_xy(2) = min(ud.ImData.Dimensions(2), oldPnt_xy(2) + (dists_xy(2) - 1023));
elseif (dists_xy(2)<-1023)
oldPnt_xy(2) = max(1, oldPnt_xy(2) + (dists_xy(2) + 1023));
end
rad = 1023;
else
rad = max(abs(dists_xy));
end
startPnt_xy = oldPnt_xy - rad;
set(MipDragRectangleHandle,'Visible','on',...
'Position',[startPnt_xy(1:2),2*rad,2*rad]);
set(MipTextHandle,'Visible','on',...
'Position',oldPnt_xy(1:2),'String',{'Edge Length:',num2str(floor(rad)*2 +1)});
set(MipDragLineHandle,'Visible','on','XData',[oldPnt_xy(1),newPnt_xy(1)],'YData',[oldPnt_xy(2),newPnt_xy(2)]);
end
end
|
function y = delta(t)
y = t == 0; |
% imngderx, imgdery = Matrices with derivative values in the x and y directions
% I_P = Intensity Polarity -> +1 looks for white circles on black backgrounds
function centers = hough_disk(fname, imgderx, imgdery, radius, I_P, num_centers, parzen_std)
%Dimensions of Image
dim = size(imgderx,1);
%Magnitude of the gradient = L2-norm at each pixel
grad_mag = sqrt(imgderx.^2+imgdery.^2); %or norm[x y]
thresh = 0.05; %Used as mu for sigmoid function, with sd = 1
vote_strength = normcdf(grad_mag,thresh,1);
% Unit vectors for the gradient direction at each pixel
derx_uv = I_P*imgderx./grad_mag;
dery_uv = I_P*imgdery./grad_mag;
smoothed_accum = fill_accumulator(derx_uv, dery_uv,vote_strength, dim, radius, parzen_std);
fig=figure(1);
fig.PaperUnits = 'inches';
fig.PaperPosition = [0 0 11 10];
x = 1:dim; y = dim:-1:1;
pcolor(x,y,smoothed_accum);
c = colorbar;
c.Label.String = 'Smoothed Votes';
c.Label.FontSize = 16;
xlabel('x');
ylabel('y');set(get(gca,'YLabel'),'Rotation',0);
title('\fontsize{18}Hough Map');
fname = erase(fname,".png"); fname = erase(fname,".jpg");
print("figures\"+fname+"_HoughMap.png",'-dpng');
centers = getHighestVotes(smoothed_accum,num_centers)
end
%% Helper functions
% Gets votes from each pixel and fills them in the accumulator array
function smoothed_accum = fill_accumulator(derx_uv, dery_uv, vote_strength, dim, R, parzen_std)
% Note that matrix columns = x coordinates and rows = y coordinates
% So you would need to access the matrix as M(y,x) to get (x,y) pixel
accum = zeros(dim,dim);
% Check-function to get rid of indices outside of range
validate =@(xy) (xy>0 & xy <= dim);
% Maps coordinate points to valid matrix indices
discretize =@(x,y) round(x)+1;
for x=0:dim-1
for y=0:dim-1
% To get mathematically accurate vector directions
% with (x,y)=(0,0) pointing at bottom left pixel of image
i = dim-y; j = x+1;
a = discretize(x + R * derx_uv(i,j));
b = discretize(y + R * dery_uv(i,j));
valid = validate([a,b]);
if (valid)
accum(dim-b+1,a) = accum(dim-b+1,a) + vote_strength(j,i);
end
end
end
smoothed_accum = imgaussfilt(accum,parzen_std);
end
% Gets the top num_votes from the accumulator array
% Returns the list of x,y cenetr coordinates
function centers = getHighestVotes(accum,num_votes)
dim = size(accum,1);
pixel_radius = 0.07*dim;
[xx,yy] = meshgrid(1:dim,dim:-1:1);
centers = zeros(num_votes,2);
for i=1:num_votes
% Finding postion of current max
[column_max row_nums] = max(accum);
[max_value column_idx] = max(column_max);
row_idx = row_nums(column_idx);
% Recall that columns denote x values and rows y values
% Index postions start from 1 and coordinates start from 0
center_x = column_idx-1;
center_y = dim - row_idx;
% Removing votes from a scaled pixel radius by using a logical matrix
removed_pixels = (xx-center_x).^2 + (yy-center_y).^2 < pixel_radius^2;
accum(removed_pixels) = 0;
centers(i,:) = [center_x, center_y];
end
end
|
function C = calculate_C(X,h)
N = size(X,1);
C = false(N);
for i = 1:N
C(i,:) = sqrt(sum(bsxfun(@minus,X,X(i,:)).^2,2))'<h;
C(i,i) = 0;
end |
function process_parameter_txt(paramfile,instrumentfile,mapfile )
import java.util.Hashtable;
instrument=Hashtable();
fd=fopen(instrumentfile,'r');
tmp=textscan(fd,'%s %s');
fclose(fd);
size=length(tmp{1});
for i=1:size
instrument.put(upper(tmp{1}{i}),upper(tmp{2}{i}));
end
map=Hashtable();
fd=fopen(mapfile,'r');
tmp=textscan(fd,'%s %s');
fclose(fd);
size=length(tmp{1});
for i=1:size
map.put(upper(tmp{1}{i}),upper(tmp{2}{i}));
end
fd=fopen(paramfile,'r');
headline=fgets(fd);
remain=fscanf(fd,'%c');
fclose(fd);
expr='@([A-Za-z]+)(\d*){(.*?)}';
[match,tokens]=regexp(headline,expr,'match','tokens');
l=length(match);%match count;
for i=1:l
type=upper(tokens{i}{1});
switch type
case 'SWEEPGATE'
label=upper(tokens{i}{3});
name=map.get(label);
if isempty(name)
name=label;
end
headline=regexprep(headline,match{i},name,'ignorecase');
remain=regexprep(remain,match{i},name,'ignorecase');
case 'CURRENT'
label=upper(tokens{i}{3});
num=tokens{i}{2};
name=map.get(label);
if isempty(name)
name=label;
end
headline=regexprep(headline,match{i},name,'preservecase');
remain=regexprep(remain,match{i},name,'preservecase');
bias=map.get(['BIAS',num]);
if strcmpi(bias,'NON')||isempty(bias)
bias='';
remain=regexprep(remain,['@BIAS',num],bias,'ignorecase');
else
remain=regexprep(remain,['@BIAS',num],sprintf('bias:%s',bias),'ignorecase');
end
modulation=map.get(['MODULATION',num]);
if strcmpi(modulation,'NON')||isempty(modulation)
modulation='';
remain=regexprep(remain,['@MODULATION',num],'','ignorecase');
else
remain=regexprep(remain,['@MODULATION',num],sprintf('modulation@%s',modulation),'ignorecase');
end
source=map.get(['SOURCE',num]);
if ~isempty(source)&&~strcmpi(source,'NON')
tok=regexp(source,'([a-zA-Z]+)(\d*)','tokens');
instrname=upper(tok{1}{1});
instrnum=upper(tok{1}{2});
sourcetype=0;%1 for lockin
isfreqsexist=1;
switch instrname
case 'LOCKIN'
sourcetype=1;
sinfo='';
[ratio,status1]=str2num(char(map.get(['RATIO',num])));
[amps,status2]=str2num(char(instrument.get(['AMP',instrnum])));
if status1&&status2
sinfo=[sinfo,sprintf('amps:%g ',amps*ratio)];
end
freqs=instrument.get(['FREQ',instrnum]);
if ~isempty(freqs)
sinfo=[sinfo,sprintf('freqs:%s',freqs)];
else
isfreqsexist=0;
end
remain=regexprep(remain,['@SOURCE',num],sinfo,'ignorecase');
otherwise
sourcetype=0;
remain=regexprep(remain,['@SOURCE',num],'','ignorecase');
end
else
remain=regexprep(remain,['@SOURCE',num],'','ignorecase');
end
measure=map.get(['MEASURE',num]);
if ~isempty(measure)&&~strcmpi(measure,'NON')
tok=regexp(measure,'([a-zA-Z]+)(\d*)','tokens');
instrname=upper(tok{1}{1});
instrnum=upper(tok{1}{2});
switch instrname
case 'LOCKIN'
minfo='';
ampm=instrument.get(['AMP',instrnum]);
if ~isempty(ampm)
minfo=[minfo,sprintf('ampm:%s ',ampm)];
end
freqm=instrument.get(['FREQ',instrnum]);
if ~isempty(freqm)&&isfreqsexist
minfo=[minfo,sprintf('freqm:%s',freqm)];
end
remain=regexprep(remain,['@MEASURE',num],minfo,'ignorecase');
otherwise
remain=regexprep(remain,['@MEASURE',num],'','ignorecase');
end
else
remain=regexprep(remain,['@MEASURE',num],'','ignorecase');
end
end
end
expr='(\w+)\((.*?)\)';
[match,tokens]=regexp(remain,expr,'match','tokens');
l=length(match);%match count;
for i=1:l
label=upper(tokens{i}{1});
name=map.get(label);
if strcmpi(name,'non')
remain=regexprep(remain,sprintf('%s\\(%s\\)',tokens{i}{1},tokens{i}{2}),'','ignorecase');
else
if isempty(name)
name=label;
end
remain=regexprep(remain,label,name,'ignorecase');
end
end
[path,~,~]=fileparts(paramfile);
filename=fullfile(path,'param.txt');
fd=fopen(filename,'w');
fprintf(fd,'%s',headline);
fprintf(fd,'%s',remain);
fclose(fd);
end
|
%find average of the input signal
function average = findAverage(input)
dataSize = size(input,1);
plus= [];
for i=1:dataSize
if(i==1)
plus = input(i,:);
else
plus = [plus + input(i,:)];
end
end
average = plus/dataSize; |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function to create a pretty simple plot %
% That used frequently in this work %
% %
% Author: Bezborodov Grigoriy %
% Github: somenewacc %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [] = CreateSimplePlot( is_subplot, a, b, c, y, plot_title )
if is_subplot == true
subplot(a, b, c)
end
x = 0:1:length(y) - 1;
plot( x, y )
% Get rid of interpretes since we don't have any TeX in this case
title( plot_title, 'Interpreter', 'none' )
end |
function even_vector = filter_even_positions(arr)
even_vector = [];
for i = 1:length(arr)
if ~rem(i, 2)
even_vector = [even_vector arr(i)];
end
end
end |
clc
clear
close all
% Radial Basis Approximation
% This example uses the NEWRB function to create a radial basis network
% that approximates a function defined by a set of data points.
% Define 21 inputs P and associated targets T.
X = -1:.1:1;
% T = [-.9602 -.5770 -.0729 .3771 .6405 .6600 .4609 ...
% .1336 -.2013 -.4344 -.5000 -.3930 -.1647 .0988 ...
% .3072 .3960 .3449 .1816 -.0312 -.2189 -.3201];
T = X.*sin(cos(3*X));
figure(1);
subplot(2,2,1);
plot(X,T,'+');
title('Training Vectors');
xlabel('Input Vector X');
ylabel('Target Vector T');
% We would like to find a function which fits the 21 data points. One way
% to do this is with a radial basis network. A radial basis network is a
% network with two layers. A hidden layer of radial basis neurons and an
% output layer of linear neurons. Here is the radial basis transfer
% function used by the hidden layer.
x = -3:.1:3;
a = radbas(x);
subplot(2,2,2);
plot(x,a)
title('Radial Basis Transfer Function');
xlabel('Input x');
ylabel('Output a');
% The weights and biases of each neuron in the hidden layer define the
% position and width of a radial basis function. Each linear output neuron
% forms a weighted sum of these radial basis functions. With the correct
% weight and bias values for each layer, and enough hidden neurons, a
% radial basis network can fit any function with any desired accuracy. This
% is an example of three radial basis functions (in blue) are scaled and
% summed to produce a function (in magenta).
a1 = radbas(x);
a2 = radbas(x-1.5);
a3 = 0.5 * radbas(x+2);
a4 = a1 + a2 + a3;
subplot(2,2,3);
plot(x,a1,'b-',x,a2,'g-',x,a3,'r-',x,a4,'m-')
title('Weighted Sum of Radial Basis Transfer Functions');
xlabel('Input p');
ylabel('Output a');
legend('RBF #1','RBF #2','RBF #3','scaled and summed of 3 RBFs');
% The function NEWRB quickly creates a radial basis network which
% approximates the function defined by P and T. In addition to the training
% set and targets, NEWRB takes two arguments, the sum-squared error goal
% and the spread constant.
goal = 0.001; % sum-squared error goal
spread = 1; % spread constant
MN = 8; % number of hidden neurons
DF = 1; % display frequency
net = newrb(X,T,goal,spread,MN,DF);
%net = newrbe(X,T,spread);
% To see how the network performs, replot the training set. Then simulate
% the network response for inputs over the same range. Finally, plot the
% results on the same graph.
X_test = -1:.01:1;
Y_hat = net(X_test);
figure(1);
subplot(2,2,4);
plot(X,T,'+');
xlabel('Input');
hold on;
plot(X_test,Y_hat);
hold off;
legend({'Target','Output'});
title('RBF Network');
view(net)
netPerformance(T,net(X));
|
%SVD for rectangular and square image
image = imread('24_square.jpg');
image = rgb2gray(image);
A = im2double(image);
%A = im2double(image(:,:,3));
[U,D] = eig(A*A');
Vin = inv(sqrt(D))*inv(U)*A;
[M,N] = size(A);
D1 =zeros(M,N);
Z = zeros(M,N);
eigen_value = zeros(1,M);
error = zeros(1,M);
k=1;
%remove this for random N
for i =[5:50:M]
%i=75; %remove this line for iterative version, use it only for specific
% number of eigen values
D1 = D;
for j =[1:1:M-i]
D1(j,j) = 0;
end
%{
remove from this for top N
for i=[1:1:2]
Rnd = randi([0 1],1,M);
D1 = D;
for j =[1:1:M]
D1(j,j) = D1(j,j)* Rnd(1,j);
end
%remove till here for manual
%}
newimg = U*sqrt(D1)*Vin;
subplot(1,4,k);
imshow(cat(3,Z,Z,newimg));
title(['Reconstructed with ' num2str(i) ' singular values']);
%use this for manual
%title('Random singular values reconstruction');
subplot(1,4,k+1);
imshow(A - newimg);
title(['Error image with ' num2str(i) ' singular values']);
%title('Error ');
B = (A - newimg).^2;
S = sum(sum(B));
eigen_value(i) = i;
error(i) = S;
k=k+2;
end
i = (error == 0);
error(i) = [];
eigen_value(i) = [];
%plot(eigen_value,error);
|
function pj = pj_calc(fcarrier,freq_spur,power_spur,integ_start,integ_stop)
ind=find(freq_spur>=integ_start);
ind_integ_start=ind(1);
ind=find(freq_spur<=integ_stop);
ind_integ_stop=ind(end);
pnoise_spur_integ=power_spur(ind_integ_start:ind_integ_stop);
power_spur_rad2=10.^(pnoise_spur_integ/10);
pj=sqrt(2*sum(power_spur_rad2))/(2*pi*fcarrier);
% semilogx(freq_spur,power_spur,'-');
% scatter(freq_spur,power_spur);
|
%计算基于最大李雅谱诺夫方法的预测值
function [x_1,x_2]=pre_by_lya(m,lmd,whlsj,whlsl,idx,min_d)
% x_1 - 第一预测值, x_2 - 第二预测值,
% m -嵌入维数,lmd - 最大李雅谱诺夫值,whlsj - 数据数组,whlsl - 数据个数,
%idx - 中心点的最近距离点位置, min_d - 中心点与最近距离点的距离
%相空间重构
LAST_POINT = whlsl-m+1;
for j=1:LAST_POINT
for k=1:m
Y(k,j)=whlsj(k+j-1);
end
end
a_1=0.;
for k=1:(m-1)
a_1=a_1+(Y(k,idx+1)-Y(k+1,LAST_POINT))*(Y(k,idx+1)-Y(k+1,LAST_POINT));
% 此处Y(k+1,LAST_POINT)实际上就是Y(k,LAST_POINT+1)
end
deta=sqrt(min_d^2*2^(lmd*2)-a_1);
if (isreal(deta)==0) || (deta>Y(m,idx+1)*0.001);
deta=Y(m,idx+1)*0.001;
end
x_1=Y(m,idx+1)+deta;
x_2=Y(m,idx+1)-deta;
|
% Reproduces the analysis of Heinzle et al. (2016) deriving the appropriate
% prior density over epsilon given the review of T2* values from Donahue et
% al. 2011
for B0 = [1.5, 3.0, 7.0]
% Range of intra-vascular and extra-vascular T2* relaxation rates per field
% strength, as reviewed by Donahue et al. 2011.
switch B0
case 1.5
T2i = 90:0.5:100; T2e = 55:0.5:65; % 1.5 Tesla
TE = 40; % ms
case 3
T2i = 15:0.5:25; T2e = 35:0.5:45; % 3 Tesla
TE = 30; % ms
case 7
T2i = 3:0.5:7; T2e = 25:0.5:30; % 7 Tesla
TE = 25; % ms
end
% R2* (Hz)
R2i = 1./T2i; R2e = 1./T2e;
% Compute epsilon
epsilon = [];
for i = 1:length(T2i)
for e = 1:length(T2e)
epsilon(i,e) = exp(-R2i(i)*TE) / exp(-R2e(e)*TE);
end
end
figure;hist(epsilon(:));
% Fit a log-normal density
[parmhat] = lognfit(epsilon(:));
fprintf('B0: %1.1fT. Fitted epsilon: %2.2f, LogNormal Mu: %2.2f Variance: %2.2f\n', B0, exp(parmhat(1)), parmhat(1), parmhat(2).^2);
end |
%Prob. 4
%let b0 = 1, b1 = 1
b0 = 1;
b1 = -1;
n = 0:49;
%when a1 < -2, e.g. a1 = -3
a1 = -3;
Hz = z*(b0*z+b1)/(z^2+(a1)*z+(a1^2)/4);
hn1 = iztrans(Hz, n);
figure
stem(n, hn1)
title('Growing exponential')
xlabel('n')
ylabel('h[n]')
%when a1 = -2
a1 = -2;
Hz = z*(b0*z+b1)/(z^2+(a1)*z+(a1^2)/4);
hn2 = iztrans(Hz, n);
figure
stem(hn2)
title('Unit Step')
xlabel('n')
ylabel('h[n]')
b0 = 1;
b1 = 1;
%when 0 > a1 > -2, e.g. a1 = -1
a1 = -1;
Hz = z*(b0*z+b1)/(z^2+(a1)*z+(a1^2)/4);
hn3 = iztrans(Hz, n);
figure
stem(hn3)
title('Decaying exponential')
xlabel('n')
ylabel('h[n]')
%when 2 > a1 > 0, e.g. a1 = 1
a1 = 1;
Hz = z*(b0*z+b1)/(z^2+(a1)*z+(a1^2)/4);
hn4 = iztrans(Hz, n);
figure
stem(hn4)
title('Decaying alternating exponential')
xlabel('n')
ylabel('h[n]')
%when a1 = 2, e.g. a1 = 2
a1 = 2;
Hz = z*(b0*z+b1)/(z^2+(a1)*z+(a1^2)/4);
hn5 = iztrans(Hz, n);
figure
stem(hn5)
title('Unit alternating Step')
xlabel('n')
ylabel('h[n]')
%when a1 > 2, e.g. a1 = 3
a1 = 3;
Hz = z*(b0*z+b1)/(z^2+(a1)*z+(a1^2)/4);
hn6 = iztrans(Hz, n);
figure
stem(hn6)
title('Growing alternating exponential')
xlabel('n')
ylabel('h[n]') |
function ct = ctpg_plasJ2(dgamma,norm_s_trial,kp_new,hp_new,N_new,mu,capa,e_VG)
%******************************************************************************************
%* RETTURN-MAPPING PARA COMPUTO DEL TENSOR TANGENTE: PLANE STRAIN - 3D *
%* MODELO DE PLASTICIDAD J2 CON ENDURECIMIENTO ISOTROPO *
%* *
%* A.E. Huespe, P.J.Sanchez *
%* CIMEC-INTEC-UNL-CONICET *
%******************************************************************************************
%global SSOIT FOAT2
SSOIT = e_VG.SSOIT;
FOAT2 = e_VG.FOAT2;
tita_new = 1 - (2*mu*dgamma)/(norm_s_trial);
tita_new_b = 1/(1+(kp_new+hp_new)/(3*mu)) - (1-tita_new);
ct = (capa*SSOIT) + (2*mu*tita_new*FOAT2) - (2*mu*tita_new_b*(N_new*N_new.')); |
function [m I] = fn_max(a)
% function [m I] = fn_max(a)
%---
% find the global max in an array, and give its coordinates
%
% See also fn_min
% Thomas Deneux
% Copyright 2005-2012
if nargin==0, help fn_min, return, end
[m i] = max(a(:));
i = i-1;
s = size(a);
for k=1:length(s)
I(k) = mod(i,s(k))+1;
i = floor(i/s(k));
end
|
function y=zfunpp02(x)
% derivata seconda funzione test zfunf02 in [-2,6]
y=(6.*(3.*x - 8))./x.^5;
end |
%Fichier contenant la configuration du problème. En opération normale
%seulement ce fichier devrait être modifié.
lambda = 500E-9;
%Échelle du système, correspond à la distance entre la pupille et l'image.
%En mètres. Les résultats sont convertis, l'ensemble des calcul sont fait
%avec une échelle de 1.
echelle_systeme = 0.2; %20cm
%Distance de la surface S. 1: pupille, 0: plan image
z = 0.1;
%F number du faisceau
f_number = 15;
%Centre du grandissement
cx = 0;
cy = 0;
%Grandissement
g1 = 2;
g2 = 1;
%Rayon de la surface à grandir. Le rayon final sera r1*g.
r1 = 0.2;
%Rayon de la zone de redressement
r2 = 0.3;
%Type de profil de distorsion (gaussien ou quadratique)
type_dist = 'gaussien';
%Nombre de rayon simulé par axe (toujours impair)
n = 501;
%Vecteur de points à analyser sur l'image
r = linspace(0,0.4,20);
theta = linspace(0,4*pi,20);
% x = linspace(0,0.5,20);
% y = zeros(1,20);
[x,y] = pol2cart(theta,r);
%Analyse centré sur le centre de la distortion
x = x + cx;
y = y + cy; |
%% Machine Learning Online Class - Exercise 4 Neural Network Learning
%% Initialization
%clear ; close all; clc
%% Setup the parameters you will use for this exercise
input_layer_size = 784; % 20x20 Input Images of Digits
hidden_layer_size = 25; % 25 hidden units
num_labels = 10; % 10 labels, from 1 to 10
% (note that we have mapped "0" to label 10)
%% =========== Part 1: Loading and Visualizing Data =============
% Load Training Data
fprintf('Loading and Visualizing Data ...\n')
%load('ex4data1.mat');
m = size(X, 1);
% Randomly select 100 data points to display
sel = randperm(size(X, 1));
sel = sel(1:100);
displayData(X(sel, :));
fprintf('Program paused. Press enter to continue.\n');
pause;
%% ================ Part 2: Loading Parameters ================
%% ================ Part 6: Initializing Pameters ================
%% ================= Part 9: Visualize Weights =================
fprintf('\nVisualizing Neural Network... \n')
displayData(Theta1(:, 2:end));
fprintf('\nProgram paused. Press enter to continue.\n');
pause;
%% ================= Part 10: Implement Predict =================
pred = predict(Theta1, Theta2, U);
%fprintf('\nTraining Set Accuracy: %f\n', mean(double(pred == v)) * 100);
|
[FileName,PathName] = uigetfile('*.nii','Select the Nifti file','/home/sophie/Desktop/');
file=strcat(PathName,FileName)
D=MRIread(file);
Temp=squeeze(D.vol);
St=size(Temp);
[FileName,PathName] = uigetfile('*.nii','Select the Nifti file','/home/sophie/Desktop/');
file=strcat(PathName,FileName)
D=MRIread(file);
Data=D.vol;
Looks like we need an array of 512*1024*44
Coordinates=zeros(S(1)*S(2)*S(3),3);
for i=1:S(1)
for j=1:S(2)
for k=1:S(3)
Coordinates(((i-1)*S(2)*(j-1)*S(3)+k),:)=[i,j,k];
end
end
end
S=size(Data);
idx=[2 1 3];
[O_transMC2,Spacing,Xreg]=point_registration([256 512 109],JFRCpoints(:,idx),Points945(:,idx));
IregMC2=bspline_transform(O_transMC2,Data,Spacing,3);
out.vol=IregMC2;
err = MRIwrite(out,strcat(file(1:size(file,2)-4),'Tempreg.nii'));
for i=1:S(4)
CLreg(:,:,:,i)=bspline_transform(O_transMC2,CLr(:,:,:,i),Spacing,3);
end
%import time series
DataTS=MIJ.getCurrentImage;
DTS=reshape(DataTS,98,199,93,1159);
S2=size(DTS)
x=1:S2(4);
%play with the initial values of the fit for bleaching to have nice fits
for i=1:S(4)
% for (j=1:S2(4))
% D(:,:,:,j)=DTS(:,:,:,j).*CLregbin(:,:,:,i);
% Mean_Data_in_LPUs(j,i)=mean(mean(mean(D(:,:,:,j))));
% end
A=fit(x',Mean_Data_in_LPUs(:,i),'a*(1+b*exp(c*x)-0.29*exp(0.00012*x))','StartPoint',[0.0001,0.045,-0.03],'Lower',[0.00001,-5,-2],'Upper',[100,2,1])
%
figure(i)
plot(A,x',Mean_Data_in_LPUs(:,i))
B=squeeze(A(x));
U_LPUs(:,i)=Mean_Data_in_LPUs(:,i)-B(:);
end
LPUactivity=-U_LPUs;
for i=1:S(4)
figure(i)
plot(LPUactivity(:,i))
end
|
function PSNR=PSNR(u0,u,uni)
% u0: orginal image
% u: noised image
% (nb,na): size
% generalize to image sequence
if nargin<3
uni=0;
end
if ndims(u)<ndims(u0)
error ('Dimesion of second one should be larger or equal to the dimension of the first one');
end
if (uni)
min_=0;
max_=255;
else
max_=max(max(u0));
min_=min(min(u0));
end
[nb na]=size(u0);
if ndims(u)==2 % They are images
if size(u0)~=size(u)
error ('Sizes of the two images are not equal');
end
MSE=norm(abs(u-u0),'fro')^2/(nb*na);
PSNR=10.*log10((max_-min_)^2/MSE);
else % second one is an image sequence
PSNR=zeros(size(u,3),1);
for i=1:size(u,3)
MSE=norm(abs(u(:,:,i)-u0),'fro')^2/(nb*na);
PSNR(i)=10.*log10((max_-min_)^2/MSE);
end
end |
function InitFigure(obj)
%% target figure
obj.TargetHandle = figure();
obj.TargetHandle.Units = 'Normalized';
obj.TargetHandle.Position = [0.05 0.05 0.9 0.85];
set(obj.TargetHandle,'name','TARGET VIEW','numbertitle','off');
obj.TargetHandle.Units = 'pixels';
colormap(obj.TargetHandle,'gray');
cameratoolbar();
obj.TargetAxesHandle = axes('Parent',obj.TargetHandle,'Color',[0 0 0 ]);
view(obj.TargetAxesHandle,37,45);
U1 = uicontrol('Style','slider','Callback',@changeAlpha, ...
'Position', [20 940 150 50], 'Min',-Inf,'Max',Inf,'Value',0,...
'String','Low');
U2 = uicontrol('Style','slider','Callback',@changeAlpha, ...
'Position', [20 840 150 50], 'Min',-Inf,'Max',Inf,'Value',1,...
'String','High');
obj.TargetSliders(1) =U1;
obj.TargetSliders(2) =U2;
%% main figure
obj.FigureHandle = figure();
obj.FigureHandle.Units = 'Normalized';
obj.FigureHandle.Position = [0.05 0.05 0.9 0.85];
obj.FigureHandle.Color = [0.9 0.9 0.9];
obj.PanelHandle = uipanel('parent',obj.FigureHandle','position',[0 0 0.3 1]);
set(obj.FigureHandle,'name','SPINE IMAGEING','numbertitle','off');
uicontrol('parent', obj.PanelHandle,'position',[30 7 100 22], ...
'Style','pushbutton','Callback',@obj.c_AddFields,'string','Add ROIs');
uicontrol('parent', obj.PanelHandle,'position',[150 7 100 22], ...
'Style','pushbutton','Callback',@obj.c_SaveObjCallback,'string','Save');
uicontrol('parent', obj.PanelHandle,'position',[270 7 100 22], ...
'Style','pushbutton','Callback',@obj.c_displayTarget,'string','Target');
obj.AxesHandle = axes('parent',obj.FigureHandle,'position',[0.35 0.05 0.61 0.9]);
obj.AxesHandle.Color = [0.9 0.9 0.9];
obj.Axes2Handle =axes('parent', obj.PanelHandle,'position',[0.09 0.07 0.8 0.27]);
obj.TextHandle = uicontrol('style','text','units','normalized', ...
'position',[0.3,0.89 0.1 0.1],'fontsize',14','foregroundcolor',...
[1 0 0],'String','Working','parent', obj.FigureHandle);
obj.FigureHandle.Units = 'pixels';
obj.BranchColors = distinguishable_colors(200);
set(obj.AxesHandle,'xlimmode','manual','ylimmode','manual')
set(obj.AxesHandle,'xlim',[0 530],'ylim',[0 530])
axes(obj.AxesHandle);
view(3);
end
function changeAlpha(hObject,~)
obj = evalin('base','Sp');
newval =hObject.Value;
Alim = obj.TargetAxesHandle.ALim;
if strcmp(hObject.String,'Low')
Alim(1) = newval;
else
Alim(2) = newval;
end
obj.TargetAxesHandle.ALim = Alim;
end
|
close all;clear all;clc;
img_rgb = imread('process/colorcapture.jpg');
video_out = 'A4_2_7.mp4';
[M,N,~] = size(img_rgb);
for img_k = 1:3
img = img_rgb(:,:,img_k);
rows = mean(img,2);
cols = mean(img)';
rows = rows-mean(rows);
cols = cols-mean(cols);
K = 1024;
[~,o,FT,~] = prefourier([0,N],N,[0,pi],K);
col_f = FT*cols;
[~,m(img_k)] = max(abs(col_f));
w(img_k) = 2*pi/(o(m(img_k)));
col_p = angle(col_f(m(img_k)));
[~,o,FT,~] = prefourier([0,M],M,[0,pi],K);
row_f = FT*rows;
[~,n(img_k)] = max(abs(row_f));
h(img_k) = 2*pi/(o(n(img_k)));
row_p = angle(row_f(n(img_k)));
m(img_k) = floor(M/h(img_k));
n(img_k) = floor(N/w(img_k));
x(img_k) = abs((row_p/pi/2)*h(img_k));
y(img_k) = abs((col_p/pi/2)*w(img_k));
end
m = mean(m);
n = mean(n);
x = mean(x);
y = mean(y);
w = mean(w);
h = mean(h);
% 第二小问,分块
figure;
for k = 1:m*n
subplot(m,n,k);
a = mod(k-1,n); % 左侧已经有a个
b = ceil(k/n)-1; % 上边已经有b个
imshow(img_rgb(round(y+b*h+1:y+(b+1)*h),round(x+a*w+1:x+(a+1)*w),:));
end
% 第三小问,最相似的十块
figure;
blocks = cell(m,n);
matching = cell(m,n);
corr_mat = zeros(m*n,m*n);
minpeakheight = 0.77;
for k = 1:m*n
a = ceil(k/m)-1; % 左侧已经有a个
b = mod(k-1,m); % 上边已经有b个
tmp = im2double(img_rgb(round(y+b*h+1:y+(b+1)*h),round(x+a*w+1:x+(a+1)*w),:));
x_corr = sqrt(normxcorr2(tmp(:,:,1),img_rgb(:,:,1)).^2 ...
+normxcorr2(tmp(:,:,2),img_rgb(:,:,2)).^2 ...
+normxcorr2(tmp(:,:,3),img_rgb(:,:,3)).^2)/sqrt(3);
for kk = 1:m*n
aa = ceil(kk/m)-1;
bb = mod(kk-1,m);
part = x_corr(round((h-1)/2+y+bb*h+1:(h-1)/2+y+(bb+1)*h),round((w-1)/2+x+aa*w+1:(w-1)/2+x+(aa+1)*w));
if k~=kk % 同一块比较没有意义
corr_mat(k,kk) = max(part(:));
end
if any(part(:)>minpeakheight)
matching{kk}(end+1) = k;
end
end
blocks{b+1,a+1} = tmp;
end
corr_mat = (corr_mat+corr_mat')/2; % 由于算法的不对称性,结果的对称性稍微破缺
corr_mat = tril(corr_mat); % 再次平均以后仅使用下三角部分
[~,index] = sort(corr_mat(:),'descend');
index10 = index(1:10); % 截取前十个
index_i = mod(index10-1,m*n)+1; % 转为二维坐标
index_j = ceil(index10/(m*n));
for k = 1:10
subplot(2,5,k);
handle = imshow([blocks{index_i(k)};blocks{index_j(k)}]);
title(sprintf('r=%.4f',corr_mat(index_i(k),index_j(k))));
end
% 第四小问,最相似但不是正确匹配的十块
figure;
count = 0;
result = zeros(m,n);
matches = [];
for k = 1:m*n
if result(k)==0
if any(result(matching{k})) % 是否已经有匹配?
result(matching{k}) = max(result(matching{k}));
else
count = count+1;
result(matching{k}) = count;
end
else
result(matching{k}) = result(k);
end
end
index1 = mod(index-1,m*n)+1;
index2 = ceil(index/(m*n));
i1 = mod(index1-1,m)+1;
j1 = ceil(index1/m);
i2 = mod(index2-1,m)+1;
j2 = ceil(index2/m);
selected = zeros(1,10);
count = 0;
for k = 1:length(index)
if result(i1(k),j1(k))~=result(i2(k),j2(k))
count = count+1;
selected(count) = index(k);
end
if count == 10
break;
end
end
index1 = mod(selected-1,m*n)+1; % 转为二维坐标
index2 = ceil(selected/(m*n));
for k = 1:10
subplot(2,5,k);
imshow([blocks{index1(k)};blocks{index2(k)}]);
title(sprintf('r=%.4f',corr_mat(index1(k),index2(k))));
end
% 第五小问
figure;
for k = 1:m*n
subplot(m,n,k);
a = mod(k-1,n); % 左侧已经有a个
b = ceil(k/n)-1; % 上边已经有b个
imshow(img_rgb(round(y+b*h+1:y+(b+1)*h),round(x+a*w+1:x+(a+1)*w),:));
title(sprintf('%d',result(b+1,a+1)));
end
% 第六小问
figure;
addpath(strcat(pwd,'\linkgame'));
steps = omg(result); % 调用之前的函数计算步骤
img_now = img_rgb;
% 录制视频
video_obj=VideoWriter(video_out,'MPEG-4');
open(video_obj);
for k = 1:steps(1)
img_last = img_now;
b = steps(4*k-2)-1;
a = steps(4*k-1)-1;
img_now(round(y+b*h+1:y+(b+1)*h),round(x+a*w+1:x+(a+1)*w),:) = 0;
b = steps(4*k)-1;
a = steps(4*k+1)-1;
img_now(round(y+b*h+1:y+(b+1)*h),round(x+a*w+1:x+(a+1)*w),:) = 0;
imshow(img_now);
current_frame=getframe;
for kk = 1:15 % 帧率30fps
writeVideo(video_obj,current_frame);
end
pause(0.5);
imshow(img_last);
current_frame=getframe;
for kk = 1:15 % 帧率30fps
writeVideo(video_obj,current_frame);
end
pause(0.5);
imshow(img_now);
current_frame=getframe;
for kk = 1:15 % 帧率30fps
writeVideo(video_obj,current_frame);
end
pause(0.5);
end
close(video_obj); |
function [RegistrationParameter]=Ant_K(M,I1,I2)
%%%%%%%%%%%%%%%%%初始化%%%%%%%%%%%%%%%%%%%%%%%%%%%
Ant=10; %蚂蚁数量
Times=100; %蚂蚁移动次数
Rou=0.5; %信息素挥发系数
P0=0.2; %转移概率常数
Lower_1=0; %设置搜索范围
Upper_1=1;
%}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:Ant
X(i,1)=(Lower_1+(Upper_1-Lower_1)*rand);
%随机设置蚂蚁的初值位置
Tau(i)=F(X(i,1),M,I1,I2); %计算信息量
end
for T=1:Times
lamda=1/T;
[Tau_Best(T),BestIndex]=max(Tau);
for i=1:Ant
P(T,i)=(Tau(BestIndex)-Tau(i))/Tau(BestIndex);
%计算状态转移概率
end
for i=1:Ant
if P(T,i)<P0 %局部搜索
temp1=X(i,1)+(2*rand-1)*lamda;
else %全局搜索
temp1=X(i,1)+(Upper_1-Lower_1)*(rand-0.5);
end
%%%%%%%%%%%%%%%越界处理%%%%%%%%%%%%%%%%%%%%%%
if temp1<Lower_1
temp1=Lower_1;
end
if temp1>Upper_1
temp1=Upper_1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if F(temp1,M,I1,I2)>F(X(i,1),M,I1,I2)
%判断蚂蚁是否移动
X(i,1)=temp1;
end
end
for i=1:Ant
Tau(i)=(1-Rou)*Tau(i)+F(X(i,1),M,I1,I2);
%更新信息量
end
end
[max_value,max_index]=max(Tau);
maxX=X(max_index,1);
RegistrationParameter(1)=maxX; %y
end
function [F]=F(k,M,I1,I2) %目标函数
F=-mse(MM(k,M,I1,I2),I2);
end
function [M]=MM(k,M,I1,I2) %目标函数
Hsmooth=fspecial('gaussian',[60 60],10);
Tx=zeros(size(M)); Ty=zeros(size(M));
Idiff=M-I2;
[My,Mx] = gradient(M);
% Default demon force, (Thirion 1998)
Ux = -(Idiff.*Mx)./((Mx.^2+My.^2)+k^2);
Uy = -(Idiff.*My)./((Mx.^2+My.^2)+k^2);
% Extended demon force. With forces from the gradients from both
% % moving as static image. (Cachier 1999, He Wang 2005)
% [My,Mx] = gradient(M);
% Ux = -Idiff.* ((Sx./((Sx.^2+Sy.^2)+(Idiff).^2))+(Mx./((Mx.^2+My.^2)+(Idiff).^2)));
% Uy = -Idiff.* ((Sy./((Sx.^2+Sy.^2)+(Idiff).^2))+(My./((Mx.^2+My.^2)+(Idiff).^2)));
% %
% When divided by zero
Ux(isnan(Ux))=0; Uy(isnan(Uy))=0; %判断是否是非数值参数
% Smooth the transformation field
Uxs=3*imfilter(Ux,Hsmooth);
Uys=3*imfilter(Uy,Hsmooth);
% Add the new transformation field to the total transformation field.
Tx=Tx+Uxs;
Ty=Ty+Uys;
M=movepixels(I1,Tx,Ty);
end |
function pfl_output = persForLoopSplitSaves( varargin )
% Handle args and setup
if isa(varargin{nargin}, 'char')
identifier = append('__pfl_state__', varargin{nargin});
filename = append(identifier, '.mat');
f = varargin{nargin - 1};
num_iterators = nargin - 2;
else
identifier = '__pfl_state';
filename = append(identifier, '.mat');
f = varargin{nargin};
num_iterators = nargin - 1;
end
iterator_sizes = cellfun(@(x) length(x) , varargin(1:num_iterators));
if ~isa(f, 'function_handle')
err(append('Expected function_handle, received ', class(f)))
end
% Check for existing state
if isfile(filename)
load(filename)
% Load up previous state of rng
rng(pfl_rng);
else
% We prepend these with pfl_
% So that they are note affected by workspace
% Not sure if necessary?
pfl_workingOn = ones(1, num_iterators);
pfl_rng = rng;
end
% Start the work loop
while ~isa(pfl_workingOn,'char')
% Do the work
workSnippet = getWorkSnippet(num_iterators, pfl_workingOn);
outputOfWork = eval(workSnippet);
% Save work to file
thisWorksFilename = getWorkFilename(pfl_workingOn, identifier);
save(thisWorksFilename,'outputOfWork');
workStr = getWorkStr(pfl_workingOn);
% Get next work and save progress
pfl_workingOn = getNextWork(pfl_workingOn, iterator_sizes);
pfl_rng = rng;
save(filename, 'pfl_workingOn', 'pfl_rng');
% Report
fprintf('Finished %s\n', workStr)
end
fprintf('Rejoining save files, please do not abort!\n')
% Rejoin save files
pfl_workingOn = ones(1, num_iterators);
if num_iterators == 1
pfl_output = cell(1, iterator_sizes);
else
pfl_output = cell(iterator_sizes);
end
while ~isa(pfl_workingOn,'char')
thisWorksFilename = getWorkFilename(pfl_workingOn, identifier);
load(thisWorksFilename,'outputOfWork');
% Store the work
storageSnippet = getStorageSnippet(pfl_workingOn);
eval(storageSnippet);
% Get next work
pfl_workingOn = getNextWork(pfl_workingOn, iterator_sizes);
end
fprintf('Deleting save files, please do not abort!\n')
% Clean up split saves
pfl_workingOn = ones(1, num_iterators);
while ~isa(pfl_workingOn,'char')
% Delete save file
thisWorksFilename = getWorkFilename(pfl_workingOn, identifier);
delete(thisWorksFilename);
% Get next work
pfl_workingOn = getNextWork(pfl_workingOn, iterator_sizes);
end
% Clean up persistence file
delete(filename)
end
function snippet = getWorkSnippet(num_iterators, workingOn)
zippedWorkingOn = [1:num_iterators; workingOn];
zippedWorkingOn = zippedWorkingOn(:);
argStr = sprintf('varargin{%d}(%d),', zippedWorkingOn);
argStr = argStr(1:end-1);
snippet = append('f(',argStr,')');
end
function workStr = getWorkStr(workingOn)
workStr = join(split(num2str(workingOn)),'_');
workStr = workStr{1};
end
function worksFilename = getWorkFilename(workingOn, identifier)
workStr = getWorkStr(workingOn);
worksFilename = append(identifier,'__',workStr,'.mat');
end
function snippet = getStorageSnippet(workingOn)
idxStr = sprintf('%d,', workingOn);
idxStr = idxStr(1:end-1);
snippet = append('pfl_output{', idxStr, '} = outputOfWork;');
end
function workingOn = getNextWork(workingOn, iterator_sizes)
workingOn(end) = workingOn(end) + 1;
for i=length(iterator_sizes):(-1):1
if workingOn(i) > iterator_sizes(i)
if i == 1
% We've done all the work
workingOn = 'finished';
return
end
workingOn(i) = workingOn(i) - iterator_sizes(i);
workingOn(i-1) = workingOn(i-1) + 1;
end
end
end
|
function [output] = myCLAHE(input,w_size,clip)
%MYCLAHE Summary of this function goes here
% Detailed explanation goes here
[row,col,numChannels] = size(input);
for k = 1:numChannels
for i = 1:row
for j = 1:col
window = input(max(1,i-w_size):min(row,i+w_size),max(1,j-w_size):min(col,j+w_size));
histogram = imhist(window);
clip_value = clip*sum(histogram);
clipped_area = sum(max(0,histogram-clip_value));
histogram = min(histogram,clip_value);
histogram = histogram + clipped_area/256;
cum_hist = cumsum(histogram)/sum(histogram);
output(i,j,k) = cum_hist(input(i,j,k) + 1);
end
end
end
end
|
function plotPath(states,waypoints)
% plotPath.m e.anderlini@ucl.ac.uk 15/09/2017
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function is used to plot the path of the ROV.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure;
plot3(states(:,1),states(:,2),states(:,3));
hold on;
scatter3(waypoints(:,1),waypoints(:,2),waypoints(:,3),'MarkerEdgeColor',...
[0.8500,0.3250,0.0980]);
xlabel('$x$ (m)','Interpreter','Latex');
ylabel('$y$ (m)','Interpreter','Latex');
zlabel('$z$ (m)','Interpreter','Latex');
grid on;
set(gca,'TickLabelInterpreter','Latex')
set(gcf,'color','w');
end |
function [w] = train(x,yd,nro_epocas,criterio,tasa_ap)
#criterio = nro de 0 a 1
x=[-1*ones(size(x,1),1) x]; #Agrega a x la columna de -1 al inicio
w=rand(size(x,2),1)-0.5;
for epoca=1:nro_epocas
#Corrección de los w
for patron=1:size(x,1)
#funcion de transferencia
z=x(patron,:)*w;
if (z>=0)
y=1;
else
y=-1;
endif
# ajustar pesos
w = w + 0.5*tasa_ap*(yd(patron)-y)*x(patron,:)';
endfor
# desempeño de epoca ( validacion si contamos con otro conjunto de datos )
desempenio=0;
for patron=1:size(x,1)
z=x(patron,:)*w;
if (z>=0)
y_val=1;
else
y_val=-1;
endif
if y_val == yd(patron)
desempenio += 1;
endif
endfor
# nro de aciertos / nro total de casos
desempenio_prom = desempenio / size(x,1);
if desempenio_prom >= criterio
break
endif
endfor
endfunction |
function [s, table0, poly0, img0] = saveData( obj, table, poly, img, filename)
% SAVEDATA
%
% DESCRIPTION:
%
%
% SYNTAX:
%
%
% INPUTS:
%
%
% OUTPUTS:
%
%
% COMMENTS:
%
%@
% Copyright 2016 The Johns Hopkins University Applied Physics Laboratory
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
%@
%
table0 = [];
poly0 = [];
img0 = [];
imSize = size(img);
types = table(:,1);
types(cellfun(@isempty, types)) = {' 0. NOT LABELED'};
label = unique(types);
mask = zeros(imSize(1), imSize(2), numel(label));
for p = 1:numel(poly)
ind = strcmp(label, types(p));
tmp = roipoly(mask(:,:,ind), poly{p}(:,1), poly{p}(:,2));
mask(:,:,ind) = mask(:,:,ind) | tmp;
end
s.imSize = imSize;
s.label = label;
s.mask = mask;
end
|
function mprocessfinish(pid,status)
%MPROCESSFINISH will mark the process as finished.
% MPROCESSFINISH(PID,STATUS) will indicate that the process was completed with the given status.
%
% Example:
% MPROCESSFINISH(PID,1) will mark the process PID as completed sucessfully.
%
% Copyright (C) 2010 James Dalessio
% Declare the process data as a global variable.
global MAESTRO_PROCESS_DATA
% Mark the given process as completed with the given status.
MAESTRO_PROCESS_DATA(pid).STATUS = status;
MAESTRO_PROCESS_DATA(pid).ISRUNNING = 0;
% Check whether or not to display text.
if mvolume == 1
if ~isdeployed
if MAESTRO_PROCESS_DATA(pid).WASWARNING
mtalk('\b\b\b\b\b\b\b[ WARNING ]',1,0);
elseif status == 0
mtalk('\b\b\b\b\b\b\b[ FAILED ]\n',1,0);
elseif status == 1
mtalk('\b\b\b\b\b\b\b[ OK ]',1,0);
elseif status == -1
mtalk('\b\b\b\b\b\b\b[ WARNING ]',1,0);
end
else
if MAESTRO_PROCESS_DATA(pid).WASWARNING
mtalk('\b\b\b\b\b\b\b [ WARNING ] ',1,0);
elseif status == 0
mtalk('\b\b\b\b\b\b\b [ FAILED ]\n ',1,0);
elseif status == 1
mtalk('\b\b\b\b\b\b\b [ OK ] ',1,0);
elseif status == -1
mtalk('\b\b\b\b\b\b\b [ WARNING ] ',1,0);
end
end
else
if status == 0
mtalk('[ FAILED ]\n',1,0);
elseif status == 1
mtalk('[ OK ]',1,0);
elseif status == -1
mtalk('[ WARNING ]',1,0);
end
end
|
%ATHELP generates the list of Accelerator Toolbox functions
ATROOT = getenv('ATROOT');
if isempty(ATROOT)
ATROOT = atroot;
end
disp('Physics Tools');
disp('');
help(fullfile(ATROOT,'atphysics'))
disp('Touschek Pivinski');
disp('');
help(fullfile(ATROOT,'atphysics', 'TouschekPiwinski'))
disp('Lattice Tools');
disp('');
help(fullfile(ATROOT, 'lattice'))
help(fullfile(ATROOT, 'atgui'))
disp('Element creation');
disp('');
help(fullfile(ATROOT,'lattice','element_creation'))
disp('atfastring');
disp('');
help(fullfile(ATROOT,'lattice', 'atfastring'))
disp('Survey');
disp('');
help(fullfile(ATROOT,'lattice', 'survey'))
disp('Integrators Tracking Methods');
disp('');
help(fullfile(ATROOT,'..', 'atintegrators'))
help(fullfile(ATROOT,'attrack'))
disp('User defined Integrators');
disp('');
help(fullfile(ATROOT,'..','atintegrators', 'user'))
disp('Matching Tools');
disp('');
help(fullfile(ATROOT,'atmatch'))
disp('Plot Tools to be used with atplot');
disp('');
help(fullfile(ATROOT,'atplot'))
disp('Plot functions to be used with atplot');
help(fullfile(ATROOT,'atplot', 'plotfunctions'))
disp('AT Demos');
disp('');
help(fullfile(ATROOT,'atdemos')) |
function net = Classification(XTrain, YTrain, XTest, YTest)
%Train and test classification model
%Input: Train data, Train data label, Test data, Test data label
%Output: Trained neural networks
% numObservations = numel(XTrain);
% for i=1:numObservations
% sequence = XTrain{i};
% sequenceLengths(i) = size(sequence,2);
% end
%
% [sequenceLengths,idx] = sort(sequenceLengths);
% XTrain = XTrain(idx);
% YTrain = YTrain(idx);
%
% figure;
% bar(sequenceLengths);
% ylim([0 30]);
% xlabel("Sequence");
% ylabel("Length");
% title("Sorted Data");
inputSize = length(XTrain(:,1));
numHiddenUnits = 100;
numClasses = numel(unique(YTrain));
layers = [ ... %Combining different layers according to different situation
sequenceInputLayer(inputSize)
bilstmLayer(numHiddenUnits,'OutputMode','last')
fullyConnectedLayer(numClasses)
softmaxLayer
classificationLayer];
maxEpochs = 100;
miniBatchSize = 27;
options = trainingOptions('adam', ... %Modifing parameters according to your requirement
'ExecutionEnvironment','cpu', ...
'GradientThreshold',1, ...
'MaxEpochs',maxEpochs, ...
'MiniBatchSize',miniBatchSize, ...
'SequenceLength','longest', ...
'Shuffle','never', ...
'Verbose',0, ...
'Plots','training-progress');
net = trainNetwork(XTrain,YTrain,layers,options);
miniBatchSize = 27;
YPred = classify(net,XTest, ...
'MiniBatchSize',miniBatchSize, ...
'SequenceLength','longest');
acc = sum(YPred == YTest)./numel(YTest);
end
|
% [OUTPUT_kfold, CVP_kfold] = feature_variability_impact_kfold;
load OUTPUT_kfold
load Common_feature_type
k_fold = length(OUTPUT_kfold);
nb_features = size(OUTPUT_kfold{1},1);
feature_name_table = cell2table(OUTPUT_kfold{1,1}{:,1});
feature_name_table.Properties.VariableNames{'Var1'} = 'Feature_name';
% Plot histogram of feature range
TF = OUTPUT_kfold{1}.Feature_values;
figure, hist(TF{28}.CellProfiler_Texture_Contrast_3_0,70);
figure, hist(TF{32}.CellProfiler_Texture_AngularSecondMoment_3_0,70);
classifier_ind = 1;
Tools_to_plot = {'Python'; 'CellProfiler'; 'MaZda'; 'ImageJ'; 'Java'};
nb_tools = length(Tools_to_plot);
% Get the features that are computed for a given tool
feature_tool_indx = false(nb_features,nb_tools);
for t = 1:nb_tools
tool = Tools_to_plot{t};
for f = 1:nb_features
% Find indexes of this tool name for every feature.
find_indx_cell = cellfun(@(x)strfind(x,tool),OUTPUT_kfold{1}.Tool_name{f},'UniformOutput',0);
feature_tool_indx(f,t) = sum(~cellfun(@isempty,find_indx_cell));
end
end
% The common_feature_table shows the number of features in common between a pair of tools
common_feature_table = cell2table(cell(nb_tools,nb_tools), 'VariableNames', Tools_to_plot, 'RowNames', Tools_to_plot);
% The feature_variability_table shows the number of features that express differences in values larger than 0.1% between a pair of tools
feature_variability_table = array2table(cell(nb_tools,nb_tools), 'VariableNames', Tools_to_plot, 'RowNames', Tools_to_plot);
% The feature_impact_table shows the number of ROI (out of 70 total) that were classified differently between a pair of tools
feature_impact_table = array2table(cell(nb_tools,nb_tools), 'VariableNames', Tools_to_plot, 'RowNames', Tools_to_plot);
for t1 = 1:nb_tools-1
tool1_name = Tools_to_plot{t1};
for t2 = t1+1:nb_tools
tool2_name = Tools_to_plot{t2};
% find the features in common between these two tools
common_features_2_tools = feature_tool_indx(:,t1) & feature_tool_indx(:,t2);
common_feature_table{t1,t2} = {common_features_2_tools};
% Initialize the difference between tools
feature_diff = nan(nb_features,k_fold);
feature_class_diff = nan(nb_features,k_fold);
for f = 1:nb_features
% if not common feature between the two tools, skip it
if ~common_features_2_tools(f), continue, end
% Get tool1 and tool2 index in the list of all available tools
find_indx_cell = cellfun(@(x)strfind(x,tool1_name),OUTPUT_kfold{1}.Tool_name{f},'UniformOutput',0);
tool1_ind = find(~cellfun(@isempty,find_indx_cell));
find_indx_cell = cellfun(@(x)strfind(x,tool2_name),OUTPUT_kfold{1}.Tool_name{f},'UniformOutput',0);
tool2_ind = find(~cellfun(@isempty,find_indx_cell));
% Get feature values from both tools for all k_fold
for g = 1:k_fold
F1 = OUTPUT_kfold{g}.Feature_values{f}{:,tool1_ind(1)};
F2 = OUTPUT_kfold{g}.Feature_values{f}{:,tool2_ind(1)};
% Compute the number of features that differ more that 0.1%
D = (F1-F2)./mean([F1,F2],2);
feature_diff(f,g) = sum( D > 0.001);
% Get classification for each tool
C1 = OUTPUT_kfold{g}.Prediction{f,1}{1,classifier_ind}{1}{:,tool1_ind(1)};
C2 = OUTPUT_kfold{g}.Prediction{f,1}{1,classifier_ind}{1}{:,tool2_ind(1)};
feature_class_diff(f,g) = sum((C1-C2)~=0);
end
end
% save results as average values computed from all k_fold runs
feature_variability_table{t1,t2} = {mean(feature_diff,2)};
feature_impact_table{t1,t2} = {mean(feature_class_diff,2)};
end
end
% Get the number of common features between tools and the number of features that vary with more than 1%
common_features_matrix = cellfun(@(x)sum(x>0),table2cell(common_feature_table));
common_features_matrix = array2table(common_features_matrix, 'VariableNames', Tools_to_plot, 'RowNames', Tools_to_plot);
common_features_variability_matrix = cellfun(@(x)sum(x>0),table2cell(feature_variability_table));
common_features_variability_matrix = array2table(common_features_variability_matrix, 'VariableNames', Tools_to_plot, 'RowNames', Tools_to_plot);
% Get the common features numbers and the feature variability numbers by feature type: intensity, shape and texture
unique_feature_type_names = unique(Common_feature_type);
m = 1;
TT = cell(1,1);
for t1 = 1:nb_tools-1
tool1_name = Tools_to_plot{t1};
for t2 = t1+1:nb_tools
tool2_name = Tools_to_plot{t2};
cf = common_feature_table{t1,t2}{1}>0; % common feature index between t1 and t2
fv = feature_variability_table{t1,t2}{1}>0; % feature variability value between t1 and t2
for i = 1:length(unique_feature_type_names)
feature_type_ind = strcmp(unique_feature_type_names(i),Common_feature_type);
TT{m,1} = [tool1_name ' VS ' tool2_name];
TT{m,i+1} = [num2str(sum(fv(feature_type_ind))) '/' num2str(sum(cf(feature_type_ind)))];
end
m = m+1;
end
end
common_features_variability_matrix_feature_type = array2table(TT, 'VariableNames', [{'Software'}; unique_feature_type_names]);
writetable(common_features_variability_matrix_feature_type,'common_features_variability_matrix_feature_type.csv')
% Plot results for variability
figure, hold on
% plot_color = jet(nb_tools*(nb_tools-1)/2);
plot_color = linspecer(nb_tools*(nb_tools-1)/2);
legend_label = [];
m = 1;
TT = [];
marker_plot = '>ox^+*sd<v';
for t1 = 1:nb_tools-1
tool1_name = Tools_to_plot{t1};
for t2 = t1+1:nb_tools
tool2_name = Tools_to_plot{t2};
cf = common_feature_table{t1,t2}{1};
h = plot(feature_variability_table{t1,t2}{1},1:nb_features);
TT(:,m) = feature_variability_table{t1,t2}{1};
h.Color = plot_color(m,:);
h.LineStyle = 'none';
h.LineWidth = 2;
h.Marker = marker_plot(m);
h.MarkerSize = 8;
legend_label{m} = [tool1_name ' VS ' tool2_name];
m = m+1;
end
end
legend(legend_label)
set(gca,'FontSize',30)
for i = 1:length(legend_label), legend_label{i} = legend_label{i}(~isspace(legend_label{i})); end
TT = array2table(TT,'VariableNames',legend_label);
TT = [feature_name_table TT];
writetable(TT,'Feature_variability.csv')
a = gca;
a.YTick = 0:5:nb_features;
% a.XTickLabel = OUTPUT_kfold{1}{:,3};
% Get the number of features that impacted the stem cell colony classification
common_features_impact_matrix = cellfun(@(x)sum(x>0),table2cell(feature_impact_table));
common_features_impact_matrix = array2table(common_features_impact_matrix, 'VariableNames', Tools_to_plot, 'RowNames', Tools_to_plot);
% Plot results for impact
figure, hold on
plot_color = linspecer(nb_tools*(nb_tools-1)/2);
legend_label = [];
m = 1;
TT = [];
for t1 = 1:nb_tools-1
tool1_name = Tools_to_plot{t1};
for t2 = t1+1:nb_tools
tool2_name = Tools_to_plot{t2};
cf = common_feature_table{t1,t2}{1};
h = plot(feature_impact_table{t1,t2}{1},1:nb_features);
TT(:,m) = feature_impact_table{t1,t2}{1};
h.Color = plot_color(m,:);
h.LineStyle = 'none';
h.LineWidth = 2;
h.Marker = marker_plot(m);
h.MarkerSize = 8;
legend_label{m} = [tool1_name ' VS ' tool2_name];
m = m+1;
end
end
legend(legend_label)
set(gca,'FontSize',30)
for i = 1:length(legend_label), legend_label{i} = legend_label{i}(~isspace(legend_label{i})); end
TT = array2table(TT,'VariableNames',legend_label);
TT = [feature_name_table TT];
writetable(TT,'Feature_variability_impact.csv')
a = gca;
a.YTick = 0:5:nb_features;
% a.YTickLabel = table2cell(feature_name_table);
|
%% Compactar imagens
% Compacta as imagens de um diretório específico
%%
caminho = '/media/dados/facedatabase/AR_warp_zip/test2/';
outputPath = '/media/dados/facedatabase/ARface_48_56/';
fileFolder = fullfile(caminho);
dirOutput = dir(fullfile(fileFolder,'*.bmp'));
fileNames = {dirOutput.name}';
numFrames = numel(fileNames);
cont =1;
for p = 1:numFrames
name = [fileFolder '/' fileNames{p}];
I2 = imread(name);
I2 =rgb2gray(I2);
[x y] = size(I2);
I2 = imcrop(I2,[0 24 y x-24]);
I2 = imresize(I2, [56 NaN]);
[people_name_tmp, imgIdx] = strtok(fileNames{p},'.');
imwrite(I2, [outputPath '/' people_name_tmp '.png']);
end
|
classdef Cell < handle
%Mesh cell class
properties(SetAccess = private)
vertices %adjacent vertices. Have to be sorted according
%to local vertex number!(counterclockwise
%starting from lower left corner)
edges %adjacent edges. Have to be sorted according to
%local edge number! (counterclockwise starting
%from lower left corner)
surface %surface of cell element
centroid %centroid of cell
type = 'rectangle'
end
methods
function self = Cell(vertices, edges, type)
%Constructor
%Vertices and edges must be sorted according to local
%vertex/edge number!
self.vertices = vertices;
self.edges = edges;
if nargin > 2
self.type = type;
end
%Compute centroid
self.centroid = 0;
for n = 1:numel(self.vertices)
self.centroid = self.centroid + self.vertices{n}.coordinates;
end
self.centroid = self.centroid/numel(self.vertices);
self.compute_surface;
end
function delete_edges(self, indices)
%Deletes edges according to indices
for i = indices
delete(self.edges{i});
self.edges{i} = [];
end
end
function compute_surface(self)
if strcmp(self.type, 'rectangle')
self.surface = self.edges{1}.length*self.edges{2}.length;
else
error('unknown cell type')
end
end
function [isin] = inside(self, x)
%Check if point is inside of cell
% x: N*dim array, --> each line is a point
isin = (x(:, 1) > self.vertices{1}.coordinates(1) - eps & ...
x(:, 1) <= self.vertices{3}.coordinates(1) + eps & ...
x(:, 2) > self.vertices{1}.coordinates(2) - eps & ...
x(:, 2) <= self.vertices{3}.coordinates(2) + eps);
end
end
end
|
% ANALYZING THE CC RESULTS
clear all;close all;
% choose directory of cell to be analyzed
CellPath = uigetdir()
% set the current path to that directory
path = cd(CellPath);
files = dir('*.mat'); %list the .mat files in the cwd
vars = cell(size(files)); %initialize a cell the size of the number of files we have
for ii = 1:numel(files) %for each file
fields{ii} = files(ii).name; %save the name of the files
end
[OrderedFileNames,index] = sort_nat(fields); %order the files by name in ascending order
waveformFiles = strfind(OrderedFileNames,'AD'); %find the files corresponding to waveforms
OrderedFileNames = OrderedFileNames(1:sum(cell2mat(waveformFiles)));
for ii = 1:numel(files) %for each file
vars{ii} = load(OrderedFileNames{ii}); %in each cell of the array 'vars' load the struct with the data from each file
fieldsID{ii} = OrderedFileNames{ii}(1:end-4); %substract the .mat from the name
fieldsID{ii} = regexprep(OrderedFileNames{ii},'.mat',''); %substract the .mat from the name to use later on for reading the struct names
data{1,ii} = vars{ii,1}.(fieldsID{ii}).data(1:30000); %in a new cell array called 'data', store in each cell the info corresponding to the waveforms in each file.
data{2,ii} = OrderedFileNames{ii};
end
% for i=1:size(data,2)
% data{1,i} = data{1,i}(1:30000);
% end
% % Read the ephys files from a chosen directory
% [data,CellPath] = readEphysFiles(false);
%% Define pulses and responses
[responses,correctedPulses] = DefinePulsesAndResponses(data);
%% plot the raw results, all together
%figure, set(gcf,'units','points','position',[100,100,1000,600]); %if I run it in lab
figure, set(gcf,'units','points','position',[80,80,600,350]); %if I run it in my laptop
subplot(2,1,1)
hold on
cellfun(@plot,correctedPulses)
title('Current pulses'), ylabel('Current (pA)');
ylim([-300, 900]);
subplot(2,1,2)
hold on
cellfun(@plot,responses)
title('Responses'), ylabel('Voltage (mV)'); xlabel('Time (ms)');
saveas(gcf,fullfile(CellPath,'AllTraces.png'));
%saveas(gcf,'AllTraces.svg');
%% Find peaks (APs) in the individual responses
% Find the APs with an automatic function, and if you want, plot the
% individual results
[peakLoc,peakMag] = myPeakFinder(correctedPulses,responses,true,0);
%% AP analysis
close all;
pulseStart = 5000; % when in the protocol is our pulse starting (in points)
pulseEnd = 15000; % when is it ending
threshold = 10; % define a threshold to look for AP
[APlocation,APpeak,APthreshold,latency,APthrough,APhalfwidth,APamplitude,sweepnumberwithfirstAP] = FindAPProperties(pulseStart,pulseEnd,responses,threshold,peakLoc,peakMag);
%% IV curve
for ii = 1:size(responses,2)
pulseV(ii) = median(responses{1,ii}(pulseStart:pulseEnd)); %calculate the voltage of the plateau, using the median of the round value of V during the pulse
currents(ii) = correctedPulses{1,ii}(10300); %measure the current during a specific point of the pulse given
DifCurrents(ii) = currents(ii) - correctedPulses{1,ii}(300); %add an extra correction, given that they start shifted from zero sometimes. Make it read the difference instead.
end
% Plot the IV curve using the "plotIVcurve" function
[a] = plotIVcurve(pulseV,DifCurrents,monitor);
%% Hyperpolarization parameters
% Calculate the hypolarized steady state and the sag using the
% hyperpolParameters function
[hyperpolsteadystate,sag] = hyperpolParameters(DifCurrents,responses,pulseStart,pulseEnd);
%% first sweep with AP
for ii = 1:size(responses,2)
APnum(ii) = size(peakLoc{ii},2);
end
% AP number in sweep with first AP
spikenumberfirsttrain = APnum(sweepnumberwithfirstAP);
%rheobase
rheobase = DifCurrents(sweepnumberwithfirstAP);
%% Firing rate
[maxAPnum,InstFR,totFR,maxInstFR,maxtotFR] = firingRateAnalysis(APnum,peakLoc);
%% If curves with the three different frequencies
plotIFcurves(DifCurrents,APnum,InstFR,maxInstFR,totFR,maxtotFR,0);
%% Load session's properties and save outputs to struct
[cellProp] = restingProp(CellPath,APthrough,InstFR,totFR,sag,maxtotFR,maxInstFR,rheobase,correctedPulses,responses,peakLoc,peakMag,pulseV,DifCurrents,APnum,APthreshold,latency,APamplitude,APhalfwidth,maxAPnum);
|
function [Rq,Rq_tube]=reachTubeExt(rec,tau,Aq,fq,Dq)
q = rec.getMidpoint';
eta = (rec.xmax-rec.xmin)';
X_q_hat = zonoBox([],eta/2);
X0 = zonoBox(q,eta/2);
e_At = expm(Aq*tau);
% Calculate G
if(rank(Aq) == length(Aq))
G = (-Aq)\(eye(size(Aq))-e_At);
else
f = @(t) expm(Aq.*(tau-t));
G = integral(f,0,tau,'ArrayValued',true);
end
% Calculate alpha, beta, gamma
inf_A = norm(Aq,'inf');
expA = exp(tau*inf_A);
com_fact = (expA - 1 - tau*inf_A);
one = ones(length(Aq));
inf_x = sum(abs(X0.gener),2);
nx1 = norm(X0.cv+inf_x,'inf');
nx2 = norm(X0.cv-inf_x,'inf');
alpha_t = com_fact*max(nx1,nx2)*one;
max_u = max(abs(Dq.cv)+sum(abs(Dq.gener),2));
beta_t = com_fact*inf_A^(-1)*max_u*one;
gamma_t = com_fact*inf_A^(-1)*norm(fq,'inf')*one;
Yt = (e_At*X_q_hat) + G*fq + tau*Dq + zonoBox([],beta_t);
Rq = Yt + q;
B_ag = zonoBox([],alpha_t+gamma_t);
Rq_tube = CH(X_q_hat,Yt+B_ag) + q;%CH(X_q_hat,Yt+B_ag)+q;
% clean zero generators
Rq.clean_gener;
Rq_tube.clean_gener;
end |
function check = check_feasibility(node, d)
if(node.index == 1)
index = 1;
n_index = 2;
else
index = 2;
n_index = 1;
end
tol = 0.001; %%tolerance for rounding errors
if (d(node.index) < 0-tol), check = 0; return; end;
if (d(node.index) > 100+tol), check = 0; return; end;
if (d(node.index)*node.k(1)+ d(n_index)*node.k(2)< node.L-node.o-tol), check = 0; return; end;
check = 1;
end |
function deleteBlockLines(blockName)
% Delete incoming and outgoing lines from a block
%
% deleteBlockLines(blockName)
%
% Delete incoming and outgoing lines from blockName
if blockExists(blockName)
% delete outgoing lines
nPorts = getNumOutPorts(blockName);
for iPort = 1:nPorts
deleteOutgoingLine(blockName, iPort);
end
% delete incoming lines
nPorts = getNumInPorts(blockName);
for iPort = 1:nPorts
deleteIncomingLine(blockName, iPort);
end
end
end
|
function [lpim] = generateLaplacianPyramid(img,pyram,levels)
g = ([1, 4, 6, 4, 1])/16;
gaussianpyramid = [];
laplacianpyramid = [];
for l = (1:levels-1)
gaussianpyramid = [gaussianpyramid img];
% LP Filter
filter_0 = convn(img, g);
img_filter = convn(filter_0, g);
img_filter_downsample = img_filter(1:2:end, 1:2:end);
upsample_img = zeros(size(img));
upsample_img(1:2:end, 1:2:end) = img_filter_downsample;
filter_0 = conv2(upsample_img, 2*g,'reflect');
upsample_img_filter = conv2(filter_0, g,'reflect');
laplacian_step = img - upsample_img_filter;
laplacianpyramid = [laplacianpyramid laplacian_step];
img = img_filter_downsample;
end
laplacianpyramid(end) = gaussianpyramid(end);
if pyram == 'lap'
lpim = laplacianpyramid;
elseif pyram == 'gauss'
lpim = gaussianpyramid;
else
error('Error: Unknown pyramid type');
end
end |
%Export data to file
function wwlln_export(data,filename)
%
% Written By: Michael Hutchins
fid=fopen(filename,'wt');
format='%g/%g/%g,%02g:%02g:%09f, % 08.4f, % 09.4f,% 05.1f, %g, %.2f %.2f %g\n';
if size(data,2)~=13
format=sprintf('%%g/%%g/%%g,%%02g:%%02g:%%09f, %% 08.4f, %% 09.4f,%% 05.1f, %%g%s\n',...
repmat(', %.2f',1,size(data,2)-10));
end
for i=1:size(data,1);
fprintf(fid,format,data(i,:));
end
fclose(fid); |
function [onflAuto, additional] = segmentONFLCirc(bscan, Params, rpe, icl, ipl, infl, bv)
% SEGMENTONFLCIRC Segments the ONFL from a BScan. Intended for use on
% circular OCT B-Scans.
%
% ONFLAUTO = segmentINFLAuto(BSCAN)
% ONFLAUTO: Automated segmentation of the ONFL
% ADDITIONAL: May be used for transferring additional information from the
% segmentation. Not recommended to use outside development.
% BSCAN: Unnormed BScan image
% Params: Parameter struct for the automated segmentation
% In this function, the following parameters are currently used:
% CL parameters: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ONFL_SEGMENT_LINESWEETER_INIT_INTERPOLATE: Should be set to pure
% interpolation of wholes
% Region sum ratio parameters: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ONFL_SEGMENT_LINESWEETER_REGRATIO: The region-ratio values used for
% estimating thin/thick regions are also smoothed using the
% linesweeter function.
% ONFL_SEGMENT_REGRATIO_THIN: Threshold for the region-sum ratio. The
% regions above this threshold are assumed to be thick, below thin
% (suggestion: 0.7)
% ONFL_SEGMENT_REGRATIO_THICK: Threshold for the region-sum ratio. The
% regions above this threshold are assumed to be very thick.
% (suggestion: 2.8)
% Denoise parameters: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ONFL_SEGMENT_NOISEESTIMATE_MEDIAN: The 2D median filter values used for
% noise estimateion. (suggestion: [7 1])
% ONFL_SEGMENT_DENOISEPM_SIGMAMULT: Multiplier for the noise estimate.
% noise estimate * sigmamult = sigma for the complex diffusion.
% ONFL_SEGMENT_FINDRETINAEXTREMA_SIGMA_FZ_EXTR4: Before finding the 4
% largest contrast drops in the inner part of the scan, a gaussian
% with this sigma is applied
% ONFL_SEGMENT_FINDRETINAEXTREMA_SIGMA_FZ_EXTRMAX: Before finding the
% largest contrast drop in the inner part of the scan, a gaussian
% with this sigma is applied
% Blood vessel detection parameters - see the findBloodVessels function
% for more details on the parameters. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ONFL_SEGMENT_FINDBLOODVESSELS_THRESHOLD_ALL
% ONFL_SEGMENT_FINDBLOODVESSELS_FREEWIDTH_ALL
% ONFL_SEGMENT_FINDBLOODVESSELS_MULTWIDTH_ALL
% ONFL_SEGMENT_FINDBLOODVESSELS_MULTWIDTHTHRESH_ALL: These four
% parameters are used for detecting accurate blood vessel positions
% ONFL_SEGMENT_FINDBLOODVESSELS_THRESHOLD_EN
% ONFL_SEGMENT_FINDBLOODVESSELS_FREEWIDTH_EN
% ONFL_SEGMENT_FINDBLOODVESSELS_MULTWIDTH_EN
% ONFL_SEGMENT_FINDBLOODVESSELS_MULTWIDTHTHRESH_EN: These parameters are
% used to find blood vessel centers for the spliting of the B-Scan
% into regions (used in the enrgy minimization)
% Energy minimization parameters: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ONFL_SEGMENT_POLYNUMBER: A polynom of this cardinality is fit through
% the initial segmentation and taken as an initialization for the
% energy minimization
% ONFL_SEGMENT_LINESWEETER_FINAL: The resulting segmentation is smoothed
% with this parameters (see linesweeter function)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% RPE: Segmentation of the RPE in OCTSEG line format
% INFL: Segmentation of the INFL in OCTSEG line format
%
% The algorithm (of which this function is a part) is described in
% Markus A. Mayer, Joachim Hornegger, Christian Y. Mardin, Ralf P. Tornow:
% Retinal Nerve Fiber Layer Segmentation on FD-OCT Scans of Normal Subjects
% and Glaucoma Patients, Biomedical Optics Express, Vol. 1, Iss. 5,
% 1358-1383 (2010). Note that modifications have been made to the
% algorithm since the paper publication.
%
% Writen by Markus Mayer, Pattern Recognition Lab, University of
% Erlangen-Nuremberg
%
% First final Version: June 2010
bscan = mirrorCirc(bscan, 'add', Params.ONFLCIRC_SEGMENT_MIRRORWIDTH);
icl = mirrorCirc(icl, 'add', Params.ONFLCIRC_SEGMENT_MIRRORWIDTH);
ipl = mirrorCirc(ipl, 'add', Params.ONFLCIRC_SEGMENT_MIRRORWIDTH);
infl = mirrorCirc(infl, 'add', Params.ONFLCIRC_SEGMENT_MIRRORWIDTH);
bv = mirrorCirc(bv, 'add', Params.ONFLCIRC_SEGMENT_MIRRORWIDTH);
% 1) Normalize intensity values and align the image to the RPE
bscan(bscan > 1) = 0;
bscan = sqrt(bscan);
bscanDSqrt = sqrt(bscan);
% 2) Find blood vessels for segmentation and energy-smooth
idxBV = find(extendBloodVessels(bv, Params.ONFLCIRC_EXTENDBLOODVESSELS_ADDWIDTH, ...
Params.ONFLCIRC_EXTENDBLOODVESSELS_MULTWIDTHTHRESH, ...
Params.ONFLCIRC_EXTENDBLOODVESSELS_MULTWIDTH));
[alignedBScanDSqrt, ~, transformLine] = alignAScans(bscanDSqrt, Params, [icl; round(infl)]);
flatINFL = round(infl - transformLine);
flatIPL = round(ipl - transformLine);
% Interpolate over B-Scans
averageMask = fspecial('average', [3 7]);
alignedBScanDen = imfilter(alignedBScanDSqrt, averageMask, 'symmetric');
idxBVlogic = zeros(1,size(alignedBScanDSqrt, 2), 'uint8') + 1;
idxBVlogic(idxBV) = idxBVlogic(idxBV) - 1;
idxBVlogic(1) = 1;
idxBVlogic(end) = 1;
idxBVlogicInv = zeros(1,size(alignedBScanDSqrt, 2), 'uint8') + 1 - idxBVlogic;
alignedBScanWoBV = alignedBScanDen(:, find(idxBVlogic));
alignedBScanInter = alignedBScanDen;
runner = 1:size(alignedBScanDSqrt, 2);
runnerBV = runner(find(idxBVlogic));
for k = 1:size(alignedBScanDSqrt,1)
alignedBScanInter(k, :) = interp1(runnerBV, alignedBScanWoBV(k,:), runner, 'linear', 0);
end
alignedBScanDSqrt(:, find(idxBVlogicInv)) = alignedBScanInter(:, find(idxBVlogicInv)) ;
% 2) Denoise the image with complex diffusion
noiseStd = estimateNoise(alignedBScanDSqrt, Params);
% Complex diffusion relies on even size. Enlarge the image if needed.
if mod(size(alignedBScanDSqrt,1), 2) == 1
alignedBScanDSqrt = alignedBScanDSqrt(1:end-1, :);
end
Params.DENOISEPM_SIGMA = [(noiseStd * Params.ONFLCIRC_SEGMENT_DENOISEPM_SIGMAMULT) (pi/1000)];
if mod(size(alignedBScanDSqrt,2), 2) == 1
temp = alignedBScanDSqrt(:,1);
alignedBScanDSqrt = alignedBScanDSqrt(:, 2:end);
alignedBScanDen = real(denoisePM(alignedBScanDSqrt, Params, 'complex'));
alignedBScanDen = [temp alignedBScanDen];
else
alignedBScanDen = real(denoisePM(alignedBScanDSqrt, Params, 'complex'));
end
% Find extrema highest Min, 2 highest min sorted by position
extr2 = findRetinaExtrema(alignedBScanDen, Params, 2, 'min pos', ...
[flatINFL + 1; flatIPL - Params.ONFLCIRC_SEGMENT_MINDIST_IPL_ONFL]);
additional(1,:) = flatIPL + transformLine;
% 6) First estimate of the ONFL:
onfl = extr2(2,:);
idx1Miss = find(extr2(1,:) == 0);
idx2Miss = find(extr2(2,:) == 0);
onfl(idx2Miss) = flatINFL(idx2Miss);
onfl= linesweeter(onfl, Params.ONFLCIRC_SEGMENT_LINESWEETER_INIT_INTERPOLATE);
% Remove this line!
additional(2,:) = onfl + transformLine;
% 7) Do energy smoothing
% Heavily blurring the first estimate by median & gaussian filtering.
onfl = linesweeter(onfl, [1 0 0 0 0 0 1; 5 0 0 0 0 0 15; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0]);
onfl = round(onfl);
% Set the positions where there were two extremas found (i.e. the NFL or
% GC/IPL might contain speckle that dow not allow for a good decision, the estimate may
% lie below the actual NFL) to the ILM. Energy smooth will correct for that.
onfl(idx1Miss) = flatINFL(idx1Miss);
diffNFL = onfl - flatINFL;
onfl(diffNFL < 0) = flatINFL(diffNFL < 0);
onflInitialization = onfl;
gaussCompl = fspecial('gaussian', 5 , 1);
smoothedBScan = alignedBScanDen;
smoothedBScan = imfilter(smoothedBScan, gaussCompl, 'symmetric');
smoothedBScan = -smoothedBScan;
smoothedBScan = smoothedBScan ./ (max(max(smoothedBScan)) - min(min(smoothedBScan))) .* 2 - 1;
onfl = energySmooth(smoothedBScan, Params, onflInitialization, idxBV, [flatINFL; flatIPL]);
% Some additional constraints and a final smoothing
onfl(idx2Miss) = flatINFL(idx2Miss); % No extrema found => NFL loss.
onfl(idxBV) = 0;
onfl = linesweeter(onfl, Params.ONFLCIRC_SEGMENT_LINESWEETER_FINAL);
diffNFL = onfl - flatINFL;
onfl(find(diffNFL < 0)) = flatINFL(find(diffNFL < 0));
onflAuto = onfl + transformLine;
onflAuto = mirrorCirc(onflAuto, 'remove', Params.ONFLCIRC_SEGMENT_MIRRORWIDTH);
additional = mirrorCirc(additional, 'remove', Params.ONFLCIRC_SEGMENT_MIRRORWIDTH);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Helper functions:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A simple noise estimate for adapting a denoising filter. It may seem a
% bit weird at first glance, but it delivers appropriate results.
function res = estimateNoise(octimg, Params)
octimg = octimg - mean(mean(octimg));
mimg = medfilt2(octimg, Params.ONFLCIRC_SEGMENT_NOISEESTIMATE_MEDIAN);
octimg = mimg - octimg;
octimg = abs(octimg);
line = reshape(octimg, numel(octimg), 1);
res = std(line);
end |
function r=yink(p,data)
%function r=yink(p,fileinfo)
% YINK - fundamental frequency estimator
% new version (feb 2003)
%
%
%global jj;
%jj=0;
% process signal a chunk at a time
idx=p.range(1)-1;
%totalhops=round((p.range(2)-p.range(1)+1) / p.hop);
totalhops=floor((p.range(2)-p.range(1)-p.wsize) / p.hop);
r1=nan*zeros(1,totalhops);r2=nan*zeros(1,totalhops);
r3=nan*zeros(1,totalhops);r4=nan*zeros(1,totalhops);
%idx2=0+round(p.wsize/2/p.hop);
idx2=0+floor(p.wsize/2/p.hop);
idx22 = idx2;
while (1)
start = idx+1;
stop = idx+p.bufsize;
stop=min(stop, p.range(2));
xx= data(start:stop);
%xx=sf_wave(fileinfo, [start, stop], []);
% if size(xx,1) == 1; xx=xx'; end
%xx=xx(:,1); % first channel if multichannel
[prd,ap0,ap,pwr]=yin_helper(xx,p);
n=size(prd ,2);
if (~n) break; end;
idx=idx+n*p.hop;
r1(idx2+1:idx2+n)= prd;
r2(idx2+1:idx2+n)= ap0;
r3(idx2+1:idx2+n)= ap;
r4(idx2+1:idx2+n)= pwr;
idx2=idx2+n;
end
%Pad the beginning part
if (idx22>0)
r1(1:idx22) = r1(idx22+1:2*idx22);
r2(1:idx22) = r2(idx22+1:2*idx22);
r3(1:idx22) = r3(idx22+1:2*idx22);
r4(1:idx22) = r4(idx22+1:2*idx22);
end
r.r1=r1(1:idx2); % period estimate
r.r2=r2(1:idx2); % gross aperiodicity measure
r.r3=r3(1:idx2); % fine aperiodicity measure
r.r4=r4(1:idx2); % power
%sf_cleanup(fileinfo);
% end of program
% Estimate F0 of a chunk of signal
function [prd,ap0,ap,pwr]=yin_helper(x,p,dd)
smooth=ceil(p.sr/p.lpf);
x=rsmooth(x,smooth); % light low-pass smoothing
x=x(smooth:end-smooth+1);
[m,n]=size(x);
maxlag = ceil(p.sr/p.minf0);
minlag = floor(p.sr/p.maxf0);
mxlg = maxlag+2; % +2 to improve interp near maxlag
hops=floor((m-mxlg-p.wsize)/p.hop);
prd=zeros(1,hops);
ap0=zeros(1,hops);
ap=zeros(1,hops);
pwr=zeros(1,hops);
if hops<1; return; end
% difference function matrix
dd=zeros(floor((m-mxlg-p.hop)/p.hop),mxlg);
if p.shift == 0 % windows shift both ways
lags1=round(mxlg/2) + round((0:mxlg-1)/2);
lags2=round(mxlg/2) - round((1:mxlg)/2);
lags=[lags1; lags2];
elseif p.shift == 1 % one window fixed, other shifts right
lags=[zeros(1,mxlg); 1:mxlg];
elseif p.shift == -1 % one window fixed, other shifts right
lags=[mxlg-1:-1:0; mxlg*ones(1,mxlg)];
else
error (['unexpected shift flag: ', num2str(p.shift)]);
end
rdiff_inplace(x,x,dd,lags,p.hop);
rsum_inplace(dd,round(p.wsize/p.hop));
dd=dd';
[dd,ddx]=minparabolic(dd); % parabolic interpolation near min
cumnorm_inplace(dd);; % cumulative mean-normalize
% first period estimate
%global jj;
for j=1:hops
d=dd(:,j);
if p.relflag
pd=dftoperiod2(d,[minlag,maxlag],p.thresh);
else
pd=dftoperiod(d,[minlag,maxlag],p.thresh);
end
ap0(j)=d(pd+1);
prd(j)=pd;
end
% replace each estimate by best estimate in range
range = 2*round(maxlag/p.hop);
if hops>1; prd=prd(mininrange(ap0,range*ones(1,hops))); end
%prd=prd(mininrange(ap0,prd));
% refine estimate by constraining search to vicinity of best local estimate
margin1=0.6;
margin2=1.8;
for j=1:hops
d=dd(:,j);
dx=ddx(:,j);
pd=prd(j);
lo=floor(pd*margin1); lo=max(minlag,lo);
hi=ceil(pd*margin2); hi=min(maxlag,hi);
pd=dftoperiod(d,[lo,hi],0);
ap0(j)=d(pd+1);
pd=pd+dx(pd+1)+1; % fine tune based on parabolic interpolation
prd(j)=pd;
% power estimates
idx=(j-1)*p.hop;
k=(1:ceil(pd))';
x1=x(k+idx);
x2=k+idx+pd-1;
interp_inplace(x,x2);
x3=x2-x1;
x4=x2+x1;
x1=x1.^2; rsum_inplace(x1,pd);
x3=x3.^2; rsum_inplace(x3,pd);
x4=x4.^2; rsum_inplace(x4,pd);
x1=x1(1)/pd;
x2=x2(1)/pd;
x3=x3(1)/pd;
x4=x4(1)/pd;
% total power
pwr(j)=x1;
% fine aperiodicity
ap(j)=(eps+x3)/(eps+(x3+x4)); % accurate, only for valid min
%ap(j)
%plot(min(1, d)); pause
prd(j)=pd;
end
%cumulative mean-normalize
function y=cumnorm(x)
[m,n]=size(x);
y = cumsum(x);
y = (y)./ (eps+repmat((1:m)',1,n)); % cumulative mean
y = (eps+x) ./ (eps+y);
|
function [U, mu, eigvals] = mypca(x)
mu= mean(x);
x_cent = bsxfun(@minus, x, mean(x));
[U, p, eigvals] = pca(x_cent);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.