diff --git "a/20230446_matlab.jsonl" "b/20230446_matlab.jsonl" new file mode 100644--- /dev/null +++ "b/20230446_matlab.jsonl" @@ -0,0 +1,649 @@ +{"plateform": "github", "repo_name": "CankayaUniversity/ceng-407-408-2017-2018-project-blood-vessel-segmentation-master", "name": "segmentation.m", "ext": ".m", "path": "ceng-407-408-2017-2018-project-blood-vessel-segmentation-master/Project/segmentation.m", "size": 695, "source_encoding": "utf_8", "md5": "8468fbee34ea6573785311ec6c4a67c8", "text": "% Segmentation function.\r\nfunction [ves] = segmentation(path)\r\n% Read image.\r\nim=imread(path);\r\n% Image enhancement & gray scale of a green channel image.\r\nimage = imageEnhancement(im);\r\n% Load network.\r\nload net;\r\n[m,n] = size(image);\r\nves=uint8(zeros(size(image)));\r\n% Classification.\r\nfor i = 1:1:m-(9-1)\r\n for j = 1:1:n-(9-1)\r\n patch=image(i:i+(9-1),j:j+(9-1));\r\n if isBlackSpot(patch)==0\r\n x=net.classify(patch);\r\n if x=='Positive' % if positive, binarize for the center pixel.\r\n \r\n ves((i+(i+(9-1)))/2,(j+(j+(9-1)))/2)=255;\r\n \r\n end\r\n end\r\n end\r\nend\r\n\r\n% Final image 'ves' constructed.\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "UGM-Geofisika/Dispersion_Inversion-master", "name": "main.m", "ext": ".m", "path": "Dispersion_Inversion-master/main.m", "size": 35750, "source_encoding": "utf_8", "md5": "d9dada994aca8aadc9c712bc8898076f", "text": "function varargout = main(varargin)\n% MAIN MATLAB code for main.fig\n% MAIN, by itself, creates a new MAIN or raises the existing\n% singleton*.\n%\n% H = MAIN returns the handle to a new MAIN or the handle to\n% the existing singleton*.\n%\n% MAIN('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in MAIN.M with the given input arguments.\n%\n% MAIN('Property','Value',...) creates a new MAIN or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before main_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to main_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n%\n% Author: Pablo Pizarro @ppizarror.com, 2017.\n%\n% This program is free software; you can redistribute it and/or\n% modify it under the terms of the GNU General Public License\n% as published by the Free Software Foundation; either version 2\n% of the License, or (at your option) any later version.\n%\n% This program is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with this program; if not, write to the Free Software\n% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n%\n% Last Modified by GUIDE v2.5 09-Feb-2017 16:09:04\n%\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @main_OpeningFcn, ...\n 'gui_OutputFcn', @main_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before main is made visible.\nfunction main_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to main (see VARARGIN)\n\n% Choose default command line output for main\nhandles.output = hObject;\n\n% Add bin, and gui to path from folder (recursive)\nPATH_DEPTH = 3;\n\nfor i=1:PATH_DEPTH\n\n try\n path_str = '';\n if i~=1\n for j=1:i-1\n path_str = strcat(path_str, '../');\n end\n end\n path_bin = cd(cd(strcat(path_str, 'bin')));\n path_gui = cd(cd(strcat(path_str, 'gui')));\n addpath(path_bin);\n addpath(path_gui);\n break\n \n catch Exception\n \n % Folders could not be found\n if i==PATH_DEPTH\n fprintf(getReport(Exception));\n error('Error while setting software path.');\n end\n \n end\nend\n\n% Center window\nmovegui(gcf, 'center');\n\n% Import configurations\nconfig;\n\n% Load language strings\nlang = load_lang(lang_id);\n\n% Disable Excel warning\nwarning('off', 'MATLAB:xlswrite:AddSheet');\n\n% Set gui-app config\nsetappdata(handles.root, 'lang', lang);\nsetappdata(handles.root, 'gui_sound', gui_sound_enabled);\nsetappdata(handles.root, 'delete_entry_if_invalid', delete_entry_if_invalid);\n\n% Set inversion config\nsetappdata(handles.root, 'cgf_sigma', inv_sigma);\nsetappdata(handles.root, 'cgf_mu', inv_mu);\nsetappdata(handles.root, 'cgf_maxiter', inv_maxiter);\nsetappdata(handles.root, 'cgf_tolvs', inv_tol_vs);\n\n% Set plot configuration - style\nsetappdata(handles.root, 'plt_disp_labl_fontsize', plt_dispersion_label_fontsize);\nsetappdata(handles.root, 'plt_dispersion_style', plt_dispersion_style);\nsetappdata(handles.root, 'sol_plot_disp_fontsize', solution_plt_dispersion_fontsize);\nsetappdata(handles.root, 'sol_plot_disp_style_exp', solution_plt_dispersion_experimental_style);\nsetappdata(handles.root, 'sol_plot_disp_style_sol', solution_plt_dispersion_solution_style);\nsetappdata(handles.root, 'plt_dispersion_showlegend', plt_dispersion_show_legend);\nsetappdata(handles.root, 'plt_dispersion_solution_showlegend', solution_plt_dispersion_show_legend);\nsetappdata(handles.root, 'sol_plot_shear_showlegend', solution_plt_shear_show_legend);\nsetappdata(handles.root, 'sol_plot_shear_fontsize', solution_plt_shear_fontsize);\nsetappdata(handles.root, 'dispersion_iteration_style', dispersion_iteration_style);\nsetappdata(handles.root, 'dispersion_iteration_fontsize', dispersion_iteration_fontsize);\nsetappdata(handles.root, 'dispersion_iteration_color', dispersion_iteration_color);\nsetappdata(handles.root, 'dispersion_iteration_random_color', dispersion_iteration_random_color);\nsetappdata(handles.root, 'dispersion_iteration_show_legend', dispersion_iteration_show_legend);\nsetappdata(handles.root, 'solution_plt_shear_curve_style', solution_plt_shear_curve_style);\nsetappdata(handles.root, 'dispersion_iteration_linewidth', dispersion_iteration_linewidth);\nsetappdata(handles.root, 'plt_dispersion_linewidth', plt_dispersion_linewidth);\nsetappdata(handles.root, 'solution_plt_dispersion_experimental_linewidth', ...\n solution_plt_dispersion_experimental_linewidth);\nsetappdata(handles.root, 'solution_plt_dispersion_linewidth', ...\n solution_plt_dispersion_linewidth);\nsetappdata(handles.root, 'solution_plot_shear_linewidth', ...\n solution_plot_shear_linewidth);\nsetappdata(handles.root, 'solution_shear_comparision_fontsize', ...\n solution_shear_comparision_fontsize);\nsetappdata(handles.root, 'solution_shear_comparision_shear_curve_linewidth', ...\n solution_shear_comparision_shear_curve_linewidth);\nsetappdata(handles.root, 'solution_shear_comparision_iguess_curve_linewidth', ...\n solution_shear_comparision_iguess_curve_linewidth);\nsetappdata(handles.root, 'solution_shear_comparision_shear_curve_style', ...\n solution_shear_comparision_shear_curve_style);\nsetappdata(handles.root, 'solution_shear_comparision_iguess_curve_style', ...\n solution_shear_comparision_iguess_curve_style);\nsetappdata(handles.root, 'solution_plt_shear_comparision_legend', ...\n solution_plt_shear_comparision_legend);\n\n% Set solution configuration\nsetappdata(handles.root, 'show_dispersion_comparision', show_dispersion_comparision);\nsetappdata(handles.root, 'show_shear_velocity_plot', show_shear_velocity_plot);\nsetappdata(handles.root, 'show_dispersion_iterations', show_dispersion_iterations);\nsetappdata(handles.root, 'show_shear_velocity_comparision', show_shear_velocity_comparision);\n\n% Set GUI Strings from lang\nset_gui_lang(handles, lang);\n\n% Set new file\nnew_file(handles, lang, false);\nsetappdata(handles.root, 'last_opened_folder', '');\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes main wait for user response (see UIRESUME)\n% uiwait(handles.root);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = main_OutputFcn(hObject, eventdata, handles) %#ok<*INUSL>\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --------------------------------------------------------------------\nfunction menu_file_Callback(hObject, eventdata, handles) %#ok<*DEFNU,*INUSD>\n% hObject handle to menu_file (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes during object creation, after setting all properties.\nfunction initial_solution_CreateFcn(hObject, eventdata, handles)\n% hObject handle to initial_solution (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n\n% --------------------------------------------------------------------\nfunction table_menu_Callback(hObject, eventdata, handles)\n% hObject handle to table_menu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction table_add_row_Callback(hObject, eventdata, handles)\n% hObject handle to table_add_row (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nadd_row(handles);\n\n\n% --- Executes when entered data in editable cell(s) in initial_solution.\nfunction initial_solution_CellEditCallback(hObject, eventdata, handles)\n% hObject handle to initial_solution (see GCBO)\n% eventdata structure with the following fields (see MATLAB.UI.CONTROL.TABLE)\n%\tIndices: row and column indices of the cell(s) edited\n%\tPreviousData: previous data for the cell(s) edited\n%\tEditData: string(s) entered by the user\n%\tNewData: EditData or its converted form set on the Data property. Empty if Data was not changed\n%\tError: error string when failed to convert EditData to appropriate value for Data\n% handles structure with handles and user data (see GUIDATA)\nreplace_nan_initbl(handles, getappdata(handles.root, 'lang'));\n\n\n% --------------------------------------------------------------------\nfunction delete_last_row_Callback(hObject, eventdata, handles)\n% hObject handle to delete_last_row (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ndelete_last_row(handles, getappdata(handles.root, 'lang'));\n\n\n% --------------------------------------------------------------------\nfunction table_import_from_excel_Callback(hObject, eventdata, handles)\n% hObject handle to table_import_from_excel (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nimport_initbl_excel(handles, getappdata(handles.root, 'lang'));\n\n\n% --------------------------------------------------------------------\nfunction menu_edition_Callback(hObject, eventdata, handles)\n% hObject handle to menu_edition (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction menu_edition_cleantable_Callback(hObject, eventdata, handles)\n% hObject handle to menu_edition_cleantable (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclear_initialtable(handles, getappdata(handles.root, 'lang'), true);\n\n\n% --------------------------------------------------------------------\nfunction menu_file_new_Callback(hObject, eventdata, handles)\n% hObject handle to menu_file_new (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nnew_file(handles, getappdata(handles.root, 'lang'), true);\n\n\n% --------------------------------------------------------------------\nfunction menu_file_load_Callback(hObject, eventdata, handles)\n% hObject handle to menu_file_load (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nload_project(handles, getappdata(handles.root, 'lang'));\n\n\n% --- Executes during object creation, after setting all properties.\nfunction initial_solution_table_title_CreateFcn(hObject, eventdata, handles)\n% hObject handle to initial_solution_table_title (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n\n% --------------------------------------------------------------------\nfunction menu_help_Callback(hObject, eventdata, handles)\n% hObject handle to menu_help (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction menu_view_help_Callback(hObject, eventdata, handles)\n% hObject handle to menu_view_help (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nmanual;\n\n\n% --------------------------------------------------------------------\nfunction menu_about_Callback(hObject, eventdata, handles)\n% hObject handle to menu_about (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nabout(getappdata(handles.root, 'lang'));\n\n\n% --------------------------------------------------------------------\nfunction menu_file_save_Callback(hObject, eventdata, handles)\n% hObject handle to menu_file_save (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nsave_project(handles, getappdata(handles.root, 'lang'), false);\n\n\n% --------------------------------------------------------------------\nfunction menu_file_save_as_Callback(hObject, eventdata, handles)\n% hObject handle to menu_file_save_as (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nsave_project(handles, getappdata(handles.root, 'lang'), true);\n\n\n% --------------------------------------------------------------------\nfunction menu_file_close_Callback(hObject, eventdata, handles)\n% hObject handle to menu_file_close (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ndoclose = close_app(handles, getappdata(handles.root, 'lang'));\nif doclose\n close all;\nend\n\n\n% --- Executes on button press in btn_opendispersion.\nfunction btn_opendispersion_Callback(hObject, eventdata, handles)\n% hObject handle to btn_opendispersion (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nload_dispersion_file(handles, getappdata(handles.root, 'lang'));\n\n% --------------------------------------------------------------------\nfunction panel_dispersion_file_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to panel_dispersion_file (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on selection change in unit_h.\nfunction unit_h_Callback(hObject, eventdata, handles)\n% hObject handle to unit_h (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns unit_h contents as cell array\n% contents{get(hObject,'Value')} returns selected item from unit_h\n\n\n% --- Executes during object creation, after setting all properties.\nfunction unit_h_CreateFcn(hObject, eventdata, handles)\n% hObject handle to unit_h (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in unit_vsvp.\nfunction unit_vsvp_Callback(hObject, eventdata, handles)\n% hObject handle to unit_vsvp (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns unit_vsvp contents as cell array\n% contents{get(hObject,'Value')} returns selected item from unit_vsvp\n\n\n% --- Executes during object creation, after setting all properties.\nfunction unit_vsvp_CreateFcn(hObject, eventdata, handles)\n% hObject handle to unit_vsvp (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in unit_vr.\nfunction unit_vr_Callback(hObject, eventdata, handles)\n% hObject handle to unit_vr (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns unit_vr contents as cell array\n% contents{get(hObject,'Value')} returns selected item from unit_vr\n\n\n% --- Executes during object creation, after setting all properties.\nfunction unit_vr_CreateFcn(hObject, eventdata, handles)\n% hObject handle to unit_vr (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in unit_rho.\nfunction unit_rho_Callback(hObject, eventdata, handles)\n% hObject handle to unit_rho (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns unit_rho contents as cell array\n% contents{get(hObject,'Value')} returns selected item from unit_rho\n\n\n% --- Executes during object creation, after setting all properties.\nfunction unit_rho_CreateFcn(hObject, eventdata, handles)\n% hObject handle to unit_rho (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on mouse press over axes background.\nfunction plt_dispersion_file_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to plt_dispersion_file (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction disp_plt_viewlarger_Callback(hObject, eventdata, handles)\n% hObject handle to disp_plt_viewlarger (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nplot_large_dispcurv(handles, getappdata(handles.root, 'lang'));\n\n\n% --------------------------------------------------------------------\nfunction dispersion_curve_menu_Callback(hObject, eventdata, handles)\n% hObject handle to dispersion_curve_menu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in start_button.\nfunction start_button_Callback(hObject, eventdata, handles)\n% hObject handle to start_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nstart_inversion(handles, hObject, getappdata(handles.root, 'lang'));\n\n\nfunction param_inv_sigma_Callback(hObject, eventdata, handles)\n% hObject handle to param_inv_sigma (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of param_inv_sigma as text\n% str2double(get(hObject,'String')) returns contents of param_inv_sigma as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction param_inv_sigma_CreateFcn(hObject, eventdata, handles)\n% hObject handle to param_inv_sigma (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\nfunction param_inv_mu_Callback(hObject, eventdata, handles)\n% hObject handle to param_inv_mu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of param_inv_mu as text\n% str2double(get(hObject,'String')) returns contents of param_inv_mu as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction param_inv_mu_CreateFcn(hObject, eventdata, handles)\n% hObject handle to param_inv_mu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\nfunction param_maxiter_Callback(hObject, eventdata, handles)\n% hObject handle to param_maxiter (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of param_maxiter as text\n% str2double(get(hObject,'String')) returns contents of param_maxiter as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction param_maxiter_CreateFcn(hObject, eventdata, handles)\n% hObject handle to param_maxiter (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\nfunction param_tolvs_Callback(hObject, eventdata, handles)\n% hObject handle to param_tolvs (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of param_tolvs as text\n% str2double(get(hObject,'String')) returns contents of param_tolvs as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction param_tolvs_CreateFcn(hObject, eventdata, handles)\n% hObject handle to param_tolvs (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in view_sol_plot.\nfunction view_sol_plot_Callback(hObject, eventdata, handles)\n% hObject handle to view_sol_plot (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nshow_plots(handles, getappdata(handles.root, 'lang'));\n\n\n% --- Executes on button press in export_results.\nfunction export_results_Callback(hObject, eventdata, handles)\n% hObject handle to export_results (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nexport_results(handles, hObject, getappdata(handles.root, 'lang'));\n\n\n% --- Executes on key press with focus on param_inv_sigma and none of its controls.\nfunction param_inv_sigma_KeyPressFcn(hObject, eventdata, handles)\n% hObject handle to param_inv_sigma (see GCBO)\n% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)\n%\tKey: name of the key that was pressed, in lower case\n%\tCharacter: character interpretation of the key(s) that was pressed\n%\tModifier: name(s) of the modifier key(s) (i.e., control, shift) pressed\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- If Enable == 'on', executes on mouse press in 5 pixel border.\n% --- Otherwise, executes on mouse press in 5 pixel border or over param_inv_sigma.\nfunction param_inv_sigma_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to param_inv_sigma (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% check_inv_parameters(handles, getappdata(handles.root, 'lang'), true);\n\n\n% --- If Enable == 'on', executes on mouse press in 5 pixel border.\n% --- Otherwise, executes on mouse press in 5 pixel border or over param_inv_mu.\nfunction param_inv_mu_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to param_inv_mu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on key press with focus on param_inv_mu and none of its controls.\nfunction param_inv_mu_KeyPressFcn(hObject, eventdata, handles)\n% hObject handle to param_inv_mu (see GCBO)\n% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)\n%\tKey: name of the key that was pressed, in lower case\n%\tCharacter: character interpretation of the key(s) that was pressed\n%\tModifier: name(s) of the modifier key(s) (i.e., control, shift) pressed\n% handles structure with handles and user data (see GUIDATA)\n% check_inv_parameters(handles, getappdata(handles.root, 'lang'), true);\n\n\n% --- If Enable == 'on', executes on mouse press in 5 pixel border.\n% --- Otherwise, executes on mouse press in 5 pixel border or over param_maxiter.\nfunction param_maxiter_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to param_maxiter (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on key press with focus on param_maxiter and none of its controls.\nfunction param_maxiter_KeyPressFcn(hObject, eventdata, handles)\n% hObject handle to param_maxiter (see GCBO)\n% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)\n%\tKey: name of the key that was pressed, in lower case\n%\tCharacter: character interpretation of the key(s) that was pressed\n%\tModifier: name(s) of the modifier key(s) (i.e., control, shift) pressed\n% handles structure with handles and user data (see GUIDATA)\n% check_inv_parameters(handles, getappdata(handles.root, 'lang'), true);\n\n\n% --- If Enable == 'on', executes on mouse press in 5 pixel border.\n% --- Otherwise, executes on mouse press in 5 pixel border or over param_tolvs.\nfunction param_tolvs_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to param_tolvs (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on key press with focus on param_tolvs and none of its controls.\nfunction param_tolvs_KeyPressFcn(hObject, eventdata, handles)\n% hObject handle to param_tolvs (see GCBO)\n% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)\n%\tKey: name of the key that was pressed, in lower case\n%\tCharacter: character interpretation of the key(s) that was pressed\n%\tModifier: name(s) of the modifier key(s) (i.e., control, shift) pressed\n% handles structure with handles and user data (see GUIDATA)\n% check_inv_parameters(handles, getappdata(handles.root, 'lang'), true);\n\n\n% --- If Enable == 'on', executes on mouse press in 5 pixel border.\n% --- Otherwise, executes on mouse press in 5 pixel border or over btn_opendispersion.\nfunction btn_opendispersion_ButtonDownFcn(hObject, eventdata, handles)\n% hObject handle to btn_opendispersion (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on key press with focus on btn_opendispersion and none of its controls.\nfunction btn_opendispersion_KeyPressFcn(hObject, eventdata, handles)\n% hObject handle to btn_opendispersion (see GCBO)\n% eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL)\n%\tKey: name of the key that was pressed, in lower case\n%\tCharacter: character interpretation of the key(s) that was pressed\n%\tModifier: name(s) of the modifier key(s) (i.e., control, shift) pressed\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes when selected cell(s) is changed in initial_solution.\nfunction initial_solution_CellSelectionCallback(hObject, eventdata, handles)\n% hObject handle to initial_solution (see GCBO)\n% eventdata structure with the following fields (see MATLAB.UI.CONTROL.TABLE)\n%\tIndices: row and column indices of the cell(s) currently selecteds\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction menu_import_table_from_excel_Callback(hObject, eventdata, handles)\n% hObject handle to menu_import_table_from_excel (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nimport_initbl_excel(handles, getappdata(handles.root, 'lang'));\n\n\n% --------------------------------------------------------------------\nfunction menu_add_row_table_Callback(hObject, eventdata, handles)\n% hObject handle to menu_add_row_table (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nadd_row(handles);\n\n\n% --------------------------------------------------------------------\nfunction menu_delete_row_table_Callback(hObject, eventdata, handles)\n% hObject handle to menu_delete_row_table (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ndelete_last_row(handles, getappdata(handles.root, 'lang'));\n\n\n% --------------------------------------------------------------------\nfunction menu_edit_import_Callback(hObject, eventdata, handles)\n% hObject handle to menu_edit_import (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction menu_import_dispersion_file_Callback(hObject, eventdata, handles)\n% hObject handle to menu_import_dispersion_file (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nload_dispersion_file(handles, getappdata(handles.root, 'lang'));\n\n\n% --------------------------------------------------------------------\nfunction menu_clean_initial_invparam_Callback(hObject, eventdata, handles)\n% hObject handle to menu_clean_initial_invparam (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclear_invparam(handles);\n\n\n% --------------------------------------------------------------------\nfunction menu_preferences_Callback(hObject, eventdata, handles)\n% hObject handle to menu_preferences (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction menu_cfg_app_Callback(hObject, eventdata, handles)\n% hObject handle to menu_cfg_app (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get lang variable\nlang = getappdata(handles.root, 'lang');\n\n% Check if gui dir exist, if not a message error is displayed\nif exist('gui', 'dir')\n cfg_app(lang, 'main', handles);\nelse\n disp_error(handles, lang, 128);\nend\n\n\n% --------------------------------------------------------------------\nfunction menu_cfg_plot_Callback(hObject, eventdata, handles)\n% hObject handle to menu_cfg_plot (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --------------------------------------------------------------------\nfunction menu_cfg_inversion_Callback(hObject, eventdata, handles)\n% hObject handle to menu_cfg_inversion (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get lang variable\nlang = getappdata(handles.root, 'lang');\n\n% Check if gui dir exist, if not a message error is displayed\nif exist('gui', 'dir')\n cfg_inv(lang, 'main', handles.root);\nelse\n disp_error(handles, lang, 128);\nend\n\n\n% --------------------------------------------------------------------\nfunction menu_cfg_solution_Callback(hObject, eventdata, handles)\n% hObject handle to menu_cfg_solution (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get lang variable\nlang = getappdata(handles.root, 'lang');\n\n% Check if gui dir exist, if not a message error is displayed\nif exist('gui', 'dir')\n cfg_sol(lang, 'main', handles.root);\nelse\n disp_error(handles, lang, 128);\nend\n\n\n% --------------------------------------------------------------------\nfunction dispersion_plt_viewtable_Callback(hObject, eventdata, handles)\n% hObject handle to dispersion_plt_viewtable (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get lang variable\nlang = getappdata(handles.root, 'lang');\n\nif getappdata(handles.root, 'dispersion_ok')\n view_disp_table(lang, 'main', handles.root);\nend\n"} +{"plateform": "github", "repo_name": "UGM-Geofisika/Dispersion_Inversion-master", "name": "cfg_sol.m", "ext": ".m", "path": "Dispersion_Inversion-master/gui/cfg_sol.m", "size": 9758, "source_encoding": "utf_8", "md5": "c33866390ebc4a79a24b23945faa1e47", "text": "function varargout = cfg_sol(varargin)\n% ROOT MATLAB code for root.fig\n% ROOT, by itself, creates a new ROOT or raises the existing\n% singleton*.\n%\n% H = ROOT returns the handle to a new ROOT or the handle to\n% the existing singleton*.\n%\n% ROOT('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in ROOT.M with the given input arguments.\n%\n% ROOT('Property','Value',...) creates a new ROOT or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before cfg_sol_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to cfg_sol_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help root\n\n% Last Modified by GUIDE v2.5 27-Jan-2017 20:27:57\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @cfg_sol_OpeningFcn, ...\n 'gui_OutputFcn', @cfg_sol_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before root is made visible.\nfunction cfg_sol_OpeningFcn(hObject, eventdata, handles, varargin) %#ok<*INUSL>\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to root (see VARARGIN)\n\n% Check if application is opened from main\nif ~ (length(varargin)==3 && strcmp(varargin{2}, 'main'))\n close;\nend\n\n% Set main variables\nlang = varargin{1}; %#ok<*NASGU>\nsetappdata(handles.root, 'lang', lang);\nsetappdata(handles.root, 'main_handles', varargin{3});\n\n% Set app strings\nset(handles.root, 'Name', lang{129});\nset_lang_string(handles.btn_save, lang{20}, 'string');\nset_lang_string(handles.btn_close, lang{147}, 'string');\nset_lang_string(handles.text_comparision, lang{132}, 'string');\nset_lang_string(handles.text_shear, lang{133}, 'string');\nset_lang_string(handles.text_iteration, lang{134}, 'string');\nset_lang_string(handles.text_shear_comparision, lang{140}, 'string');\n\n% Import config\nconfig_solution;\nconfig_app;\n\n% Set config values\nif show_dispersion_comparision\n set(handles.cfg_comparision, 'Value', 1.0);\nend\nif show_shear_velocity_plot\n set(handles.cfg_shear, 'Value', 1.0);\nend\nif show_dispersion_iterations\n set(handles.cfg_iteration, 'Value', 1.0);\nend\nif show_shear_velocity_comparision\n set(handles.cfg_comparision_shear, 'Value', 1.0);\nend\n\n% Save configs\nsetappdata(handles.root, 'gui_sound', gui_sound_enabled);\n\n% Center window\nmovegui(gcf, 'center');\n\n% Choose default command line output for root\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes root wait for user response (see UIRESUME)\n% uiwait(handles.root);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = cfg_sol_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on selection change in conf_lang.\nfunction conf_lang_Callback(hObject, eventdata, handles)\n% hObject handle to conf_lang (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns conf_lang contents as cell array\n% contents{get(hObject,'Value')} returns selected item from conf_lang\n\n\n% --- Executes during object creation, after setting all properties.\nfunction conf_lang_CreateFcn(hObject, eventdata, handles) %#ok<*INUSD,*DEFNU>\n% hObject handle to conf_lang (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in btn_save.\nfunction btn_save_Callback(hObject, eventdata, handles)\n% hObject handle to btn_save (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get lang\nlang = getappdata(handles.root, 'lang');\n\n% Get original handles\nroot_handles = getappdata(handles.root, 'main_handles');\n\n% Import config\nconfig_solution;\n\n% Get configs\ncomparision = get(handles.cfg_comparision, 'Value');\nshear = get(handles.cfg_shear, 'Value');\niteration = get(handles.cfg_iteration, 'Value');\nshear_comparision = get(handles.cfg_comparision_shear, 'Value');\n\n% Check if something changed\nif (comparision == show_dispersion_comparision) && (shear == show_shear_velocity_plot) && ...\n (show_dispersion_iterations == iteration) && (shear_comparision == show_shear_velocity_comparision)\nelse\n \n % Set config strings\n if comparision\n str_comparision = 'show_dispersion_comparision = true;';\n else\n str_comparision = 'show_dispersion_comparision = false;';\n end\n if shear\n str_shear = 'show_shear_velocity_plot = true;';\n else\n str_shear = 'show_shear_velocity_plot = false;';\n end\n if iteration\n str_iteration = 'show_dispersion_iterations = true;';\n else\n str_iteration = 'show_dispersion_iterations = false;';\n end\n if shear_comparision\n str_shear_comparision = 'show_shear_velocity_comparision = true;';\n else\n str_shear_comparision = 'show_shear_velocity_comparision = false;';\n end\n\n % Save config file\n conf_file = fopen('gui/config_solution.m', 'wt');\n write_conf_header(conf_file, ' SOLUTION CONFIGURATION', ' Configures solution behaviour.');\n fprintf(conf_file, '%s\\n', '% Show Calculated vs Experimental dispersion curve');\n fprintf(conf_file, '%s\\n\\n', str_comparision);\n fprintf(conf_file, '%s\\n', '% Show Shear velocity on depth plot');\n fprintf(conf_file, '%s\\n\\n', str_shear);\n fprintf(conf_file, '%s\\n', '% Show Calculated dispersion - iteration changes');\n fprintf(conf_file, '%s\\n\\n', str_iteration);\n fprintf(conf_file, '%s\\n', '% Show shear velocity comparision');\n fprintf(conf_file, '%s\\n\\n', str_shear_comparision);\n fclose(conf_file);\n \n % Set changes\n setappdata(root_handles, 'show_dispersion_comparision', comparision);\n setappdata(root_handles, 'show_shear_velocity_plot', shear);\n setappdata(root_handles, 'show_dispersion_iterations', iteration);\n setappdata(root_handles, 'show_shear_velocity_comparision', shear_comparision);\n \nend\nclose;\n\n\n% --- Executes on button press in btn_close.\nfunction btn_close_Callback(hObject, eventdata, handles)\n% hObject handle to btn_close (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose;\n\n\n% --- Executes on button press in cfg_shear.\nfunction cfg_shear_Callback(hObject, eventdata, handles)\n% hObject handle to cfg_shear (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of cfg_shear\n\n\n% --- Executes on button press in cfg_delete_inv_entry.\nfunction cfg_delete_inv_entry_Callback(hObject, eventdata, handles)\n% hObject handle to cfg_delete_inv_entry (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of cfg_delete_inv_entry\n\n\n% --- Executes on button press in cfg_comparision.\nfunction cfg_comparision_Callback(hObject, eventdata, handles)\n% hObject handle to cfg_comparision (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of cfg_comparision\n\n\n% --- Executes on button press in cfg_iteration.\nfunction cfg_iteration_Callback(hObject, eventdata, handles)\n% hObject handle to cfg_iteration (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of cfg_iteration\n\n\n% --- Executes on button press in cfg_comparision_shear.\nfunction cfg_comparision_shear_Callback(hObject, eventdata, handles)\n% hObject handle to cfg_comparision_shear (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of cfg_comparision_shear\n\n"} +{"plateform": "github", "repo_name": "UGM-Geofisika/Dispersion_Inversion-master", "name": "view_disp_table.m", "ext": ".m", "path": "Dispersion_Inversion-master/gui/view_disp_table.m", "size": 3934, "source_encoding": "utf_8", "md5": "d795f65e03e1977c37b975f14f367207", "text": "function varargout = view_disp_table(varargin)\n% VIEW_DISPERSION_TABLE MATLAB code for view_disp_table.fig\n% VIEW_DISPERSION_TABLE, by itself, creates a new VIEW_DISPERSION_TABLE or raises the existing\n% singleton*.\n%\n% H = VIEW_DISPERSION_TABLE returns the handle to a new VIEW_DISPERSION_TABLE or the handle to\n% the existing singleton*.\n%\n% VIEW_DISPERSION_TABLE('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in VIEW_DISPERSION_TABLE.M with the given input arguments.\n%\n% VIEW_DISPERSION_TABLE('Property','Value',...) creates a new VIEW_DISPERSION_TABLE or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before view_dispersion_table_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to view_dispersion_table_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help view_dispersion_table\n\n% Last Modified by GUIDE v2.5 09-Feb-2017 16:24:00\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @view_dispersion_table_OpeningFcn, ...\n 'gui_OutputFcn', @view_dispersion_table_OutputFcn, ...\n 'gui_LayoutFcn', [], ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before view_dispersion_table is made visible.\nfunction view_dispersion_table_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to view_dispersion_table (see VARARGIN)\n\n% Choose default command line output for view_dispersion_table\nhandles.output = hObject;\n\n% Check if application is opened from main\nif ~(length(varargin) == 3 && strcmp(varargin{2}, 'main'))\n close;\nend\n\n% Set main variables\nlang = varargin{1}; %#ok<*NASGU>\nsetappdata(handles.root, 'lang', lang);\nsetappdata(handles.root, 'main_handles', varargin{3});\n\n% Set app lang\nset(handles.root, 'Name', lang{146});\n\n% Set table\nfreq = getappdata(varargin{3}, 'disp_freq');\nvrexp = getappdata(varargin{3}, 'disp_vrexp');\n[nCols, ~] = size(vrexp);\n\n% If data exists\nif nCols ~= 0\n % Create new cell structure\n tabl = cell(nCols, 2);\n tabl_nom = cell(nCols, 1);\n \n % Copy data to new cell structures\n for i = 1:nCols\n tabl{i, 1} = freq(i);\n tabl{i, 2} = vrexp(i);\n tabl_nom{i} = strcat('f', num2str(i));\n end\n \n % Store data to table object\n set(handles.table, 'Data', tabl);\n set(handles.table, 'RowName', tabl_nom);\nelse\n close;\nend\n\n% Center window\nmovegui(gcf, 'center');\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes view_dispersion_table wait for user response (see UIRESUME)\n% uiwait(handles.root);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = view_dispersion_table_OutputFcn(hObject, eventdata, handles) %#ok<*INUSL>\n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n"} +{"plateform": "github", "repo_name": "UGM-Geofisika/Dispersion_Inversion-master", "name": "manual.m", "ext": ".m", "path": "Dispersion_Inversion-master/gui/manual.m", "size": 2812, "source_encoding": "utf_8", "md5": "547b164df037a6ccb4ebc0699cc92fd3", "text": "function varargout = manual(varargin)\n% MANUAL MATLAB code for manual.fig\n% MANUAL, by itself, creates a new MANUAL or raises the existing\n% singleton*.\n%\n% H = MANUAL returns the handle to a new MANUAL or the handle to\n% the existing singleton*.\n%\n% MANUAL('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in MANUAL.M with the given input arguments.\n%\n% MANUAL('Property','Value',...) creates a new MANUAL or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before manual_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to manual_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help manual\n\n% Last Modified by GUIDE v2.5 26-Jan-2017 09:57:58\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @manual_OpeningFcn, ...\n 'gui_OutputFcn', @manual_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before manual is made visible.\nfunction manual_OpeningFcn(hObject, eventdata, handles, varargin) %#ok<*INUSL>\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to manual (see VARARGIN)\n\n% Choose default command line output for manual\nhandles.output = hObject;\n\n% Center window\nmovegui(gcf, 'center');\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes manual wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = manual_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n"} +{"plateform": "github", "repo_name": "UGM-Geofisika/Dispersion_Inversion-master", "name": "cfg_inv.m", "ext": ".m", "path": "Dispersion_Inversion-master/gui/cfg_inv.m", "size": 12746, "source_encoding": "utf_8", "md5": "5d47aac8bf783746377d2552555b7bec", "text": "function varargout = cfg_inv(varargin)\n% ROOT MATLAB code for root.fig\n% ROOT, by itself, creates a new ROOT or raises the existing\n% singleton*.\n%\n% H = ROOT returns the handle to a new ROOT or the handle to\n% the existing singleton*.\n%\n% ROOT('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in ROOT.M with the given input arguments.\n%\n% ROOT('Property','Value',...) creates a new ROOT or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before cfg_inv_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to cfg_inv_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help root\n\n% Last Modified by GUIDE v2.5 27-Jan-2017 19:50:35\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @cfg_inv_OpeningFcn, ...\n 'gui_OutputFcn', @cfg_inv_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before root is made visible.\nfunction cfg_inv_OpeningFcn(hObject, eventdata, handles, varargin) %#ok<*INUSL>\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to root (see VARARGIN)\n\n% Check if application is opened from main\nif ~ (length(varargin)==3 && strcmp(varargin{2}, 'main'))\n close;\nend\n\n% Set main variables\nlang = varargin{1}; %#ok<*NASGU>\nsetappdata(handles.root, 'lang', lang);\nsetappdata(handles.root, 'main_handles', varargin{3});\n\n% Set app strings\nset(handles.root, 'Name', lang{130});\nset(handles.panel_initialparams, 'Title', lang{135});\nset_lang_string(handles.btn_save, lang{20}, 'string');\nset_lang_string(handles.btn_close, lang{147}, 'string');\nset(handles.text_mu, 'String', lang{136});\nset(handles.text_sigma, 'String', lang{137});\nset(handles.text_maxiter, 'String', lang{138});\nset(handles.text_tolvs, 'String', lang{139});\n\n% Import config\nconfig_app;\nconfig_inverse;\n\n% Save configs\nsetappdata(handles.root, 'delete_entry_if_invalid', delete_entry_if_invalid);\nsetappdata(handles.root, 'gui_sound', gui_sound_enabled);\n\n% Set initial configuration\nset(handles.param_inv_mu, 'String', inv_mu);\nset(handles.param_inv_sigma, 'String', inv_sigma);\nset(handles.param_maxiter, 'String', inv_maxiter);\nset(handles.param_tolvs, 'String', inv_tol_vs);\n\n% Center window\nmovegui(gcf, 'center');\n\n% Choose default command line output for root\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes root wait for user response (see UIRESUME)\n% uiwait(handles.root);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = cfg_inv_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on selection change in conf_lang.\nfunction conf_lang_Callback(hObject, eventdata, handles)\n% hObject handle to conf_lang (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns conf_lang contents as cell array\n% contents{get(hObject,'Value')} returns selected item from conf_lang\n\n\n% --- Executes during object creation, after setting all properties.\nfunction conf_lang_CreateFcn(hObject, eventdata, handles) %#ok<*INUSD,*DEFNU>\n% hObject handle to conf_lang (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in btn_save.\nfunction btn_save_Callback(hObject, eventdata, handles)\n% hObject handle to btn_save (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get lang\nlang = getappdata(handles.root, 'lang');\n\n% Get original handles\nroot_handles = getappdata(handles.root, 'main_handles');\n\n% Import config\nconfig_inverse;\n\n% Check entry status\nstatus = check_inv_parameters(handles, lang, true);\nif status\n sigma = get(handles.param_inv_sigma, 'string');\n mu = get(handles.param_inv_mu, 'string');\n maxiter = get(handles.param_maxiter, 'string');\n tol_vs = get(handles.param_tolvs, 'string');\nelse\n return\nend\n\n% Check if something changed\nif (str2double(sigma) == inv_sigma) && (str2double(maxiter) == inv_maxiter) && ...\n (str2double(mu) == inv_mu) && (inv_tol_vs == str2double(tol_vs))\nelse\n \n % Create strings\n str_maxiter = sprintf('inv_maxiter = %s;', maxiter);\n str_mu = sprintf('inv_mu = %s;', mu);\n str_sigma = sprintf('inv_sigma = %s;', sigma);\n str_tolvs = sprintf('inv_tol_vs = %s;', tol_vs);\n\n % Save config file\n conf_file = fopen('gui/config_inverse.m', 'wt');\n write_conf_header(conf_file, ' INVERSE MATLAB CONFIGURATION', ' Set configurations used by mat_inverse libraries.');\n fprintf(conf_file, '%s\\n', '% Maximum number of iterations, used by mat_inverse');\n fprintf(conf_file, '%s\\n\\n', str_maxiter);\n fprintf(conf_file, '%s\\n', '% Mu coefficient, mat_inverse');\n fprintf(conf_file, '%s\\n\\n', str_mu);\n fprintf(conf_file, '%s\\n', '% Vs tolerance error, mat_inverse');\n fprintf(conf_file, '%s\\n\\n', str_tolvs);\n fprintf(conf_file, '%s\\n', '% Sigma, mat_inverse');\n fprintf(conf_file, '%s\\n\\n', str_sigma);\n fclose(conf_file);\n \n % Set inversion config\n sigma = str2double(sigma);\n mu = str2double(mu);\n maxiter = str2double(maxiter);\n tol_vs = str2double(tol_vs);\n setappdata(root_handles, 'cgf_sigma', sigma);\n setappdata(root_handles, 'cgf_mu', mu);\n setappdata(root_handles, 'cgf_maxiter', maxiter);\n setappdata(root_handles, 'cgf_tolvs', tol_vs);\n \nend\nclose;\n\n\n% --- Executes on button press in btn_close.\nfunction btn_close_Callback(hObject, eventdata, handles)\n% hObject handle to btn_close (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose;\n\n\n% --- Executes on button press in cfg_shear.\nfunction cfg_shear_Callback(hObject, eventdata, handles)\n% hObject handle to cfg_shear (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of cfg_shear\n\n\n% --- Executes on button press in cfg_delete_inv_entry.\nfunction cfg_delete_inv_entry_Callback(hObject, eventdata, handles)\n% hObject handle to cfg_delete_inv_entry (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of cfg_delete_inv_entry\n\n\n% --- Executes on button press in cfg_comparision.\nfunction cfg_comparision_Callback(hObject, eventdata, handles)\n% hObject handle to cfg_comparision (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of cfg_comparision\n\n\n% --- Executes on button press in cfg_iteration.\nfunction cfg_iteration_Callback(hObject, eventdata, handles)\n% hObject handle to cfg_iteration (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of cfg_iteration\n\n\nfunction param_inv_mu_Callback(hObject, eventdata, handles)\n% hObject handle to param_inv_mu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of param_inv_mu as text\n% str2double(get(hObject,'String')) returns contents of param_inv_mu as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction param_inv_mu_CreateFcn(hObject, eventdata, handles)\n% hObject handle to param_inv_mu (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\nfunction param_inv_sigma_Callback(hObject, eventdata, handles)\n% hObject handle to param_inv_sigma (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of param_inv_sigma as text\n% str2double(get(hObject,'String')) returns contents of param_inv_sigma as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction param_inv_sigma_CreateFcn(hObject, eventdata, handles)\n% hObject handle to param_inv_sigma (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\nfunction param_maxiter_Callback(hObject, eventdata, handles)\n% hObject handle to param_maxiter (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of param_maxiter as text\n% str2double(get(hObject,'String')) returns contents of param_maxiter as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction param_maxiter_CreateFcn(hObject, eventdata, handles)\n% hObject handle to param_maxiter (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\nfunction param_tolvs_Callback(hObject, eventdata, handles)\n% hObject handle to param_tolvs (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of param_tolvs as text\n% str2double(get(hObject,'String')) returns contents of param_tolvs as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction param_tolvs_CreateFcn(hObject, eventdata, handles)\n% hObject handle to param_tolvs (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n"} +{"plateform": "github", "repo_name": "UGM-Geofisika/Dispersion_Inversion-master", "name": "mat_inverse.m", "ext": ".m", "path": "Dispersion_Inversion-master/bin/mat_inverse.m", "size": 2755, "source_encoding": "utf_8", "md5": "ecba5e9d7c128ae9a9c8c0df5527cdcd", "text": "function [niter, vr_iter, vp_iter, vs_iter, dns_iter] = mat_inverse(freq, vr_exp, ...\n sigma, thk, vp, vs, dns, maxiter, mu, tol_vs, gui, object, msg)\n% input:\n% 1. dispersion curve\n% freq, vr_exp, sigma\n% 2. initial model\n% thk, vp, vs, dns\n% 3. parameters control the inversion\n% maxiter, mu, tol_vs (change in vs)\n% 4. GUI parameters\n% gui (true/false), object, label, msg (message to show, as %d/%d)\n% Modification history:\n% 01/19/2017: Pablo Pizarro (UChile)\n% (1) Deleted files related to Love wave\n% 01/20/2017: Pablo Pizarro (UChile)\n% (1) Add GUI support\n% (2) Iteration number is displayed on GUI\n% (3) Some statuses are displayed on GUI\n\n% Number of layers\nnl = length(thk);\n\n% Weight matrix\nw = diag(1./sigma);\n\n% Second derivative\ndelta = curv(nl, nl+1);\nL = delta;\nrms = zeros(maxiter, 1);\n\n% Initialize intial guess\nm0 = vs;\nvp0 = vp;\nvs0 = vs;\ndns0 = dns;\n\n% Initialize interation variables\nvp_iter = zeros(nl+1, maxiter);\nvs_iter = zeros(nl+1, maxiter);\ndns_iter = zeros(nl+1, maxiter);\nvr_iter = zeros(length(freq), maxiter);\n\n% Check if gui parameters is defined\nif ~exist('gui', 'var')\n gui = false;\nend\n\nfor i = 1:maxiter\n \n % If GUI\n if gui\n pause(0.01);\n set(object, 'string', sprintf(msg, i, maxiter));\n end\n \n % Calculate theoretical phase velocity and partial derivatives\n % warning: presently the code only handle 1 type of dispersion!\n [vr, dvrvs, ~] = mat_disperse(thk, dns0, vp0, vs0, freq);\n jac = real(squeeze(dvrvs)); % jac = [real(squeeze(dvrvs)) real(squeeze(dvrrho))];\n \n % Calculate the rms error\n error = w * (vr - vr_exp);\n rms(i) = sqrt(mean(error .^ 2));\n \n % Least square inversion\n wjac = w * jac;\n \n b = w * (vr_exp - vr + jac * m0);\n m1 = (wjac' * wjac + mu ^ 2 * (L' * L)) \\ (wjac' * b);\n \n % Evaluate new model\n vs1 = m1(1:nl+1);\n vp1 = vp;\n dns1 = dns; % dns1 = m1(nl+2:nl+2+nl);\n vr = mat_disperse(thk, dns1, vp1, vs1, freq);\n error1 = w * (vr - vr_exp);\n rms1 = sqrt(mean(error1 .^ 2));\n \n % Store the models\n vp_iter(:, i) = vp1;\n vs_iter(:, i) = vs1;\n dns_iter(:, i) = dns1;\n vr_iter(:, i) = vr(:);\n \n % Check for convergence, only check vs ?\n diff_vs = vs1 - vs0;\n rms_vs_change = sqrt(mean(diff_vs .^ 2));\n \n if rms_vs_change < tol_vs || rms1 <= 1\n break\n end\n \n m0 = m1;\n dns0 = dns1;\n vp0 = vp1;\n vs0 = vs1;\nend\nniter = i;\nend\n\n% Curvature matrix for regularization\nfunction delta = curv(m, ~)\ndelta = diag(ones(1, m), 0) + diag(-2*ones(1, m-1), 1) + diag(ones(1, m-2), 2);\ntmp = zeros(m, 1);\ntmp(m) = - 1;\ntmp(m - 1) = 1;\ndelta = [delta, tmp];\nend"} +{"plateform": "github", "repo_name": "foss-for-synopsys-dwc-arc-processors/synopsys-caffe-main", "name": "classification_demo.m", "ext": ".m", "path": "synopsys-caffe-main/matlab/demo/classification_demo.m", "size": 5466, "source_encoding": "utf_8", "md5": "45745fb7cfe37ef723c307dfa06f1b97", "text": "function [scores, maxlabel] = classification_demo(im, use_gpu)\n% [scores, maxlabel] = classification_demo(im, use_gpu)\n%\n% Image classification demo using BVLC CaffeNet.\n%\n% IMPORTANT: before you run this demo, you should download BVLC CaffeNet\n% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)\n%\n% ****************************************************************************\n% For detailed documentation and usage on Caffe's Matlab interface, please\n% refer to the Caffe Interface Tutorial at\n% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab\n% ****************************************************************************\n%\n% input\n% im color image as uint8 HxWx3\n% use_gpu 1 to use the GPU, 0 to use the CPU\n%\n% output\n% scores 1000-dimensional ILSVRC score vector\n% maxlabel the label of the highest score\n%\n% You may need to do the following before you start matlab:\n% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64\n% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6\n% Or the equivalent based on where things are installed on your system\n% and what versions are installed.\n%\n% Usage:\n% im = imread('../../examples/images/cat.jpg');\n% scores = classification_demo(im, 1);\n% [score, class] = max(scores);\n% Five things to be aware of:\n% caffe uses row-major order\n% matlab uses column-major order\n% caffe uses BGR color channel order\n% matlab uses RGB color channel order\n% images need to have the data mean subtracted\n\n% Data coming in from matlab needs to be in the order\n% [width, height, channels, images]\n% where width is the fastest dimension.\n% Here is the rough matlab code for putting image data into the correct\n% format in W x H x C with BGR channels:\n% % permute channels from RGB to BGR\n% im_data = im(:, :, [3, 2, 1]);\n% % flip width and height to make width the fastest dimension\n% im_data = permute(im_data, [2, 1, 3]);\n% % convert from uint8 to single\n% im_data = single(im_data);\n% % reshape to a fixed size (e.g., 227x227).\n% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');\n% % subtract mean_data (already in W x H x C with BGR channels)\n% im_data = im_data - mean_data;\n\n% If you have multiple images, cat them with cat(4, ...)\n\n% Add caffe/matlab to your Matlab search PATH in order to use matcaffe\nif exist('../+caffe', 'dir')\n addpath('..');\nelse\n error('Please run this demo from caffe/matlab/demo');\nend\n\n% Set caffe mode\nif exist('use_gpu', 'var') && use_gpu\n caffe.set_mode_gpu();\n gpu_id = 0; % we will use the first gpu in this demo\n caffe.set_device(gpu_id);\nelse\n caffe.set_mode_cpu();\nend\n\n% Initialize the network using BVLC CaffeNet for image classification\n% Weights (parameter) file needs to be downloaded from Model Zoo.\nmodel_dir = '../../models/bvlc_reference_caffenet/';\nnet_model = [model_dir 'deploy.prototxt'];\nnet_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];\nphase = 'test'; % run with phase test (so that dropout isn't applied)\nif ~exist(net_weights, 'file')\n error('Please download CaffeNet from Model Zoo before you run this demo');\nend\n\n% Initialize a network\nnet = caffe.Net(net_model, net_weights, phase);\n\nif nargin < 1\n % For demo purposes we will use the cat image\n fprintf('using caffe/examples/images/cat.jpg as input image\\n');\n im = imread('../../examples/images/cat.jpg');\nend\n\n% prepare oversampled input\n% input_data is Height x Width x Channel x Num\ntic;\ninput_data = {prepare_image(im)};\ntoc;\n\n% do forward pass to get scores\n% scores are now Channels x Num, where Channels == 1000\ntic;\n% The net forward function. It takes in a cell array of N-D arrays\n% (where N == 4 here) containing data of input blob(s) and outputs a cell\n% array containing data from output blob(s)\nscores = net.forward(input_data);\ntoc;\n\nscores = scores{1};\nscores = mean(scores, 2); % take average scores over 10 crops\n\n[~, maxlabel] = max(scores);\n\n% call caffe.reset_all() to reset caffe\ncaffe.reset_all();\n\n% ------------------------------------------------------------------------\nfunction crops_data = prepare_image(im)\n% ------------------------------------------------------------------------\n% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that\n% is already in W x H x C with BGR channels\nd = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');\nmean_data = d.mean_data;\nIMAGE_DIM = 256;\nCROPPED_DIM = 227;\n\n% Convert an image returned by Matlab's imread to im_data in caffe's data\n% format: W x H x C with BGR channels\nim_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR\nim_data = permute(im_data, [2, 1, 3]); % flip width and height\nim_data = single(im_data); % convert from uint8 to single\nim_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data\nim_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)\n\n% oversample (4 corners, center, and their x-axis flips)\ncrops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');\nindices = [0 IMAGE_DIM-CROPPED_DIM] + 1;\nn = 1;\nfor i = indices\n for j = indices\n crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);\n crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);\n n = n + 1;\n end\nend\ncenter = floor(indices(2) / 2) + 1;\ncrops_data(:,:,:,5) = ...\n im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);\ncrops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);\n"} +{"plateform": "github", "repo_name": "foss-for-synopsys-dwc-arc-processors/synopsys-caffe-main", "name": "MyVOCevalseg.m", "ext": ".m", "path": "synopsys-caffe-main/matlab/my_script/MyVOCevalseg.m", "size": 4471, "source_encoding": "utf_8", "md5": "f0b406d4e609f1cc3d3694948aeceb67", "text": "%VOCEVALSEG Evaluates a set of segmentation results.\n% VOCEVALSEG(VOCopts,ID); prints out the per class and overall\n% segmentation accuracies. Accuracies are given using the intersection/union \n% metric:\n% true positives / (true positives + false positives + false negatives) \n%\n% [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class\n% percentage ACCURACIES, the average accuracy AVACC and the confusion\n% matrix CONF.\n%\n% [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns\n% the unnormalised confusion matrix, which contains raw pixel counts.\nfunction [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id)\n\n% image test set\n[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d');\n\n% number of labels = number of classes plus one for the background\nnum = VOCopts.nclasses+1; \nconfcounts = zeros(num);\ncount=0;\n\nnum_missing_img = 0;\n\ntic;\nfor i=1:length(gtids)\n % display progress\n if toc>1\n fprintf('test confusion: %d/%d\\n',i,length(gtids));\n drawnow;\n tic;\n end\n \n imname = gtids{i};\n \n % ground truth label file\n gtfile = sprintf(VOCopts.seg.clsimgpath,imname);\n [gtim,map] = imread(gtfile); \n gtim = double(gtim);\n \n % results file\n resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname);\n try\n [resim,map] = imread(resfile);\n catch err\n num_missing_img = num_missing_img + 1;\n %fprintf(1, 'Fail to read %s\\n', resfile);\n continue;\n end\n\n resim = double(resim);\n \n % Check validity of results image\n maxlabel = max(resim(:));\n if (maxlabel>VOCopts.nclasses), \n error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses);\n end\n\n szgtim = size(gtim); szresim = size(resim);\n if any(szgtim~=szresim)\n error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2));\n end\n \n %pixel locations to include in computation\n locs = gtim<255;\n \n % joint histogram\n sumim = 1+gtim+resim*num; \n hs = histc(sumim(locs),1:num*num); \n count = count + numel(find(locs));\n confcounts(:) = confcounts(:) + hs(:);\nend\n\nif (num_missing_img > 0)\n fprintf(1, 'WARNING: There are %d missing results!\\n', num_missing_img);\nend\n\n% confusion matrix - first index is true label, second is inferred label\n%conf = zeros(num);\nconf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]);\nrawcounts = confcounts;\n\n% Pixel Accuracy\noverall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:));\nfprintf('Percentage of pixels correctly labelled overall: %6.3f%%\\n',overall_acc);\n\n% Class Accuracy\nclass_acc = zeros(1, num);\nclass_count = 0;\nfprintf('Accuracy for each class (pixel accuracy)\\n');\nfor i = 1 : num\n denom = sum(confcounts(i, :));\n if (denom == 0)\n denom = 1;\n end\n class_acc(i) = 100 * confcounts(i, i) / denom; \n if i == 1\n clname = 'background';\n else\n clname = VOCopts.classes{i-1};\n end\n \n if ~strcmp(clname, 'void')\n class_count = class_count + 1;\n fprintf(' %14s: %6.3f%%\\n', clname, class_acc(i));\n end\nend\nfprintf('-------------------------\\n');\navg_class_acc = sum(class_acc) / class_count;\nfprintf('Mean Class Accuracy: %6.3f%%\\n', avg_class_acc);\n\n% Pixel IOU\naccuracies = zeros(VOCopts.nclasses,1);\nfprintf('Accuracy for each class (intersection/union measure)\\n');\n\nreal_class_count = 0;\n\nfor j=1:num\n \n gtj=sum(confcounts(j,:));\n resj=sum(confcounts(:,j));\n gtjresj=confcounts(j,j);\n % The accuracy is: true positive / (true positive + false positive + false negative) \n % which is equivalent to the following percentage:\n denom = (gtj+resj-gtjresj);\n\n if denom == 0\n denom = 1;\n end\n \n accuracies(j)=100*gtjresj/denom;\n \n clname = 'background';\n if (j>1), clname = VOCopts.classes{j-1};end;\n \n if ~strcmp(clname, 'void')\n real_class_count = real_class_count + 1;\n else\n if denom ~= 1\n fprintf(1, 'WARNING: this void class has denom = %d\\n', denom);\n end\n end\n \n if ~strcmp(clname, 'void')\n fprintf(' %14s: %6.3f%%\\n',clname,accuracies(j));\n end\nend\n\n%accuracies = accuracies(1:end);\n%avacc = mean(accuracies);\navacc = sum(accuracies) / real_class_count;\n\nfprintf('-------------------------\\n');\nfprintf('Average accuracy: %6.3f%%\\n',avacc);\n"} +{"plateform": "github", "repo_name": "foss-for-synopsys-dwc-arc-processors/synopsys-caffe-main", "name": "MyVOCevalsegBoundary.m", "ext": ".m", "path": "synopsys-caffe-main/matlab/my_script/MyVOCevalsegBoundary.m", "size": 4279, "source_encoding": "utf_8", "md5": "704c57ab30eda1a0f001187608d3c786", "text": "%VOCEVALSEG Evaluates a set of segmentation results.\n% VOCEVALSEG(VOCopts,ID); prints out the per class and overall\n% segmentation accuracies. Accuracies are given using the intersection/union \n% metric:\n% true positives / (true positives + false positives + false negatives) \n%\n% [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class\n% percentage ACCURACIES, the average accuracy AVACC and the confusion\n% matrix CONF.\n%\n% [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns\n% the unnormalised confusion matrix, which contains raw pixel counts.\nfunction [accuracies,avacc,conf,rawcounts, overall_acc, avg_class_acc] = MyVOCevalsegBoundary(VOCopts, id, w)\n\n% get structural element\nst_w = 2*w + 1;\nse = strel('square', st_w);\n\n% image test set\nfn = sprintf(VOCopts.seg.imgsetpath,VOCopts.testset);\nfid = fopen(fn, 'r');\ngtids = textscan(fid, '%s');\ngtids = gtids{1};\nfclose(fid);\n%[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d');\n\n% number of labels = number of classes plus one for the background\nnum = VOCopts.nclasses+1; \nconfcounts = zeros(num);\ncount=0;\ntic;\nfor i=1:length(gtids)\n % display progress\n if toc>1\n fprintf('test confusion: %d/%d\\n',i,length(gtids));\n drawnow;\n tic;\n end\n \n imname = gtids{i};\n \n % ground truth label file\n gtfile = sprintf(VOCopts.seg.clsimgpath,imname);\n [gtim,map] = imread(gtfile); \n gtim = double(gtim);\n \n % results file\n resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname);\n try\n [resim,map] = imread(resfile);\n catch err\n fprintf(1, 'Fail to read %s\\n', resfile);\n continue;\n end\n\n resim = double(resim);\n \n % Check validity of results image\n maxlabel = max(resim(:));\n if (maxlabel>VOCopts.nclasses), \n error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses);\n end\n\n szgtim = size(gtim); szresim = size(resim);\n if any(szgtim~=szresim)\n error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2));\n end\n \n % dilate gt\n binary_gt = gtim == 255;\n dilate_gt = imdilate(binary_gt, se);\n target_gt = dilate_gt & (gtim~=255);\n \n %pixel locations to include in computation\n locs = target_gt;\n %locs = gtim<255;\n \n % joint histogram\n sumim = 1+gtim+resim*num; \n hs = histc(sumim(locs),1:num*num); \n count = count + numel(find(locs));\n confcounts(:) = confcounts(:) + hs(:);\nend\n\n% confusion matrix - first index is true label, second is inferred label\n%conf = zeros(num);\nconf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]);\nrawcounts = confcounts;\n\n% Pixel Accuracy\noverall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:));\nfprintf('Percentage of pixels correctly labelled overall: %6.3f%%\\n',overall_acc);\n\n% Class Accuracy\nclass_acc = zeros(1, num);\nclass_count = 0;\nfprintf('Accuracy for each class (pixel accuracy)\\n');\nfor i = 1 : num\n denom = sum(confcounts(i, :));\n if (denom == 0)\n denom = 1;\n else\n class_count = class_count + 1;\n end\n class_acc(i) = 100 * confcounts(i, i) / denom; \n if i == 1\n clname = 'background';\n else\n clname = VOCopts.classes{i-1};\n end\n fprintf(' %14s: %6.3f%%\\n', clname, class_acc(i));\nend\nfprintf('-------------------------\\n');\navg_class_acc = sum(class_acc) / class_count;\nfprintf('Mean Class Accuracy: %6.3f%%\\n', avg_class_acc);\n\n% Pixel IOU\naccuracies = zeros(VOCopts.nclasses,1);\nfprintf('Accuracy for each class (intersection/union measure)\\n');\nfor j=1:num\n \n gtj=sum(confcounts(j,:));\n resj=sum(confcounts(:,j));\n gtjresj=confcounts(j,j);\n % The accuracy is: true positive / (true positive + false positive + false negative) \n % which is equivalent to the following percentage:\n accuracies(j)=100*gtjresj/(gtj+resj-gtjresj); \n \n clname = 'background';\n if (j>1), clname = VOCopts.classes{j-1};end;\n fprintf(' %14s: %6.3f%%\\n',clname,accuracies(j));\nend\naccuracies = accuracies(1:end);\navacc = mean(accuracies);\nfprintf('-------------------------\\n');\nfprintf('Average accuracy: %6.3f%%\\n',avacc);\n"} +{"plateform": "github", "repo_name": "raalf/VAP3-master", "name": "fcnXML2STRUCT.m", "ext": ".m", "path": "VAP3-master/fcnXML2STRUCT.m", "size": 6958, "source_encoding": "utf_8", "md5": "f865267aab457943222a8412bb26b6a7", "text": "function [ s ] = fcnXML2STRUCT( file )\r\n%Convert xml file into a MATLAB structure\r\n% [ s ] = xml2struct( file )\r\n%\r\n% A file containing:\r\n% \r\n% Some text\r\n% Some more text\r\n% Even more text\r\n% \r\n%\r\n% Will produce:\r\n% s.XMLname.Attributes.attrib1 = \"Some value\";\r\n% s.XMLname.Element.Text = \"Some text\";\r\n% s.XMLname.DifferentElement{1}.Attributes.attrib2 = \"2\";\r\n% s.XMLname.DifferentElement{1}.Text = \"Some more text\";\r\n% s.XMLname.DifferentElement{2}.Attributes.attrib3 = \"2\";\r\n% s.XMLname.DifferentElement{2}.Attributes.attrib4 = \"1\";\r\n% s.XMLname.DifferentElement{2}.Text = \"Even more text\";\r\n%\r\n% Please note that the following characters are substituted\r\n% '-' by '_dash_', ':' by '_colon_' and '.' by '_dot_'\r\n%\r\n% Written by W. Falkena, ASTI, TUDelft, 21-08-2010\r\n% Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011\r\n% Added CDATA support by I. Smirnov, 20-3-2012\r\n%\r\n% Modified by X. Mo, University of Wisconsin, 12-5-2012\r\n\r\n if (nargin < 1)\r\n clc;\r\n help xml2struct\r\n return\r\n end\r\n \r\n if isa(file, 'org.apache.xerces.dom.DeferredDocumentImpl') || isa(file, 'org.apache.xerces.dom.DeferredElementImpl')\r\n % input is a java xml object\r\n xDoc = file;\r\n else\r\n %check for existance\r\n if (exist(file,'file') == 0)\r\n %Perhaps the xml extension was omitted from the file name. Add the\r\n %extension and try again.\r\n if (isempty(strfind(file,'.xml')))\r\n file = [file '.xml'];\r\n end\r\n \r\n if (exist(file,'file') == 0)\r\n error(['The file ' file ' could not be found']);\r\n end\r\n end\r\n %read the xml file\r\n xDoc = xmlread(file);\r\n end\r\n \r\n %parse xDoc into a MATLAB structure\r\n s = parseChildNodes(xDoc);\r\n \r\nend\r\n\r\n% ----- Subfunction parseChildNodes -----\r\nfunction [children,ptext,textflag] = parseChildNodes(theNode)\r\n % Recurse over node children.\r\n children = struct;\r\n ptext = struct; textflag = 'Text';\r\n if hasChildNodes(theNode)\r\n childNodes = getChildNodes(theNode);\r\n numChildNodes = getLength(childNodes);\r\n\r\n for count = 1:numChildNodes\r\n theChild = item(childNodes,count-1);\r\n [text,name,attr,childs,textflag] = getNodeData(theChild);\r\n \r\n if (~strcmp(name,'#text') && ~strcmp(name,'#comment') && ~strcmp(name,'#cdata_dash_section'))\r\n %XML allows the same elements to be defined multiple times,\r\n %put each in a different cell\r\n if (isfield(children,name))\r\n if (~iscell(children.(name)))\r\n %put existsing element into cell format\r\n children.(name) = {children.(name)};\r\n end\r\n index = length(children.(name))+1;\r\n %add new element\r\n children.(name){index} = childs;\r\n if(~isempty(fieldnames(text)))\r\n children.(name){index} = text; \r\n end\r\n if(~isempty(attr)) \r\n children.(name){index}.('Attributes') = attr; \r\n end\r\n else\r\n %add previously unknown (new) element to the structure\r\n children.(name) = childs;\r\n if(~isempty(text) && ~isempty(fieldnames(text)))\r\n children.(name) = text; \r\n end\r\n if(~isempty(attr)) \r\n children.(name).('Attributes') = attr; \r\n end\r\n end\r\n else\r\n ptextflag = 'Text';\r\n if (strcmp(name, '#cdata_dash_section'))\r\n ptextflag = 'CDATA';\r\n elseif (strcmp(name, '#comment'))\r\n ptextflag = 'Comment';\r\n end\r\n \r\n %this is the text in an element (i.e., the parentNode) \r\n if (~isempty(regexprep(text.(textflag),'[\\s]*','')))\r\n if (~isfield(ptext,ptextflag) || isempty(ptext.(ptextflag)))\r\n ptext.(ptextflag) = text.(textflag);\r\n else\r\n %what to do when element data is as follows:\r\n %Text More text\r\n \r\n %put the text in different cells:\r\n % if (~iscell(ptext)) ptext = {ptext}; end\r\n % ptext{length(ptext)+1} = text;\r\n \r\n %just append the text\r\n ptext.(ptextflag) = [ptext.(ptextflag) text.(textflag)];\r\n end\r\n end\r\n end\r\n \r\n end\r\n end\r\nend\r\n\r\n% ----- Subfunction getNodeData -----\r\nfunction [text,name,attr,childs,textflag] = getNodeData(theNode)\r\n % Create structure of node info.\r\n \r\n %make sure name is allowed as structure name\r\n name = toCharArray(getNodeName(theNode))';\r\n name = strrep(name, '-', '_dash_');\r\n name = strrep(name, ':', '_colon_');\r\n name = strrep(name, '.', '_dot_');\r\n\r\n attr = parseAttributes(theNode);\r\n if (isempty(fieldnames(attr))) \r\n attr = []; \r\n end\r\n \r\n %parse child nodes\r\n [childs,text,textflag] = parseChildNodes(theNode);\r\n \r\n if (isempty(fieldnames(childs)) && isempty(fieldnames(text)))\r\n %get the data of any childless nodes\r\n % faster than if any(strcmp(methods(theNode), 'getData'))\r\n % no need to try-catch (?)\r\n % faster than text = char(getData(theNode));\r\n text.(textflag) = toCharArray(getTextContent(theNode))';\r\n end\r\n \r\nend\r\n\r\n% ----- Subfunction parseAttributes -----\r\nfunction attributes = parseAttributes(theNode)\r\n % Create attributes structure.\r\n\r\n attributes = struct;\r\n if hasAttributes(theNode)\r\n theAttributes = getAttributes(theNode);\r\n numAttributes = getLength(theAttributes);\r\n\r\n for count = 1:numAttributes\r\n %attrib = item(theAttributes,count-1);\r\n %attr_name = regexprep(char(getName(attrib)),'[-:.]','_');\r\n %attributes.(attr_name) = char(getValue(attrib));\r\n\r\n %Suggestion of Adrian Wanner\r\n str = toCharArray(toString(item(theAttributes,count-1)))';\r\n k = strfind(str,'='); \r\n attr_name = str(1:(k(1)-1));\r\n attr_name = strrep(attr_name, '-', '_dash_');\r\n attr_name = strrep(attr_name, ':', '_colon_');\r\n attr_name = strrep(attr_name, '.', '_dot_');\r\n attributes.(attr_name) = str((k(1)+2):(end-1));\r\n end\r\n end\r\nend"} +{"plateform": "github", "repo_name": "raalf/VAP3-master", "name": "fcnPLOTCIRC.m", "ext": ".m", "path": "VAP3-master/fcnPLOTCIRC.m", "size": 2440, "source_encoding": "utf_8", "md5": "e988613a8ca8bc1d1f6be5ec87a03277", "text": "function [] = fcnPLOTCIRC(valNELE, matDVE, matVLST, matCENTER, vecDVEROLL, vecDVEPITCH, vecDVEYAW, matCOEFF, ppa)\r\n\r\nfor i = 1:valNELE\r\n corners = fcnGLOBSTAR(matVLST(matDVE(i,:),:) - matCENTER(i,:), repmat(vecDVEROLL(i),4,1), repmat(vecDVEPITCH(i),4,1), repmat(vecDVEYAW(i),4,1));\r\n points = polygrid(corners(:,1), corners(:,2), ppa);\r\n \r\n len = size(points,1);\r\n% vort_p = fcnSTARGLOB([points(:,1) points(:,2) zeros(len,1)], repmat(vecDVEROLL(i),len,1), repmat(vecDVEPITCH(i),len,1), repmat(vecDVEYAW(i),len,1)) + matCENTER(i,:);\r\n% vort = fcnSTARGLOB([(2.*matCOEFF(i,4).*points(:,1) + matCOEFF(i,5)) (2.*matCOEFF(i,1).*points(:,2) + matCOEFF(i,2)) zeros(len,1)], repmat(vecDVEROLL(i),len,1), repmat(vecDVEPITCH(i),len,1), repmat(vecDVEYAW(i),len,1));\r\n% vort = fcnSTARGLOB([zeros(len,1) (2.*matCOEFF(i,1).*points(:,2) + matCOEFF(i,2)) zeros(len,1)], repmat(vecDVEROLL(i),len,1), repmat(vecDVEPITCH(i),len,1), repmat(vecDVEYAW(i),len,1));\r\n\r\n% % points(:,2) is eta in local, points(:,1) is xsi\r\n% circ = matCOEFF(i,1).*points(:,2).^2 + matCOEFF(i,2).*points(:,2) + matCOEFF(i,3) + matCOEFF(i,4).*points(:,1).^2 + matCOEFF(i,5).*points(:,1) + matCOEFF(i,6);\r\n circ = matCOEFF(i,3).*points(:,2).^2 + matCOEFF(i,2).*points(:,2) + matCOEFF(i,1);\r\n \r\n len = size(circ,1);\r\n tri = delaunay(points(:,1), points(:,2));\r\n \r\n circ_glob = fcnSTARGLOB([points circ], repmat(vecDVEROLL(i),len,1), repmat(vecDVEPITCH(i),len,1), repmat(vecDVEYAW(i),len,1));\r\n circ_glob = circ_glob + matCENTER(i,:);\r\n hold on\r\n trisurf(tri, circ_glob(:,1), circ_glob(:,2), circ_glob(:,3),'edgealpha',0,'facealpha',0.8);\r\n% quiver3(vort_p(:,1), vort_p(:,2), vort_p(:,3), vort(:,1), vort(:,2), vort(:,3))\r\n hold off\r\nend\r\n\r\n\r\nfunction [inPoints] = polygrid( xv, yv, N)\r\n\r\n%Find the bounding rectangle\r\n\tlower_x = min(xv);\r\n\thigher_x = max(xv);\r\n\r\n\tlower_y = min(yv);\r\n\thigher_y = max(yv);\r\n%Create a grid of points within the bounding rectangle\r\n\n\tinc_x = (higher_x - lower_x)/N;\r\n\tinc_y = (higher_y - lower_y)/N;\r\n\n\t\r\n\tinterval_x = lower_x:inc_x:higher_x;\r\n\tinterval_y = lower_y:inc_y:higher_y;\r\n\t[bigGridX, bigGridY] = meshgrid(interval_x, interval_y);\r\n\t\r\n%Filter grid to get only points in polygon\r\n\t[in,on] = inpolygon(bigGridX(:), bigGridY(:), xv, yv);\r\n in = in | on;\r\n \r\n%Return the co-ordinates of the points that are in the polygon\r\n\tinPoints = [bigGridX(in), bigGridY(in)];\r\n\r\nend\r\n\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "mrelnet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/mrelnet.m", "size": 2585, "source_encoding": "utf_8", "md5": "2f946c92aba76c5b8ef746baed5e437c", "text": "function fit = mrelnet(x,is_sparse,irs,pcs,y,weights,offset,parm,nobs,nvars,...\n jd,vp,cl,ne,nx,nlam,flmin,ulam,thresh,isd,jsd,intr,maxit,family)\n\nnr = size(y, 2);\n\nwym = wtmean(y, weights);\nnulldev = sum(wtmean(bsxfun(@minus,y,wym).^2,weights)*sum(weights));\n\nif isempty(offset)\n offset = y * 0;\n is_offset = false;\nelse\n if (size(offset) ~= size(y))\n error('Offset must match dimension of y');\n end\n is_offset = true;\nend\n\nif is_sparse\n task = 30;\n [lmu,a0,ca,ia,nin,rsq,alm,nlp,jerr] = glmnetMex(task,parm,x,y-offset,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,cl,intr,maxit,irs,pcs,jsd);\nelse\n task = 31;\n [lmu,a0,ca,ia,nin,rsq,alm,nlp,jerr] = glmnetMex(task,parm,x,y-offset,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,cl,intr,maxit,jsd);\nend\n\nif (jerr ~= 0)\n errmsg = err(jerr,maxit,nx,family);\n if (errmsg.fatal)\n error(errmsg.msg);\n else\n warning(errmsg.msg);\n end\nend\n\nninmax = max(nin);\nlam = alm;\nif (ulam == 0.0)\n lam = fix_lam(lam); % first lambda is infinity; changed to entry point\nend\n\nif (nr > 1)\n beta_list = {};\n% a0 = a0 - repmat(mean(a0), nr, 1); do not center for mrelnet!\n dfmat=a0;\n dd=[nvars, lmu];\n if ninmax > 0\n ca = reshape(ca, nx, nr, lmu);\n ca = ca(1:ninmax,:,:);\n ja = ia(1:ninmax);\n [ja1,oja] = sort(ja);\n df = any(abs(ca) > 0, 2);\n df = sum(df, 1);\n df = df(:);\n for k=1:nr\n ca1 = reshape(ca(:,k,:), ninmax, lmu);\n cak = ca1(oja,:);\n dfmat(k,:) = sum(abs(cak) > 0, 1);\n beta = zeros(nvars, lmu);\n beta(ja1,:) = cak;\n beta_list{k} = beta;\n end\n else\n for k = 1:nr\n dfmat(k,:) = zeros(1,lmu);\n beta_list{k} = zeros(nvars, lmu);\n end\n df = zeros(1,lmu);\n end\n fit.beta = beta_list;\n fit.dfmat = dfmat;\n \n \nelse\n \n dd=[nvars, lmu];\n if ninmax > 0\n ca = ca(1:ninmax,:);\n df = sum(abs(ca) > 0, 1);\n ja = ia(1:ninmax);\n [ja1,oja] = sort(ja);\n beta = zeros(nvars, lmu);\n beta (ja1, :) = ca(oja,:);\n else\n beta = zeros(nvars,lmu);\n df = zeros(1,lmu);\n end\n \n fit.beta = beta;\n \n \nend\n\nfit.a0 = a0;\nfit.dev = rsq;\nfit.nulldev = nulldev;\nfit.df = df';\nfit.lambda = lam;\nfit.npasses = nlp;\nfit.jerr = jerr;\nfit.dim = dd;\nfit.offset = is_offset;\nfit.class = 'mrelnet';\n\n\nfunction new_lam = fix_lam(lam)\n\nnew_lam = lam;\nif (length(lam) > 2)\n llam=log(lam);\n new_lam(1)=exp(2*llam(2)-llam(3));\nend\n\n"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "coxnet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/coxnet.m", "size": 1563, "source_encoding": "utf_8", "md5": "895747785766daa2c82975f3d019dd18", "text": "function fit = coxnet(x,is_sparse,irs,pcs,y,weights,offset,parm,nobs,nvars,...\n jd,vp,cl,ne,nx,nlam,flmin,ulam,thresh,isd,maxit,family)\n\n% Internal glmnet function. See also glmnet, cvglmnet.\n\n%time --- column 1\n%status --- column 2\n\nty = y(:,1);\ntevent = y(:,2);\nif (any(ty <= 0))\n error('negative event times encountered; not permitted for Cox family');\nend\nif isempty(offset)\n offset = ty * 0;\n is_offset = false;\nelse\n is_offset = true;\nend\n\nif (is_sparse)\n error('Cox model not implemented for sparse x in glmnet');\nelse\n task = 41;\n [lmu,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,ty,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,tevent,cl,maxit,offset);\n\nend\n\nif (jerr ~= 0)\n errmsg = err(jerr,maxit,nx,family);\n if (errmsg.fatal)\n error(errmsg.msg);\n else\n warning(errmsg.msg);\n end\nend\n\nninmax = max(nin);\nlam = alm;\nif (ulam == 0.0)\n lam = fix_lam(lam); % first lambda is infinity; changed to entry point\nend\n\ndd=[nvars, lmu];\nif ninmax > 0\n ca = ca(1:ninmax,:);\n df = sum(abs(ca) > 0, 1);\n ja = ia(1:ninmax);\n [ja1,oja] = sort(ja);\n beta = zeros(nvars, lmu);\n beta (ja1,:) = ca(oja,:);\nelse\n beta = zeros(nvars,lmu);\n df = zeros(1,lmu);\nend\n\nfit.beta = beta;\nfit.dev = dev;\nfit.nulldev = dev0;\nfit.df = df';\nfit.lambda = lam;\nfit.npasses = nlp;\nfit.jerr = jerr;\nfit.dim = dd;\nfit.offset = is_offset;\nfit.class = 'coxnet';\n\n\nfunction new_lam = fix_lam(lam)\n\nnew_lam = lam;\nif (length(lam) > 2)\n llam=log(lam);\n new_lam(1)=exp(2*llam(2)-llam(3));\nend\n\n"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "err.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/err.m", "size": 3764, "source_encoding": "utf_8", "md5": "eeab9274fcf914b604c55eb4ec2a867a", "text": "function output = err(n,maxit,pmax,family)\n\nif n==0\n output.n=0;\n output.fatal=false;\n output.msg='';\n \nelse\n switch family\n case 'gaussian'\n output = err_elnet(n,maxit,pmax);\n case 'binomial'\n output = err_lognet(n,maxit,pmax);\n case 'multinomial'\n output = err_lognet(n,maxit,pmax);\n case 'poisson'\n output = err_fishnet(n,maxit,pmax);\n case 'cox'\n output = err_coxnet(n,maxit,pmax);\n case 'mrelnet'\n output = err_mrelnet(n,maxit,pmax);\n end\n output.msg = sprintf('from glmnet Fortran code (error code %d); %s', n, output.msg);\nend\n\n\n%------------------------------------------------------------------\n% End private function err\n%------------------------------------------------------------------\n\nfunction output = err_elnet(n,maxit,pmax)\n\nif (n > 0) %fatal error\n if (n < 7777)\n msg = 'Memory allocation error; contact package maintainer';\n elseif (n == 7777)\n msg = 'All used predictors have zero variance';\n elseif (n == 10000)\n msg = 'All penalty factors are <= 0';\n else\n msg = 'Unknown error';\n end\n output.n = n;\n output.fatal = true;\n output.msg = msg;\nelseif (n < 0) %non-fatal error\n if (n > -10000)\n msg = sprintf('Convergence for %dth lambda value not reached after maxit=%d iterations; solutions for larger lambdas returned',-n,maxit);\n end\n if (n < -10000)\n msg = sprintf('Number of nonzero coefficients along the path exceeds pmax=%d at %dth lambda value; solutions for larger lambdas returned',pmax,-n-10000);\n end\n output.n = n;\n output.fatal = false;\n output.msg = msg;\nend\n\n\nfunction output = err_lognet(n,maxit,pmax)\n\noutput = err_elnet(n,maxit,pmax);\nif (n < -20000)\n output.msg = sprintf('Max(p(1-p),1.0e-6 at %dth value of lambda; solutions for larger values of lambda returned',-n-20000);\nend\nif ~strcmp(output.msg, 'Unknown error')\n return;\nend\nif (8000 < n) && (n < 9000)\n msg = sprintf('Null probability for class%d< 1.0e-5', n-8000);\nelseif (9000 < n) && (n < 10000)\n msg = sprintf('Null probability for class%d> 1.0 - 1.0e-5',n-9000);\nelse\n msg = 'Unknown error';\nend\noutput.n = n;\noutput.fatal = true;\noutput.msg = msg;\n\n\nfunction output = err_fishnet(n,maxit,pmax)\n\noutput = err_elnet(n,maxit,pmax);\nif ~strcmp(output.msg, 'Unknown error')\n return;\nend\nif (n == 8888)\n msg = 'Negative response values - should be counts';\nelseif (n == 9999)\n msg = 'No positive observation weights';\nelse\n msg = 'Unknown error';\nend\noutput.n = n;\noutput.fatal = true;\noutput.msg = msg;\n\n\nfunction output = err_coxnet(n,maxit,pmax)\n\nif (n > 0) %fatal error\n output = err_elnet(n,maxit,pmax);\n if ~strcmp(msg, 'Unknown error')\n return;\n end\n if (n == 8888)\n msg = 'All observations censored - cannot proceed';\n elseif (n == 9999)\n msg = 'No positive observation weights';\n elseif (n == 20000) || (n == 30000)\n msg = 'Inititialization numerical error; probably too many censored observations';\n else\n msg = 'Unknown error';\n end\n output.n = n;\n output.fatal = true;\n output.msg = msg;\nelseif (n < 0)\n if (n <= -30000)\n msg = sprintf('Numerical error at %dth lambda value; solutions for larger values of lambda returned',-n-30000);\n output.n = n;\n output.fatal = false;\n output.msg = msg;\n else\n output = err_elnet(n,maxit,pmax);\n end\nend\n\n\nfunction output = err_mrelnet(n,maxit,pmax)\n\nif (n == 90000)\n msg = 'Newton stepping for bounded multivariate response did not converge';\n output.n = n;\n output.fatal = false;\n output.msg = msg;\nelse\n output = err_elnet(n,maxit,pmax);\nend"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "glmnetPlot.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/glmnetPlot.m", "size": 7609, "source_encoding": "utf_8", "md5": "12fcbd8fb5cafce7d419403fcfab5649", "text": "function glmnetPlot( x, xvar, label, type, varargin )\n\n%--------------------------------------------------------------------------\n% glmnetPlot.m: plot coefficients from a \"glmnet\" object\n%--------------------------------------------------------------------------\n%\n% DESCRIPTION:\n% Produces a coefficient profile plot fo the coefficient paths for a\n% fitted \"glmnet\" object.\n%\n% USAGE:\n% glmnetPlot(fit);\n% glmnetPlot(fit, xvar);\n% glmnetPlot(fit, xvar, label);\n% glmnetPlot(fit, xvar, label, type);\n% glmnetPlot(fit, xvar, label, type, ...);\n% (Use empty matrix [] to apply the default value, eg. glmnetPlot(fit,\n% [], [], type).)\n%\n% INPUT ARGUMENTS:\n% x fitted \"glmnet\" model.\n% xvar What is on the X-axis. 'norm' plots against the L1-norm of\n% the coefficients, 'lambda' against the log-lambda sequence,\n% and 'dev' against the percent deviance explained.\n% label If true, label the curves with variable sequence numbers.\n% type If type='2norm' then a single curve per variable, else\n% if type='coef', a coefficient plot per response.\n% varargin Other graphical parameters to plot.\n%\n% DETAILS:\n% A coefficient profile plot is produced. If x is a multinomial model, a\n% coefficient plot is produced for each class.\n%\n% LICENSE: GPL-2\n%\n% DATE: 30 Aug 2013\n%\n% AUTHORS:\n% Algorithm was designed by Jerome Friedman, Trevor Hastie and Rob Tibshirani\n% Fortran code was written by Jerome Friedman\n% R wrapper (from which the MATLAB wrapper was adapted) was written by Trevor Hasite\n% The original MATLAB wrapper was written by Hui Jiang (14 Jul 2009),\n% and was updated and maintained by Junyang Qian (30 Aug 2013) junyangq@stanford.edu,\n% Department of Statistics, Stanford University, Stanford, California, USA.\n%\n% REFERENCES:\n% Friedman, J., Hastie, T. and Tibshirani, R. (2008) Regularization Paths for Generalized Linear Models via Coordinate Descent, \n% http://www.jstatsoft.org/v33/i01/\n% Journal of Statistical Software, Vol. 33(1), 1-22 Feb 2010\n% \n% Simon, N., Friedman, J., Hastie, T., Tibshirani, R. (2011) Regularization Paths for Cox's Proportional Hazards Model via Coordinate Descent,\n% http://www.jstatsoft.org/v39/i05/\n% Journal of Statistical Software, Vol. 39(5) 1-13\n%\n% Tibshirani, Robert., Bien, J., Friedman, J.,Hastie, T.,Simon, N.,Taylor, J. and Tibshirani, Ryan. (2010) Strong Rules for Discarding Predictors in Lasso-type Problems,\n% http://www-stat.stanford.edu/~tibs/ftp/strong.pdf\n% Stanford Statistics Technical Report\n%\n% SEE ALSO:\n% glmnet, glmnetSet, glmnetPrint, glmnetPredict and glmnetCoef.\n%\n% EXAMPLES:\n% x=randn(100,20);\n% y=randn(100,1);\n% g2=randsample(2,100,true);\n% g4=randsample(4,100,true);\n% fit1=glmnet(x,y);\n% glmnetPlot(fit1);\n% glmnetPlot(fit1, 'lambda', true);\n% fit3=glmnet(x,g4,'multinomial');\n% glmnetPlot(fit3);\n%\n% DEVELOPMENT: \n% 14 Jul 2009: Original version of glmnet.m written.\n% 30 Aug 2013: Updated glmnet.m with more options and more models\n% (multi-response Gaussian, cox and Poisson models) supported.\n\nif nargin < 2 || isempty(xvar)\n xvar = 'norm';\nend\n\nif nargin < 3 || isempty(label)\n label = false;\nend\n\nif nargin < 4 || isempty(type)\n type = 'coef';\nend\n\nxvarbase = {'norm','lambda','dev'};\nxvarind = find(strncmp(xvar,xvarbase,length(xvar)),1);\nif isempty(xvarind)\n error('xvar should be one of ''norm'', ''lambda'', ''dev''');\nelse\n xvar = xvarbase{xvarind};\nend\n\ntypebase = {'coef','2norm'};\ntypeind = find(strncmp(type,typebase,length(type)),1);\nif isempty(typeind)\n error('type should be one of ''coef'', ''2norm''');\nelse\n type = typebase{typeind};\nend\n\nif any(strcmp(x.class,{'elnet','lognet','coxnet','fishnet'}))\n plotCoef(x.beta,[],x.lambda,x.df,x.dev,label,xvar,'','Coefficients',varargin{:});\nend\n\nif strcmp(x.class,'multnet') || strcmp(x.class,'mrelnet')\n beta = x.beta;\n if strcmp(xvar,'norm')\n norm = 0;\n nzbeta = beta;\n for i=1:length(beta)\n which = nonzeroCoef(beta{i});\n nzbeta{i} = beta{i}(which,:);\n norm = norm + sum(abs(nzbeta{i}),1);\n end\n else\n norm = 0;\n end\n \n if strcmp(type,'coef')\n ncl = size(x.dfmat,1);\n if strcmp(x.class,'multnet')\n for i = 1:ncl\n plotCoef(beta{i},norm,x.lambda,x.dfmat(i,:),x.dev,label,xvar,'',sprintf('Coefficients: Class %d', i),varargin{:});\n end\n else\n for i = 1:ncl\n plotCoef(beta{i},norm,x.lambda,x.dfmat(i,:),x.dev,label,xvar,'',sprintf('Coefficients: Response %d', i),varargin{:});\n end\n end\n else\n dfseq = round(mean(x.dfmat,1));\n coefnorm = beta{1}*0;\n for i=1:length(beta)\n coefnorm = coefnorm + abs(beta{i}).^2;\n end\n coefnorm = sqrt(coefnorm);\n if strcmp(x.class,'multnet')\n plotCoef(coefnorm,norm,x.lambda,dfseq,x.dev,label,xvar,'',sprintf('Coefficient 2Norms'),varargin{:});\n else\n plotCoef(coefnorm,norm,x.lambda,x.dfmat(1,:),x.dev,label,xvar,'',sprintf('Coefficient 2Norms'),varargin{:});\n end\n \n end\nend\n\n%----------------------------------------------------------------\n% End function glmnetPlot\n%----------------------------------------------------------------\n\nfunction plotCoef(beta,norm,lambda,df,dev,label,xvar,xlab,ylab,varargin)\n\nwhich = nonzeroCoef(beta);\nidwhich = find(which); %row indices\nnwhich = length(idwhich);\nif nwhich == 0\n error('No plot produced since all coefficients zero')\nend\nif nwhich == 1\n warning('1 or less nonzero coefficients; glmnet plot is not meaningful');\nend\n\nbeta = beta(which,:);\nif strcmp(xvar, 'norm')\n if isempty(norm)\n index = sum(abs(beta),1);\n else\n index = norm;\n end\n iname = 'L1 Norm';\nelseif strcmp(xvar, 'lambda')\n index=log(lambda);\n iname='Log Lambda';\nelseif strcmp(xvar, 'dev')\n index=dev;\n iname='Fraction Deviance Explained';\nend\n\nif isempty(xlab)\n xlab = iname;\nend\n\n%Prepare for the figure (especially for the df labels)\n\nclf;\n\nbeta = transpose(beta);\nplot(index,beta,varargin{:});\n\naxes1 = gca;\naxes;\naxes2 = gca;\n\nxlim1 = get(axes1,'XLim');\nylim1 = get(axes1,'YLim');\n\n%idxrange = range(index);\n%atdf = linspace(min(index)+idxrange/12, max(index)-idxrange/12, 6);\natdf = get(axes1,'XTick');\nindat = ones(size(atdf));\nif (index(end) >= index(1))\n for j = length(index):-1:1\n indat(atdf <= index(j)) = j;\n end\nelse\n for j = 1:length(index)\n indat(atdf <= index(j)) = j;\n end\nend\nprettydf = df(indat);\nprettydf(end) = df(end);\n\nset(axes1,'box','off','XAxisLocation','bottom','YAxisLocation','left');\nset(axes2,'XAxisLocation','top','YAxisLocation','right',...\n 'XLim',[min(index),max(index)],'XTick',atdf,'XTickLabel',prettydf,...\n 'YTick',[],'YTickLabel',[],'TickDir','out');\nxlabel(axes2,'Degrees of Freedom')\naxes(axes1);\n\nline(xlim1,[ylim1(2),ylim1(2)],'Color','k');\nline([xlim1(2),xlim1(2)],ylim1,'Color','k');\n\nxlabel(xlab);\nylabel(ylab);\n\n\nif (label)\n xpos = max(index);\n adjpos = 2;\n if strcmp(xvar,'lambda')\n xpos = min(index);\n adjpos = 1;\n end\n bsize = size(beta);\n for i = 1: bsize(2)\n text(1/2*xpos+1/2*xlim1(adjpos),beta(bsize(1),i),num2str(idwhich(i)));\n end\nend\n\nlinkaxes([axes1 axes2],'x');\n\n%----------------------------------------------------------------\n% End private function plotCoef\n%----------------------------------------------------------------\n"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "glmnetPredict.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/glmnetPredict.m", "size": 16486, "source_encoding": "utf_8", "md5": "58bccedbf1d9b31e6c7b0e05d2058f3d", "text": "function result = glmnetPredict(object, newx, s, type, exact, offset)\n\n%--------------------------------------------------------------------------\n% glmnetPredict.m: make predictions from a \"glmnet\" object.\n%--------------------------------------------------------------------------\n%\n% DESCRIPTION:\n% Similar to other predict methods, this functions predicts fitted\n% values, logits, coefficients and more from a fitted \"glmnet\" object.\n%\n% USAGE:\n% glmnetPredict(object, newx, s, type, exact, offset)\n%\n% Fewer input arguments(more often) are allowed in the call, but must\n% come in the order listed above. To set default values on the way, use\n% empty matrix []. \n% For example, pred=glmnetPredict(fit,[],[],'coefficients').\n% \n% To make EXACT prediction, the input arguments originally passed to \n% \"glmnet\" MUST be VARIABLES (instead of expressions, or fields\n% extracted from some struct objects). Alternatively, users should\n% manually revise the \"call\" field in \"object\" (expressions or variable\n% names) to match the original call to glmnet in the parent environment.\n%\n% INPUT ARGUMENTS:\n% object Fitted \"glmnet\" model object.\n% s Value(s) of the penalty parameter lambda at which predictions\n% are required. Default is the entire sequence used to create\n% the model.\n% newx Matrix of new values for x at which predictions are to be\n% made. Must be a matrix; can be sparse. This argument is not \n% used for type='coefficients' or type='nonzero'.\n% type Type of prediction required. Type 'link' gives the linear\n% predictors for 'binomial', 'multinomial', 'poisson' or 'cox'\n% models; for 'gaussian' models it gives the fitted values.\n% Type 'response' gives the fitted probabilities for 'binomial'\n% or 'multinomial', fitted mean for 'poisson' and the fitted\n% relative-risk for 'cox'; for 'gaussian' type 'response' is\n% equivalent to type 'link'. Type 'coefficients' computes the\n% coefficients at the requested values for s. Note that for\n% 'binomial' models, results are returned only for the class\n% corresponding to the second level of the factor response.\n% Type 'class' applies only to 'binomial' or 'multinomial'\n% models, and produces the class label corresponding to the\n% maximum probability. Type 'nonzero' returns a matrix of\n% logical values with each column for each value of s, \n% indicating if the corresponding coefficient is nonzero or not.\n% exact If exact=true, and predictions are to made at values of s not\n% included in the original fit, these values of s are merged\n% with object.lambda, and the model is refit before predictions\n% are made. If exact=false (default), then the predict function\n% uses linear interpolation to make predictions for values of s\n% that do not coincide with those used in the fitting\n% algorithm. Note that exact=true is fragile when used inside a\n% nested sequence of function calls. glmnetPredict() needs to\n% update the model, and expects the data used to create it in\n% the parent environment.\n% offset If an offset is used in the fit, then one must be supplied\n% for making predictions (except for type='coefficients' or\n% type='nonzero')\n% \n% DETAILS:\n% The shape of the objects returned are different for \"multinomial\"\n% objects. glmnetCoef(fit, ...) is equivalent to \n% glmnetPredict(fit,[],[],'coefficients\").\n%\n% LICENSE: GPL-2\n%\n% DATE: 30 Aug 2013\n%\n% AUTHORS:\n% Algorithm was designed by Jerome Friedman, Trevor Hastie and Rob Tibshirani\n% Fortran code was written by Jerome Friedman\n% R wrapper (from which the MATLAB wrapper was adapted) was written by Trevor Hasite\n% The original MATLAB wrapper was written by Hui Jiang (14 Jul 2009),\n% and was updated and maintained by Junyang Qian (30 Aug 2013) junyangq@stanford.edu,\n% Department of Statistics, Stanford University, Stanford, California, USA.\n%\n% REFERENCES:\n% Friedman, J., Hastie, T. and Tibshirani, R. (2008) Regularization Paths for Generalized Linear Models via Coordinate Descent, \n% http://www.jstatsoft.org/v33/i01/\n% Journal of Statistical Software, Vol. 33(1), 1-22 Feb 2010\n% \n% Simon, N., Friedman, J., Hastie, T., Tibshirani, R. (2011) Regularization Paths for Cox's Proportional Hazards Model via Coordinate Descent,\n% http://www.jstatsoft.org/v39/i05/\n% Journal of Statistical Software, Vol. 39(5) 1-13\n%\n% Tibshirani, Robert., Bien, J., Friedman, J.,Hastie, T.,Simon, N.,Taylor, J. and Tibshirani, Ryan. (2010) Strong Rules for Discarding Predictors in Lasso-type Problems,\n% http://www-stat.stanford.edu/~tibs/ftp/strong.pdf\n% Stanford Statistics Technical Report\n%\n% SEE ALSO:\n% glmnet, glmnetPrint, glmnetCoef, and cvglmnet.\n%\n% EXAMPLES:\n% x=randn(100,20);\n% y=randn(100,1);\n% g2=randsample(2,100,true);\n% g4=randsample(4,100,true);\n% fit1=glmnet(x,y);\n% glmnetPredict(fit1,x(1:5,:),[0.01,0.005]') % make predictions\n% glmnetPredict(fit1,[],[],'coefficients')\n% fit2=glmnet(x,g2,'binomial');\n% glmnetPredict(fit2, x(2:5,:),[], 'response')\n% glmnetPredict(fit2, [], [], 'nonzero')\n% fit3=glmnet(x,g4,'multinomial');\n% glmnetPredict(fit3, x(1:3,:), 0.01, 'response')\n%\n% DEVELOPMENT:\n% 14 Jul 2009: Original version of glmnet.m written.\n% 30 Aug 2013: Updated glmnet.m with more options and more models\n% (multi-response Gaussian, cox and Poisson models) supported. \n\n% OLDER UPDATES:\n% 20 Oct 2009: Fixed a bug in bionomial response, pointed out by Ramon\n% Casanov from Wake Forest University.\n% 26 Jan 2010: Fixed a bug in multinomial link and class, pointed out by\n% Peter Rijnbeek from Erasmus University.\n% 23 Jun 2010: Fixed a bug in multinomial with s, pointed out by \n% Robert Jacobsen from Aalborg University.\n\nif nargin < 2 || isempty(newx)\n newx = [];\nend\nif nargin < 3\n s = [];\nend\nif nargin < 4 || isempty(type)\n type = 'link';\nend\nif nargin < 5 || isempty(exact)\n exact = false;\nend\nif nargin < 6\n offset = [];\nend\n\ntypebase = {'link','response','coefficients','nonzero','class'};\ntypeind = find(strncmp(type,typebase,length(type)),1);\ntype = typebase{typeind};\n\nif isempty(newx)\n if ~strcmp(type, 'coefficients') && ~strcmp(type, 'nonzero')\n error('You need to supply a value for ''newx''');\n end\nend\n\n%exact case: need to execute statements back in the parent environment\nif (exact && ~isempty(s))\n which = ismember(s,object.lambda);\n if ~all(which)\n lambda = unique([object.lambda;reshape(s,length(s),1)]);\n %-----create a new variable in the parent environment\n vname = 'newlam';\n expr = sprintf('any(strcmp(''%s'', who))',vname);\n newname = vname;\n i = 0;\n while (evalin('caller',expr))\n i = i + 1;\n newname = [vname,num2str(i)];\n expr = sprintf('any(strcmp(who,''%s''))',newname);\n end\n parlam = newname;\n %-----\n assignin('caller', parlam, lambda);\n \n vname = 'temp_opt';\n expr = sprintf('any(strcmp(''%s'', who))',vname);\n newname = vname;\n i = 0;\n while (evalin('caller',expr))\n i = i + 1;\n newname = [vname,num2str(i)];\n expr = sprintf('any(strcmp(who,''%s''))',newname);\n end\n paropt = newname;\n \n if strcmp('[]',object.call{3})\n famcall = object.call{3};\n else\n famcall = sprintf('''%s''',object.call{3});\n end\n \n if ~strcmp('[]', object.call{4})\n evalin('caller', strcat(paropt,'=',object.call{4},';'));\n evalin('caller', strcat(paropt,'.lambda = ',parlam,';'));\n newcall = sprintf('glmnet(%s, %s, %s, %s)', ...\n object.call{1}, object.call{2}, famcall, paropt);\n object = evalin('caller', newcall);\n else\n evalin('caller', strcat(paropt,'.lambda = ',parlam,';'));\n newcall = sprintf('glmnet(%s, %s, %s, %s)', ...\n object.call{1}, object.call{2}, famcall, paropt);\n object = evalin('caller', newcall);\n end\n evalin('caller', sprintf('clearvars %s %s;',parlam,paropt));\n end\nend\n\nif strcmp(object.class,'elnet')\n a0 = transpose(object.a0);\n nbeta=[a0; object.beta];\n \n if (~isempty(s))\n lambda=object.lambda;\n lamlist=lambda_interp(lambda,s);\n nbeta=nbeta(:,lamlist.left).*repmat(lamlist.frac',size(nbeta,1),1) +nbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(nbeta,1),1));\n end\n \n if strcmp(type, 'coefficients')\n result = nbeta;\n return;\n end\n if strcmp(type, 'nonzero')\n result = nonzeroCoef(nbeta(2:size(nbeta,1),:), true);\n return;\n end\n \n result = [ones(size(newx,1),1), newx] * nbeta;\n if (object.offset)\n if isempty(offset)\n error('No offset provided for prediction, yet used in fit of glmnet');\n end\n if (size(offset,2)==2)\n offset = offset(:,2);\n end\n result = result + repmat(offset, 1, size(result, 2));\n end\nend\n\nif strcmp(object.class,'fishnet')\n a0 = transpose(object.a0);\n nbeta=[a0; object.beta];\n \n if (~isempty(s))\n lambda=object.lambda;\n lamlist=lambda_interp(lambda,s);\n nbeta=nbeta(:,lamlist.left).*repmat(lamlist.frac',size(nbeta,1),1) +nbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(nbeta,1),1));\n end\n \n if strcmp(type, 'coefficients')\n result = nbeta;\n return;\n end\n if strcmp(type, 'nonzero')\n result = nonzeroCoef(nbeta(2:size(nbeta,1),:), true);\n return;\n end\n \n result = [ones(size(newx,1),1), newx] * nbeta;\n if (object.offset)\n if isempty(offset)\n error('No offset provided for prediction, yet used in fit of glmnet');\n end\n if (size(offset,2) == 2)\n offset = offset(:, 2);\n end\n result = result + repmat(offset, 1, size(result,2));\n end\n \n if strcmp(type, 'response')\n result = exp(result);\n end\nend \n\nif strcmp(object.class, 'lognet')\n a0 = object.a0;\n nbeta=[a0; object.beta];\n \n if (~isempty(s))\n lambda=object.lambda;\n lamlist=lambda_interp(lambda,s);\n nbeta=nbeta(:,lamlist.left).*repmat(lamlist.frac',size(nbeta,1),1) +nbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(nbeta,1),1));\n end\n \n if strcmp(type, 'coefficients')\n result = nbeta;\n return;\n end\n if strcmp(type, 'nonzero')\n result = nonzeroCoef(nbeta(2:size(nbeta,1),:), true);\n return;\n end\n \n result = [ones(size(newx,1),1), newx] * nbeta;\n if (object.offset)\n if isempty(offset)\n error('No offset provided for prediction, yet used in fit of glmnet');\n end\n if (size(offset,2)==2)\n offset = offset(:,2);\n end\n result = result + repmat(offset, 1, size(result, 2));\n end\n switch type\n case 'response'\n pp = exp(-result);\n result = 1./ (1+pp);\n case 'class'\n result = (result > 0) * 2 + (result <= 0) * 1;\n result = object.label(result);\n end\nend\n\nif strcmp(object.class, 'multnet') || strcmp(object.class,'mrelnet')\n if strcmp(object.class,'mrelnet')\n if strcmp(type, 'response')\n type = 'link';\n end\n object.grouped = true;\n end\n \n a0=object.a0;\n nbeta=object.beta;\n nclass=size(a0,1);\n nlambda=length(s);\n \n if (~isempty(s))\n lambda=object.lambda;\n lamlist=lambda_interp(lambda,s);\n for i=1:nclass\n kbeta=[a0(i,:); nbeta{i}];\n kbeta=kbeta(:,lamlist.left).*repmat(lamlist.frac',size(kbeta,1),1)+kbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(kbeta,1),1));\n nbeta{i}=kbeta;\n end\n else\n for i=1:nclass\n nbeta{i} = [a0(i,:);nbeta{i}];\n end\n nlambda = length(object.lambda);\n end\n if strcmp(type, 'coefficients')\n result = nbeta;\n return;\n end\n if strcmp(type, 'nonzero')\n if (object.grouped)\n result{1} = nonzeroCoef(nbeta{1}(2:size(nbeta{1},1),:),true);\n else\n for i=1:nclass\n result{i}=nonzeroCoef(nbeta{i}(2:size(nbeta{i},1),:),true);\n end\n end\n return;\n end\n npred=size(newx,1);\n dp = zeros(nclass,nlambda,npred);\n for i=1:nclass\n fitk = [ones(size(newx,1),1), newx] * nbeta{i};\n dp(i,:,:)=dp(i,:,:)+reshape(transpose(fitk),1,nlambda,npred);\n end\n if (object.offset)\n if (isempty(offset))\n error('No offset provided for prediction, yet used in fit of glmnet');\n end\n if (size(offset,2) ~= nclass)\n error('Offset should be dimension%dx%d',npred,nclass)\n end\n toff = transpose(offset);\n for i = 1:nlambda\n dp(:,i,:) = dp(:,i,:) + toff;\n end\n end\n switch type\n case 'response'\n pp = exp(dp);\n psum = sum(pp,1);\n result = permute(pp./repmat(psum,nclass,1),[3,1,2]);\n case 'link'\n result=permute(dp,[3,1,2]);\n case 'class'\n dp=permute(dp,[3,1,2]);\n result = [];\n for i=1:size(dp,3)\n result = [result, object.label(softmax(dp(:,:,i)))];\n end\n end\n \nend\n\nif strcmp(object.class,'coxnet')\n nbeta = object.beta;\n if (~isempty(s))\n lambda=object.lambda;\n lamlist=lambda_interp(lambda,s);\n nbeta=nbeta(:,lamlist.left).*repmat(lamlist.frac',size(nbeta,1),1) +nbeta(:,lamlist.right).*(1-repmat(lamlist.frac',size(nbeta,1),1));\n end\n if strcmp(type, 'coefficients')\n result = nbeta;\n return;\n end\n if strcmp(type, 'nonzero')\n result = nonzeroCoef(nbeta, true);\n return;\n end\n result = newx * nbeta;\n if (object.offset)\n if isempty(offset)\n error('No offset provided for prediction, yet used in fit of glmnet');\n end\n result = result + repmat(offset, 1, size(result, 2));\n end\n \n if strcmp(type, 'response')\n result = exp(result);\n end\nend\n \n%-------------------------------------------------------------\n% End private function glmnetPredict\n%-------------------------------------------------------------\n\n\nfunction result = lambda_interp(lambda,s)\n% lambda is the index sequence that is produced by the model\n% s is the new vector at which evaluations are required.\n% the value is a vector of left and right indices, and a vector of fractions.\n% the new values are interpolated bewteen the two using the fraction\n% Note: lambda decreases. you take:\n% sfrac*left+(1-sfrac*right)\n\nif length(lambda)==1 % degenerate case of only one lambda\n nums=length(s);\n left=ones(nums,1);\n right=left;\n sfrac=ones(nums,1);\nelse\n s(s > max(lambda)) = max(lambda);\n s(s < min(lambda)) = min(lambda);\n k=length(lambda);\n sfrac =(lambda(1)-s)/(lambda(1) - lambda(k));\n lambda = (lambda(1) - lambda)/(lambda(1) - lambda(k));\n coord = interp1(lambda, 1:length(lambda), sfrac);\n left = floor(coord);\n right = ceil(coord);\n sfrac=(sfrac-lambda(right))./(lambda(left) - lambda(right));\n sfrac(left==right)=1;\nend\nresult.left = left;\nresult.right = right;\nresult.frac = sfrac;\n\n%-------------------------------------------------------------\n% End private function lambda_interp\n%-------------------------------------------------------------\n\nfunction result = softmax(x, gap)\nif nargin < 2\n gap = false;\nend\nd = size(x);\nmaxdist = x(:, 1);\npclass = repmat(1, d(1), 1);\nfor i =2:d(2)\n l = x(:, i) > maxdist;\n pclass(l) = i;\n maxdist(l) = x(l, i);\nend\nif gap\n x = abs(maxdist - x);\n x(1:d(1), pclass) = x * repmat(1, d(2));\n gaps = pmin(x);\nend\nif gap\n result = {pclass, gaps};\nelse\n result = pclass;\nend\n\n%-------------------------------------------------------------\n% End private function softmax\n%-------------------------------------------------------------"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "fishnet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/fishnet.m", "size": 1567, "source_encoding": "utf_8", "md5": "a38133450377adad1e403b48017b5d9e", "text": "function fit = fishnet(x,is_sparse,irs,pcs,y,weights,offset,parm,nobs,nvars,...\n jd,vp,cl,ne,nx,nlam,flmin,ulam,thresh,isd,intr,maxit,family)\n\nif any(y < 0)\n error('negative responses encountered; not permitted for Poisson family');\nend\n\nif isempty(offset)\n offset = y * 0;\n is_offset = false;\nelse\n is_offset = true;\nend\n\nif (is_sparse)\n task = 50;\n [lmu,a0,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,y,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,cl,intr,maxit,offset,irs,pcs);\nelse\n task = 51;\n [lmu,a0,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,y,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,cl,intr,maxit,offset);\nend\n\nif (jerr ~= 0)\n errmsg = err(jerr,maxit,nx,family);\n if (errmsg.fatal)\n error(errmsg.msg);\n else\n warning(errmsg.msg);\n end\nend\n\nninmax = max(nin);\nlam = alm;\nif (ulam == 0.0)\n lam = fix_lam(lam); % first lambda is infinity; changed to entry point\nend\n\ndd=[nvars, lmu];\nif ninmax > 0\n ca = ca(1:ninmax,:);\n df = sum(abs(ca) > 0, 1);\n ja = ia(1:ninmax);\n [ja1,oja] = sort(ja);\n beta = zeros(nvars, lmu);\n beta (ja1, :) = ca(oja,:);\nelse\n beta = zeros(nvars,lmu);\n df = zeros(1,lmu);\nend\n\nfit.a0 = a0;\nfit.beta = beta;\nfit.dev = dev;\nfit.nulldev = dev0;\nfit.df = df';\nfit.lambda = lam;\nfit.npasses = nlp;\nfit.jerr = jerr;\nfit.dim = dd;\nfit.offset = is_offset;\nfit.class = 'fishnet';\n\n\nfunction new_lam = fix_lam(lam)\n\nnew_lam = lam;\nif (length(lam) > 2)\n llam=log(lam);\n new_lam(1)=exp(2*llam(2)-llam(3));\nend\n\n \n "} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "cvmrelnet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/cvmrelnet.m", "size": 2101, "source_encoding": "utf_8", "md5": "d369fd63346be95c8ff0d36501321ea1", "text": "function result = cvmrelnet(object, lambda, x, y, weights, offset, foldid, ...\n type, grouped, keep)\n\nif nargin < 10 || isempty(keep)\n keep = false;\nend\n\ntypenames = struct('deviance','Mean-Squared Error','mse','Mean-Squared Error',...\n 'mae','Mean Absolute Error');\n\nif strcmp(type,'default')\n type = 'mse';\nend\n\nif ~any(strcmp(type,{'mse','mae','deviance'}))\n warning('Only ''mse'',''deviance'' or ''mae'' available for multiresponse Gaussian models; ''mse'' used');\n type = 'mse';\nend\n\n[nobs, nc] = size(y);\n\nif ~isempty(offset)\n y = y - offset;\nend\n\npredmat = NaN(nobs,nc,length(lambda));\nnfolds = max(foldid);\nnlams = nfolds;\n\nfor i = 1:nfolds\n which = foldid == i;\n fitobj = object{i};\n fitobj.offset = false;\n preds = glmnetPredict(fitobj,x(which,:));\n nlami = length(object{i}.lambda);\n predmat(which,:,1:nlami) = preds;\n nlams(i) = nlami;\nend\nN = nobs - reshape(sum(isnan(predmat(:,1,:)),1),1,[]);\nbigY = repmat(y, [1,1,length(lambda)]);\nswitch type\n case 'mse'\n cvraw = squeeze(sum((bigY - predmat).^2, 2));\n case 'mae'\n cvraw = squeeze(sum(abs(bigY - predmat), 2));\nend\nif (nobs/nfolds < 3) && grouped\n warning('Option grouped=false enforced in cv.glmnet, since < 3 observations per fold');\n grouped = false;\nend\nif (grouped)\n cvob = cvcompute(cvraw, weights, foldid, nlams);\n cvraw = cvob.cvraw;\n weights = cvob.weights;\n N = cvob.N;\nend\n% end\ncvm = wtmean(cvraw,weights);\nsqccv = (bsxfun(@minus,cvraw,cvm)).^2;\ncvsd = sqrt(wtmean(sqccv,weights)./(N-1));\nresult.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type);\nif (keep)\n result.fit_preval = predmat;\nend \n\n\nfunction result = glmnet_softmax(x)\n\nd = size(x);\nnas = any(isnan(x),2);\nif any(nas)\n pclass = NaN(d(1),1);\n if (sum(nas) < d(1))\n pclass2 = glmnet_softmax(x(~nas,:));\n pclass(~nas) = pclass2;\n result = pclass;\n end\nelse\n maxdist = x(:,1);\n pclass = ones(d(1),1);\n for i = 2:d(2)\n l = x(:,i)>maxdist;\n pclass(l) = i;\n maxdist(l) = x(l,i);\n end\n result = pclass;\nend\n\n\n\n"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "cvmultnet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/cvmultnet.m", "size": 2980, "source_encoding": "utf_8", "md5": "245d373006161331bd149a8cc0756fcd", "text": "function result = cvmultnet(object, lambda, x, y, weights, offset, foldid, ...\n type, grouped, keep)\n\nif nargin < 10 || isempty(keep)\n keep = false;\nend\n\ntypenames = struct('mse','Mean-Squared Error','mae','Mean Absolute Error',...\n 'deviance','Multinomial Deviance','class','Misclassification Error');\n\nif strcmp(type,'default')\n type = 'deviance';\nend\n\nif ~any(strcmp(type,{'mse','mae','deviance','class'}))\n warning('Only ''deviance'', ''class'', ''mse'' or ''mae'' available for multinomial models; ''deviance'' used');\n type = 'deviance';\nend\n\nprob_min = 1e-5; prob_max = 1 - prob_min;\nnc = size(y);\nif nc(2) == 1\n [classes,~,sy] = unique(y);\n nc = length(classes);\n indexes = eye(nc);\n y = indexes(sy,:);\nelse\n nc = nc(2);\nend\nis_offset = ~isempty(offset);\npredmat = NaN(size(y,1),nc,length(lambda));\nnfolds = max(foldid);\nnlams = zeros(nfolds,1);\n\nfor i = 1:nfolds\n which = foldid==i;\n fitobj = object{i};\n if (is_offset)\n off_sub = offset(which,:);\n else\n off_sub = [];\n end\n preds = glmnetPredict(fitobj,x(which,:),[],'response',[],off_sub);\n nlami = length(object{i}.lambda);\n predmat(which,:,1:nlami) = preds;\n nlams(i) = nlami;\nend\n\nywt = sum(y, 2);\ny = y ./ repmat(ywt,1,size(y,2));\nweights = weights .* ywt;\nN = size(y,1) - sum(isnan(predmat(:,1,:)),1);\nbigY = repmat(y, [1,1,length(lambda)]);\nswitch type\n case 'mse'\n cvraw = squeeze(sum((bigY - predmat).^2, 2));\n case 'mae'\n cvraw = squeeze(sum(abs(bigY - predmat), 2));\n case 'deviance'\n predmat = min(max(predmat,prob_min),prob_max);\n lp = bigY .* log(predmat);\n ly = bigY .* log(bigY);\n ly(bigY == 0) = 0;\n cvraw = squeeze(sum(2 * (ly - lp), 2));\n case 'class'\n classid = NaN(size(y,1),length(lambda));\n for i = 1:length(lambda)\n classid(:,i) = glmnet_softmax(predmat(:,:,i));\n end\n classid = reshape(classid,[],1);\n yperm = reshape(permute(bigY, [1,3,2]),[],nc);\n idx = sub2ind(size(yperm), 1:length(classid), classid');\n cvraw = reshape(1 - yperm(idx), [], length(lambda));\nend\n\nif (grouped)\n cvob = cvcompute(cvraw, weights, foldid, nlams);\n cvraw = cvob.cvraw;\n weights = cvob.weights;\n N = cvob.N;\nend\n\ncvm = wtmean(cvraw,weights);\nsqccv = (bsxfun(@minus,cvraw,cvm)).^2;\ncvsd = sqrt(wtmean(sqccv,weights)./(N-1));\nresult.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type);\nif (keep)\n result.fit_preval = predmat;\nend\n\n\nfunction result = glmnet_softmax(x)\n\nd = size(x);\nnas = any(isnan(x),2);\nif any(nas)\n pclass = NaN(d(1),1);\n if (sum(nas) < d(1))\n pclass2 = glmnet_softmax(x(~nas,:));\n pclass(~nas) = pclass2;\n result = pclass;\n end\nelse\n maxdist = x(:,1);\n pclass = ones(d(1),1);\n for i = 2:d(2)\n l = x(:,i)>maxdist;\n pclass(l) = i;\n maxdist(l) = x(l,i);\n end\n result = pclass;\nend\n \n \n\n\n\n \n\n\n "} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "lognet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/lognet.m", "size": 4177, "source_encoding": "utf_8", "md5": "c749bb59e945862ae7b1962afc11fbfc", "text": "function fit = lognet(x,is_sparse,irs,pcs,y,weights,offset,parm,nobs,nvars,...\n jd,vp,cl,ne,nx,nlam,flmin,ulam,thresh,isd,intr,maxit,kopt,family)\n\n[noo,nc] = size(y);\nif noo ~= nobs\n error('x and y have different number of rows in call to glmnet');\nend\nif nc == 1\n [classes,~,sy] = unique(y);\n nc = length(classes);\n indexes = eye(nc);\n y = indexes(sy,:);\nelse\n classes = 1: nc;\nend\n\nif strcmp(family, 'binomial')\n if nc > 2\n error ('More than two classes; use multinomial family instead');\n end\n nc = 1; % for calling binomial\n y = y(:,[2,1]);\nend\no = [];\nif ~isempty(weights)\n % check if any are zero\n o = weights > 0;\n if ~all(o) %subset the data\n y = y(o,:);\n x = x(o,:);\n weights = weights(o);\n nobs = sum(o);\n else\n o = [];\n end\n [my,ny] = size(y);\n y = y .* repmat(weights,1,ny);\nend\n\nif isempty(offset)\n offset = y * 0;\n is_offset = false;\nelse\n if ~isempty(o)\n offset = offset(o,:);\n end\n do = size(offset);\n if (do(1) ~= nobs)\n error('offset should have the same number of values as observations in binomial/multinomial call to glmnet');\n end\n if (nc == 1)\n if (do(2) == 1)\n offset = cat(2,offset,-offset);\n end\n if (do(2) > 2)\n error('offset should have 1 or 2 columns in binomial call to glmnet');\n end\n end\n if strcmp(family,'multinomial') && (do(2) ~= nc)\n error('offset should have same shape as y in multinomial call to glmnet');\n end\n is_offset = true;\nend\n\nif (is_sparse)\n task = 20;\n [lmu,a0,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,y,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,cl,intr,maxit,nc,kopt,offset,irs,pcs);\nelse\n task = 21;\n [lmu,a0,ca,ia,nin,dev,alm,nlp,jerr,dev0,ot] = glmnetMex(task,parm,x,y,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,cl,intr,maxit,nc,kopt,offset);\nend\n\nif (jerr ~= 0)\n errmsg = err(jerr,maxit,nx,family);\n if (errmsg.fatal)\n error(errmsg.msg);\n else\n warning(errmsg.msg);\n end\nend\n\nninmax = max(nin);\nlam = alm;\nif (ulam == 0.0)\n lam = fix_lam(lam); % first lambda is infinity; changed to entry point\nend\n\nif strcmp(family, 'multinomial')\n beta_list = {};\n a0 = a0 - repmat(mean(a0), nc, 1); %multinomial: center the coefficients\n dfmat=a0;\n dd=[nvars, lmu];\n if ninmax > 0\n ca = reshape(ca, nx, nc, lmu);\n ca = ca(1:ninmax,:,:);\n ja = ia(1:ninmax);\n [ja1,oja] = sort(ja);\n df = any(abs(ca) > 0, 2);\n df = sum(df, 1);\n df = df(:)';\n for k=1:nc\n ca1 = reshape(ca(:,k,:), ninmax, lmu);\n cak = ca1(oja,:);\n dfmat(k,:) = sum(abs(cak) > 0, 1);\n beta = zeros(nvars, lmu);\n beta(ja1,:) = cak;\n beta_list{k} = beta;\n end\n else\n for k = 1:nc\n dfmat(k,:) = zeros(1,lmu);\n beta_list{k} = zeros(nvars, lmu);\n end\n df = zeros(1,lmu);\n end\n fit.a0 = a0;\n fit.label = classes;\n fit.beta = beta_list;\n fit.dev = dev;\n fit.nulldev = dev0;\n fit.dfmat = dfmat;\n fit.df = df';\n fit.lambda = lam;\n fit.npasses = nlp;\n fit.jerr = jerr;\n fit.dim = dd;\n if (kopt == 2)\n grouped = true;\n else\n grouped = false;\n end\n fit.grouped = grouped;\n fit.offset = is_offset;\n fit.class = 'multnet';\n \nelse\n dd=[nvars, lmu];\n if ninmax > 0\n ca = ca(1:ninmax,:);\n df = sum(abs(ca) > 0, 1);\n ja = ia(1:ninmax);\n [ja1,oja] = sort(ja);\n beta = zeros(nvars, lmu);\n beta (ja1, :) = ca(oja,:);\n else\n beta = zeros(nvars,lmu);\n df = zeros(1,lmu);\n end\n fit.a0 = a0;\n fit.label = classes;\n fit.beta = beta; %sign flips make 2 arget class\n fit.dev = dev;\n fit.nulldev = dev0;\n fit.df = df';\n fit.lambda = lam;\n fit.npasses = nlp;\n fit.jerr = jerr;\n fit.dim = dd;\n fit.offset = is_offset;\n fit.class = 'lognet';\nend\n\n\nfunction new_lam = fix_lam(lam)\n\nnew_lam = lam;\nif (length(lam) > 2)\n llam=log(lam);\n new_lam(1)=exp(2*llam(2)-llam(3));\nend\n"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "elnet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/elnet.m", "size": 1671, "source_encoding": "utf_8", "md5": "5e93be0d78726b154d27eed1f02e36be", "text": "function fit = elnet(x, is_sparse, irs, pcs, y, weights, offset, gtype, ...\n parm, lempty, nvars, jd, vp, cl, ne, nx, nlam, flmin, ulam, thresh, ...\n isd, intr, maxit, family)\n\nybar = y' * weights/ sum(weights);\nnulldev = (y' - ybar).^2 * weights;\nka = find(strncmp(gtype,{'covariance','naive'},length(gtype)),1);\nif isempty(ka)\n error('unrecognized type');\nend\n\nif isempty(offset)\n offset = y * 0;\n is_offset = false;\nelse\n is_offset = true;\nend\n\nif is_sparse\n task = 10;\n [lmu,a0,ca,ia,nin,rsq,alm,nlp,jerr] = glmnetMex(task,parm,x,y-offset,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,ka,cl,intr,maxit,irs,pcs);\nelse\n task = 11;\n [lmu,a0,ca,ia,nin,rsq,alm,nlp,jerr] = glmnetMex(task,parm,x,y-offset,jd,vp,ne,nx,nlam,flmin,ulam,thresh,isd,weights,ka,cl,intr,maxit);\n\nend\n \nif (jerr ~= 0)\n errmsg = err(jerr,maxit,nx,family);\n if (errmsg.fatal)\n error(errmsg.msg);\n else\n warning(errmsg.msg);\n end\nend\n\nninmax = max(nin);\nlam = alm;\nif lempty\n lam = fix_lam(lam); % first lambda is infinity; changed to entry point\nend\n\ndd=[nvars, lmu];\nif ninmax > 0\n ca = ca(1:ninmax,:);\n df = sum(abs(ca) > 0, 1);\n ja = ia(1:ninmax);\n [ja1,oja] = sort(ja);\n beta = zeros(nvars, lmu);\n beta (ja1, :) = ca(oja,:);\nelse\n beta = zeros(nvars,lmu);\n df = zeros(1,lmu);\nend\n\nfit.a0 = a0;\nfit.beta = beta;\nfit.dev = rsq;\nfit.nulldev = nulldev;\nfit.df = df';\nfit.lambda = lam;\nfit.npasses = nlp;\nfit.jerr = jerr;\nfit.dim = dd;\nfit.offset = is_offset;\nfit.class = 'elnet';\n\n\nfunction new_lam = fix_lam(lam)\n\nnew_lam = lam;\nif (length(lam) > 2)\n llam=log(lam);\n new_lam(1)=exp(2*llam(2)-llam(3));\nend\n"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "cvcoxnet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/cvcoxnet.m", "size": 2338, "source_encoding": "utf_8", "md5": "eed15cafcfb188d8f0abde603f2b3ee9", "text": "function result = cvcoxnet(object, lambda, x, y, weights, offset, foldid, ...\n type, grouped, keep)\n\n% Internal glmnet function. See also cvglmnet.\n\nif nargin < 10 || isempty(keep)\n keep = false;\nend\n\ntypenames = struct('deviance','Partial Likelihood Deviance');\nif strcmp(type, 'default')\n type = 'deviance';\nend\nif ~any(strcmp(type, {'deviance'}))\n warning('Only ''deviance'' available for Cox models; changed to type=''deviance''');\n type = 'deviance';\nend\n\nif isempty(offset)\n offset = zeros(size(x,1),1);\nend\nnfolds = max(foldid);\n\nif (length(weights)/nfolds < 10) && ~grouped\n warning('Option grouped=true enforced for cv.coxnet, since < 3 observations per fold');\n grouped = true;\nend\ncvraw = NaN(nfolds,length(lambda));\n\nfor i = 1:nfolds\n which = foldid == i;\n fitobj = object{i};\n coefmat = glmnetPredict(fitobj,[],[],'coefficients');\n if (grouped)\n plfull = cox_deviance([],y,x,offset,weights,coefmat);\n plminusk = cox_deviance([],y(~which,:),x(~which,:),offset(~which),...\n weights(~which),coefmat);\n cvraw(i,1:length(plfull)) = plfull - plminusk;\n else\n plk = cox_deviance([],y(which,:),x(which,:),offset(which),...\n weights(which),coefmat);\n cvraw(i,1:length(plk)) = plk;\n end\nend\nstatus = y(:,2);\nN = nfolds - sum(isnan(cvraw),1);\nweights = accumarray(reshape(foldid,[],1),weights.*status);\ncvraw = bsxfun(@rdivide,cvraw,weights); %even some weight = 0 does matter because of adjustment in wtmean!\ncvm = wtmean(cvraw,weights);\nsqccv = (bsxfun(@minus,cvraw,cvm)).^2;\ncvsd = sqrt(wtmean(sqccv,weights)./(N-1));\nresult.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type);\nif (keep)\n warning('keep=TRUE not implemented for coxnet');\nend\n\n\nfunction result = cox_deviance(pred, y, x, offset, weights, beta)\n\nty = y(:,1);\ntevent = y(:,2);\nnobs = length(ty); nvars = size(x,2);\nif isempty(weights)\n weights = ones(nobs,1);\nend\nif isempty(offset)\n offset = zeros(nobs,1);\nend\nif isempty(beta)\n beta = []; nvec = 1; nvars = 0;\nelse\n nvec = size(beta,2);\nend\n\ntask = 42;\n[flog, jerr] = glmnetMex(task,x,ty,tevent,offset,weights,nvec,beta);\n\n\nif (jerr ~= 0)\n errmsg = err(jerr,0,0,'cox');\n if (errmsg.fatal)\n error(errmsg.msg);\n else\n warning(errmsg.msg);\n end\nend\nresult = -2 * flog;"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "cvfishnet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/cvfishnet.m", "size": 1872, "source_encoding": "utf_8", "md5": "d7cb4820ff676ff3db1adcb0418e402f", "text": "function result = cvfishnet(object,lambda,x,y,weights,offset,foldid,type,grouped,keep)\n\n% Internal glmnet function. See also cvglmnet.\n\nif nargin < 10 || isempty(keep)\n keep = false;\nend\n\ntypenames = struct('mse','Mean-Squared Error','mae','Mean Absolute Error','deviance','Poisson Deviance');\nif strcmp(type, 'default')\n type = 'deviance';\nend\nif ~any(strcmp(type, {'mse','mae','deviance'}))\n warning('Only ''mse'', ''deviance'' or ''mae'' available for Poisson models; ''deviance'' used');\n type = 'deviance';\nend\n\nis_offset = ~isempty(offset);\n\npredmat = NaN(length(y),length(lambda));\nnfolds = max(foldid);\nnlams = nfolds;\n\nfor i = 1:nfolds\n which = foldid == i;\n fitobj = object{i};\n if (is_offset)\n off_sub = offset(which);\n else\n off_sub = [];\n end\n preds = glmnetPredict(fitobj,x(which,:),[],[],[],off_sub);\n nlami = length(object{i}.lambda);\n predmat(which,1:nlami) = preds;\n nlams(i) = nlami;\nend\n\nN = size(y,1) - sum(isnan(predmat),1);\n\nyy = repmat(y, 1, length(lambda));\nswitch type\n case 'mse'\n cvraw = (yy - predmat).^2;\n case 'mae'\n cvraw = abs(yy - predmat);\n case 'deviance'\n cvraw = devi(yy, predmat);\nend\n\nif (length(y)/nfolds < 3) && grouped\n warning('Option grouped=false enforced in cv.glmnet, since < 3 observations per fold');\n grouped = false;\nend\n\nif (grouped)\n cvob = cvcompute(cvraw,weights,foldid,nlams);\n cvraw = cvob.cvraw; \n weights = cvob.weights;\n N = cvob.N;\nend\n\ncvm = wtmean(cvraw,weights);\nsqccv = (bsxfun(@minus,cvraw,cvm)).^2;\ncvsd = sqrt(wtmean(sqccv,weights)./(N-1));\n\nresult.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type);\n\nif (keep)\n result.fit_preval = predmat;\nend\n\n\nfunction result = devi(yy, eta)\n\ndeveta = yy .* eta - exp(eta);\ndevy = yy .* log(yy) - yy;\ndevy(yy == 0) = 0;\nresult = 2 * (devy - deveta);"} +{"plateform": "github", "repo_name": "shangjingbo1226/DPPred-master", "name": "cvlognet.m", "ext": ".m", "path": "DPPred-master/glmnet_matlab/cvlognet.m", "size": 4184, "source_encoding": "utf_8", "md5": "265205120a633a060736651a5eee583d", "text": "function result = cvlognet(object, lambda, x, y, weights, offset, foldid, ...\n type, grouped, keep)\n\nif nargin < 10 || isempty(keep)\n keep = false;\nend\n\ntypenames = struct('mse','Mean-Squared Error','mae','Mean Absolute Error',...\n 'deviance','Binomial Deviance','auc','AUC','class','Misclassification Error');\n\nif strcmp(type,'default')\n type = 'deviance';\nend\n\nif ~any(strcmp(type,{'mse','mae','deviance','auc','class'}))\n warning('Only ''deviance'', ''class'', ''auc'', ''mse'' or ''mae'' available for binomial models; ''deviance'' used');\n type = 'deviance';\nend\n\nprob_min = 1e-5; prob_max = 1 - prob_min;\nnc = size(y);\nif nc(2) == 1\n [classes,~,sy] = unique(y);\n nc = length(classes);\n indexes = eye(nc);\n y = indexes(sy,:);\nend\nN = size(y,1);\nnfolds = max(foldid);\nif (N/nfolds < 10) && strcmp(type,'auc')\n warning(strcat('Too few (< 10) observations per fold for type.measure=''auc'' in cv.lognet; ',...\n 'changed to type.measure=''deviance''. Alternatively, use smaller value for nfolds'));\n type = 'deviance';\nend\nif (N/nfolds < 3) && grouped\n warning(strcat('Option grouped=FALSE enforced in cv.glmnet, ',...\n 'since < 3 observations per fold'));\n grouped = false;\nend\nis_offset = ~isempty(offset);\npredmat = NaN(size(y,1),length(lambda));\nnlams = zeros(nfolds,1);\n\nfor i = 1:nfolds\n which = foldid==i;\n fitobj = object{i};\n if (is_offset)\n off_sub = offset(which,:);\n else\n off_sub = []; %a bit different from that in R\n end\n preds = glmnetPredict(fitobj,x(which,:),[],'response',[],off_sub);\n nlami = length(object{i}.lambda);\n predmat(which,1:nlami) = preds;\n nlams(i) = nlami;\nend\n\nif strcmp(type,'auc')\n cvraw = NaN(nfolds, length(lambda));\n good = zeros(nfolds, length(lambda));\n for i = 1:nfolds\n good(i,1:nlams(i)) = 1;\n which = foldid == i;\n for j = 1:nlams(i)\n cvraw(i,j) = auc_mat(y(which,:), predmat(which,j), weights(which));\n end\n end\n N = sum(good,1);\n sweights = zeros(nfolds, 1);\n for i = 1:nfolds\n sweights(i) = sum(weights(foldid==i));\n end\n weights = sweights;\nelse\n ywt = sum(y, 2);\n y = y ./ repmat(ywt,1,size(y,2));\n weights = weights .* ywt;\n N = size(y,1) - sum(isnan(predmat),1);\n yy1 = repmat(y(:,1),1,length(lambda));\n yy2 = repmat(y(:,2),1,length(lambda));\n switch type\n case 'mse'\n cvraw = (yy1 - (1 - predmat)).^2 + (yy2 - (1 - predmat)).^2;\n case 'mae'\n cvraw = abs(yy1 - (1 - predmat)) + abs(yy2 - (1 - predmat));\n case 'deviance'\n predmat = min(max(predmat,prob_min),prob_max);\n lp = yy1.*log(1-predmat) + yy2.*log(predmat);\n ly = log(y);\n ly(y == 0) = 0;\n ly = (y.*ly) * [1;1];\n cvraw = 2 * (repmat(ly,1,length(lambda)) - lp);\n case 'class'\n cvraw = yy1.*(predmat > 0.5) + yy2.*(predmat <= 0.5);\n end\n if (grouped)\n cvob = cvcompute(cvraw, weights, foldid, nlams);\n cvraw = cvob.cvraw;\n weights = cvob.weights;\n N = cvob.N;\n end\nend\ncvm = wtmean(cvraw,weights);\nsqccv = (bsxfun(@minus,cvraw,cvm)).^2;\ncvsd = sqrt(wtmean(sqccv,weights)./(N-1));\nresult.cvm = cvm; result.cvsd = cvsd; result.name = typenames.(type);\nif (keep)\n result.fit_preval = predmat;\nend\n\n\nfunction result = auc_mat(y, prob, weights)\n\nif nargin < 3 || isempty(weights)\n weights = ones(size(y,1),1);\nend\nWeights = bsxfun(@times,weights,y);\nWeights = Weights(:)';\nny = size(y,1);\nY = [zeros(ny,1);ones(ny,1)];\nProb = [prob; prob];\nresult = auc(Y, Prob, Weights);\n\n\nfunction result = auc(y, prob, w)\n\nif isempty(w)\n mindiff = min(diff(unique(prob)));\n pert = unifrnd(0,mindiff/3,size(prob));\n [~,~,rprob] = unique(prob+pert);\n n1 = sum(y); n0 = length(y) - n1;\n u = sum(rprob(y == 1)) - n1*(n1+1)/2;\n result = u / (n1*n0);\nelse\n [~,op] = sort(prob);\n y = y(op); w = w(op);\n cw = cumsum(w);\n w1 = w(y == 1);\n cw1 = cumsum(w1);\n wauc = sum(w1.*(cw(y==1)-cw1));\n sumw = cw1(length(cw1));\n sumw = sumw * (cw(length(cw)) - sumw);\n result = wauc / sumw;\nend\n \n\n\n "} +{"plateform": "github", "repo_name": "FelixWinterstein/FPGA-shared-mem-master", "name": "generate_data_points.m", "ext": ".m", "path": "FPGA-shared-mem-master/examples/filtering_algorithm/host/data/generate_data_points.m", "size": 2172, "source_encoding": "utf_8", "md5": "deb2eed5cac280eaf68b63d34bd507ca", "text": "%**********************************************************************\n% Felix Winterstein, Imperial College London, 2016\n%\n% File: generate_data_points\n%\n% Revision 1.01\n% Additional Comments: distributed under an Apache-2.0 license, see LICENSE\n%\n%**********************************************************************\n\nfunction generate_data_points\n\nclear;\nclc;\n\n\n%% config\nN=2^20;\nD=3;\nK=128;\nKnew =K;\nstd_dev = 0.10;\nM=1;\n\nfractional_bits = 10;\ngbl_seed_offset = 0;\n\nfor file_idx=1:M\n\n %% generate data points\n %rng(16221+gbl_seed_offset);\n rand('seed',16221+gbl_seed_offset+file_idx);\n centres = 5*(rand(K,D)-0.5);\n\n points=zeros(N,D);\n\n for I=1:K\n for II=1:D\n %rng(4567+gbl_seed_offset+10*I+II);\n randn('seed',4567+gbl_seed_offset+10*I+II+file_idx);\n points((I-1)*N/K+1:N/K*I,II) = centres(I,II)+std_dev*randn(N/K,1); \n end\n end\n\n tmp=max([abs(min(points(:,1))),abs(max(points(:,1))),abs(min(points(:,2))),abs(max(points(:,2)))]);\n\n points=points/tmp;\n centres = centres/tmp;\n\n points=round(points*2^fractional_bits);\n centres=round(centres*2^fractional_bits);\n \n %% save data points to file\n tmp_points=reshape(points,D*N,1); % append 2nd dim after 1st dim\n\n fid=fopen(['./data_points','_N',num2str(N),'_K',num2str(K),'_D',num2str(D),'_s',num2str(std_dev,'%.2f'),'.mat'],'w');\n for I=1:D*N\n fprintf(fid,'%d\\n',tmp_points(I));\n end\n fclose(fid); \n\n %% generate new random centres (pick K data points randomly) and save to file\n new_centres = zeros(Knew,D);\n\n %rng(4567+gbl_seed_offset+10000+II);\n rand('seed', 4567+gbl_seed_offset+10000+file_idx);\n new_centres_idx= round(rand(N,1)*N);\n new_centres_idx = new_centres_idx(1:Knew);\n %new_centres = points(new_centres_idx,:);\n\n %tmp_new_centres=reshape(new_centres,D*Knew,1); % append 2nd dim after 1st dim\n\n fid=fopen(['./initial_centers','_N',num2str(N),'_K',num2str(Knew),'_D',num2str(D),'_s',num2str(std_dev,'%.2f'),'_',num2str(file_idx),'.mat'],'w');\n\n for I=1:Knew\n fprintf(fid,'%d\\n',new_centres_idx(I));\n end\n fclose(fid);\nend \n\n\n\n\nend\n"} +{"plateform": "github", "repo_name": "FelixWinterstein/FPGA-shared-mem-master", "name": "generate_data_points.m", "ext": ".m", "path": "FPGA-shared-mem-master/examples/filtering_algorithm_no_svm/host/data/generate_data_points.m", "size": 2172, "source_encoding": "utf_8", "md5": "68f8ffaf55695f8a76b472d1df424125", "text": "%**********************************************************************\n% Felix Winterstein, Imperial College London, 2016\n%\n% File: generate_data_points\n%\n% Revision 1.01\n% Additional Comments: distributed under an Apache-2.0 license, see LICENSE\n%\n%**********************************************************************\n\nfunction generate_data_points\n\nclear;\nclc;\n\n\n%% config\nN=2^10;\nD=3;\nK=128;\nKnew =K;\nstd_dev = 0.10;\nM=1;\n\nfractional_bits = 10;\ngbl_seed_offset = 0;\n\nfor file_idx=1:M\n\n %% generate data points\n %rng(16221+gbl_seed_offset);\n rand('seed',16221+gbl_seed_offset+file_idx);\n centres = 5*(rand(K,D)-0.5);\n\n points=zeros(N,D);\n\n for I=1:K\n for II=1:D\n %rng(4567+gbl_seed_offset+10*I+II);\n randn('seed',4567+gbl_seed_offset+10*I+II+file_idx);\n points((I-1)*N/K+1:N/K*I,II) = centres(I,II)+std_dev*randn(N/K,1); \n end\n end\n\n tmp=max([abs(min(points(:,1))),abs(max(points(:,1))),abs(min(points(:,2))),abs(max(points(:,2)))]);\n\n points=points/tmp;\n centres = centres/tmp;\n\n points=round(points*2^fractional_bits);\n centres=round(centres*2^fractional_bits);\n \n %% save data points to file\n tmp_points=reshape(points,D*N,1); % append 2nd dim after 1st dim\n\n fid=fopen(['./data_points','_N',num2str(N),'_K',num2str(K),'_D',num2str(D),'_s',num2str(std_dev,'%.2f'),'.mat'],'w');\n for I=1:D*N\n fprintf(fid,'%d\\n',tmp_points(I));\n end\n fclose(fid); \n\n %% generate new random centres (pick K data points randomly) and save to file\n new_centres = zeros(Knew,D);\n\n %rng(4567+gbl_seed_offset+10000+II);\n rand('seed', 4567+gbl_seed_offset+10000+file_idx);\n new_centres_idx= round(rand(N,1)*N);\n new_centres_idx = new_centres_idx(1:Knew);\n %new_centres = points(new_centres_idx,:);\n\n %tmp_new_centres=reshape(new_centres,D*Knew,1); % append 2nd dim after 1st dim\n\n fid=fopen(['./initial_centers','_N',num2str(N),'_K',num2str(Knew),'_D',num2str(D),'_s',num2str(std_dev,'%.2f'),'_',num2str(file_idx),'.mat'],'w');\n\n for I=1:Knew\n fprintf(fid,'%d\\n',new_centres_idx(I));\n end\n fclose(fid);\nend \n\n\n\n\nend\n"} +{"plateform": "github", "repo_name": "ewine-project/Flexible-GFDM-PHY-master", "name": "read_ini_file.m", "ext": ".m", "path": "Flexible-GFDM-PHY-master/Host/Reader/read_ini_file.m", "size": 2463, "source_encoding": "utf_8", "md5": "e3cf1e3ecd343ec9b56afbd0fa088639", "text": "function [ini_struct] = read_ini_file(filename)\n\n ini_struct = struct();\n\n if (~exist('filename', 'var'))\n filename = ''; \n end\n\n if isempty(filename)\n [filename, pathname] = uigetfile('*.ini', 'Select a ini file');\n if isequal(filename,0)\n error('User selected Cancel!') \n else\n disp(['User selected ', fullfile(pathname, filename)])\n filename = fullfile(pathname, filename);\n end \n end\n\n fid = fopen(filename);\n cnt = 0;\n \n while (1)\n \n tline = fgetl(fid);\n cnt = cnt + 1;\n \n if (~ischar(tline))\n %End of file\n break;\n end\n \n if (strfind(tline, '#'))\n %skip line because of a comment\n continue;\n end\n \n if (~strfind(tline, '='))\n %skip line because there is nothing to read\n continue;\n end \n \n %Remove whitespace\n tline = strrep(tline, ' ', '');\n \n %Split line in variable and value\n strings = strtrim(strsplit(tline,'='));\n \n if length(strings) ~= 2\n %something is wrong with the line\n disp(['Something is missing in line ' num2str(cnt) ': ' tline]); \n continue; \n end\n \n %Split if array is present\n values = strtrim(strsplit(strings{2},';')); \n \n %Is the first character a string?\n if (isstrprop(values{1,1}, 'alpha'))\n [zeilen, spalten] = size(values);\n if (spalten > 1)\n ini_struct.(strings{1}) = values;\n else\n ini_struct.(strings{1}) = values{1};\n end\n else \n ini_struct.(strings{1}) = string_to_number(values); \n end\n \n end\n\n fclose(fid);\n\nend\n\nfunction number = string_to_number(str)\n\n number = [];\n \n [zeilen, spalten] = size(str);\n\n for i = 1:spalten\n \n value = strtrim(str{:,i});\n %Convert complex number in a similar writing style\n value = strrep(value, 'I', 'i');\n value = strrep(value, 'J', 'j');\n %+i5 doesnt work it has to be +i*5\n value = strrep(value, '+i*', '+i');\n value = strrep(value, '+i', '+i*');\n \n number = [number str2double(value)];\n\n end\n\nend"} +{"plateform": "github", "repo_name": "ewine-project/Flexible-GFDM-PHY-master", "name": "write_ini_file.m", "ext": ".m", "path": "Flexible-GFDM-PHY-master/Host/Reader/write_ini_file.m", "size": 2907, "source_encoding": "utf_8", "md5": "1db51ea5f88734a1e7ea4742f0afe1f1", "text": "function [file_string] = write_ini_file(filename, ini_struct)\n\n if (~exist('filename', 'var'))\n filename = ''; \n end\n \n if (~exist('ini_struct', 'var'))\n error('No data to be saved!') \n end \n\n if isempty(filename)\n [filename, pathname] = uiputfile('*.ini', 'Select a ini file');\n if isequal(filename,0)\n error('User selected Cancel!') \n else\n disp(['User selected ', fullfile(pathname, filename)])\n filename = fullfile(pathname, filename);\n end \n end\n \n %This string is then written into the file\n file_string = {};\n \n if (exist(filename, 'file')) \n %% Update existing file\n\n fid = fopen(filename);\n cnt = 0; \n while (1)\n\n tline = fgetl(fid);\n cnt = cnt + 1;\n\n if (~ischar(tline))\n %End of file\n break;\n end\n\n if (strfind(tline, '#'))\n file_string = {file_string{:} tline};\n %skip line because of a comment \n continue;\n end\n\n if (~strfind(tline, '='))\n file_string = {file_string{:} tline};\n %skip line because there is nothing to read\n continue;\n end \n\n %Remove whitespace\n tline = strrep(tline, ' ', '');\n\n %Split line in variable and value\n strings = strtrim(strsplit(tline,'='));\n\n %this variable exist in our struct?\n if isfield(ini_struct, strings{1}) \n value = ini_struct.(strings{1});\n tline = [strings{1} '=' value_to_string(value)];\n end\n file_string = {file_string{:} tline};\n end\n fclose(fid); \n \n else\n %% Create a new file\n fields = fieldnames(ini_struct);\n for line = 1:numel(fields)\n value = ini_struct.(fields{line});\n file_string = {file_string{:} [fields{line} '=' value_to_string(value)]};\n end\n \n end\n %% (Over-)write string into file\n fileID = fopen(filename, 'w');\n [zeilen, spalten] = size(file_string);\n for i = 1:spalten\n fprintf(fileID,'%s\\r\\n', file_string{i});\n end\n fclose(fileID);\nend\n\nfunction str = value_to_string(value)\n [zeilen,spalten] = size(value);\n str = [];\n if isnumeric(value)\n for i = 1:numel(value)\n str = [str num2str(value(i))];\n if i ~= numel(value)\n str = [str ';'];\n end\n end\n elseif iscellstr(value)\n for i = 1:length(value)\n str = [str value{i}];\n if i ~= numel(value)\n str = [str ';'];\n end \n end\n else\n str = value;\n end\nend"} +{"plateform": "github", "repo_name": "tangzhenyu/Scene-Text-Understanding-master", "name": "predict_depth.m", "ext": ".m", "path": "Scene-Text-Understanding-master/SynthText_Chinese/prep_scripts/predict_depth.m", "size": 3416, "source_encoding": "utf_8", "md5": "f03754d767f958f0bea597bd0c3564cc", "text": "% MATLAB script to regress a depth mask for an image.\n% uses: (1) https://bitbucket.org/fayao/dcnf-fcsp/\n% (2) vlfeat\n% (3) matconvnet\n\n% Author: Ankush Gupta\n\nfunction predict_depth()\n % setup vlfeat\n \n %run( '../libs/vlfeat-0.9.18/toolbox/vl_setup');\n run( '/home/yuz/lijiahui/fayao-dcnf-fcsp/libs/vlfeat-0.9.18/toolbox/vl_setup');\n % setup matconvnet\n % dir_matConvNet='../libs/matconvnet/matlab/';\n dir_matConvNet='/home/yuz/lijiahui/fayao-dcnf-fcsp/libs/matconvnet_20141015/matlab/';\n addpath(genpath(dir_matConvNet));\n run([dir_matConvNet 'vl_setupnn.m']);\n\n opts=[];\n opts.useGpu=false;\n opts.inpaint = true;\n opts.normalize_depth = false; % limit depth to [0,1]\n %opts.imdir = '/path/to/image/dir';\n opts.imdir = '/home/yuz/lijiahui/syntheticdata/SynthText/img_dir';\n %opts.out_h5 = '/path/to/save/output/depth.h5';\n opts.out_h5 = '/home/yuz/lijiahui/syntheticdata/depth.h5';\n % these should point to the pre-trained models from:\n % https://bitbucket.org/fayao/dcnf-fcsp/\n opts.model_file.indoor = '/home/yuz/lijiahui/fayao-dcnf-fcsp/model_trained/model_dcnf-fcsp_NYUD2.mat';\n opts.model_file.outdoor = '/home/yuz/lijiahui/fayao-dcnf-fcsp/model_trained/model_dcnf-fcsp_Make3D.mat';\n\n fprintf('\\nloading trained model...\\n\\n');\n mdl = load(opts.model_file.indoor);\n model.indoor = mdl.data_obj;\n mdl = load(opts.model_file.outdoor);\n model.outdoor = mdl.data_obj;\n\n %if gpuDeviceCount==0\n % fprintf(' ** No GPU found. Using CPU...\\n');\n % opts.useGpu=false;\n %end\n\n imnames = dir(fullfile(opts.imdir),'*');\n imnames = {imnames.name};\n N = numel(imnames);\n for i = 1:N\n fprintf('%d of %d\\n',i,N);\n imname = imnames{i};\n imtype = 'outdoor';\n img = read_img_rgb(fullfile(opts.imdir,imname));\n if strcmp(imtype, 'outdoor')\n opts.sp_size=16;\n opts.max_edge=600;\n elseif strcmp(imtype, 'indoor')\n opts.sp_size=20;\n opts.max_edge=640;\n end\n depth = get_depth(img,model.(imtype),opts);\n save_depth(imname,depth,opts);\n end\nend\n\nfunction save_depth(imname,depth,opts)\n dset_name = ['/',imname];\n h5create(opts.out_h5, dset_name, size(depth), 'Datatype', 'single');\n h5write(opts.out_h5, dset_name, depth);\nend\n\nfunction depth = get_depth(im_rgb,model,opts)\n % limit the maximum edge size of the image:\n if ~isempty(opts.max_edge)\n sz = size(im_rgb);\n [~,max_dim] = max(sz(1:2));\n osz = NaN*ones(1,2);\n osz(max_dim) = opts.max_edge;\n im_rgb = imresize(im_rgb, osz);\n end\n\n % do super-pixels:\n fprintf(' > super-pix\\n');\n supix = gen_supperpixel_info(im_rgb, opts.sp_size);\n pinfo = gen_feature_info_pairwise(im_rgb, supix);\n\n % build \"data-set\":\n ds=[];\n ds.img_idxes = 1;\n ds.img_data = im_rgb;\n ds.sp_info{1} = supix;\n ds.pws_info = pinfo;\n ds.sp_num_imgs = supix.sp_num;\n % run cnn:\n fprintf(' > CNN\\n');\n depth = do_model_evaluate(model, ds, opts);\n\n if opts.inpaint\n fprintf(' > inpaint\\n');\n depth = do_inpainting(depth, im_rgb, supix);\n end\n\n if opts.normalize_depth\n d_min = min(depth(:));\n d_max = max(depth(:));\n depth = (depth-d_min) / (d_max-d_min);\n depth(depth<0) = 0;\n depth(depth>1) = 1;\n end\nend\n\npredict_depth()\n"} +{"plateform": "github", "repo_name": "tangzhenyu/Scene-Text-Understanding-master", "name": "classification_demo.m", "ext": ".m", "path": "Scene-Text-Understanding-master/ctpn_crnn_ocr/CTPN/caffe/matlab/demo/classification_demo.m", "size": 5412, "source_encoding": "utf_8", "md5": "8f46deabe6cde287c4759f3bc8b7f819", "text": "function [scores, maxlabel] = classification_demo(im, use_gpu)\n% [scores, maxlabel] = classification_demo(im, use_gpu)\n%\n% Image classification demo using BVLC CaffeNet.\n%\n% IMPORTANT: before you run this demo, you should download BVLC CaffeNet\n% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)\n%\n% ****************************************************************************\n% For detailed documentation and usage on Caffe's Matlab interface, please\n% refer to Caffe Interface Tutorial at\n% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab\n% ****************************************************************************\n%\n% input\n% im color image as uint8 HxWx3\n% use_gpu 1 to use the GPU, 0 to use the CPU\n%\n% output\n% scores 1000-dimensional ILSVRC score vector\n% maxlabel the label of the highest score\n%\n% You may need to do the following before you start matlab:\n% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64\n% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6\n% Or the equivalent based on where things are installed on your system\n%\n% Usage:\n% im = imread('../../examples/images/cat.jpg');\n% scores = classification_demo(im, 1);\n% [score, class] = max(scores);\n% Five things to be aware of:\n% caffe uses row-major order\n% matlab uses column-major order\n% caffe uses BGR color channel order\n% matlab uses RGB color channel order\n% images need to have the data mean subtracted\n\n% Data coming in from matlab needs to be in the order\n% [width, height, channels, images]\n% where width is the fastest dimension.\n% Here is the rough matlab for putting image data into the correct\n% format in W x H x C with BGR channels:\n% % permute channels from RGB to BGR\n% im_data = im(:, :, [3, 2, 1]);\n% % flip width and height to make width the fastest dimension\n% im_data = permute(im_data, [2, 1, 3]);\n% % convert from uint8 to single\n% im_data = single(im_data);\n% % reshape to a fixed size (e.g., 227x227).\n% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');\n% % subtract mean_data (already in W x H x C with BGR channels)\n% im_data = im_data - mean_data;\n\n% If you have multiple images, cat them with cat(4, ...)\n\n% Add caffe/matlab to you Matlab search PATH to use matcaffe\nif exist('../+caffe', 'dir')\n addpath('..');\nelse\n error('Please run this demo from caffe/matlab/demo');\nend\n\n% Set caffe mode\nif exist('use_gpu', 'var') && use_gpu\n caffe.set_mode_gpu();\n gpu_id = 0; % we will use the first gpu in this demo\n caffe.set_device(gpu_id);\nelse\n caffe.set_mode_cpu();\nend\n\n% Initialize the network using BVLC CaffeNet for image classification\n% Weights (parameter) file needs to be downloaded from Model Zoo.\nmodel_dir = '../../models/bvlc_reference_caffenet/';\nnet_model = [model_dir 'deploy.prototxt'];\nnet_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];\nphase = 'test'; % run with phase test (so that dropout isn't applied)\nif ~exist(net_weights, 'file')\n error('Please download CaffeNet from Model Zoo before you run this demo');\nend\n\n% Initialize a network\nnet = caffe.Net(net_model, net_weights, phase);\n\nif nargin < 1\n % For demo purposes we will use the cat image\n fprintf('using caffe/examples/images/cat.jpg as input image\\n');\n im = imread('../../examples/images/cat.jpg');\nend\n\n% prepare oversampled input\n% input_data is Height x Width x Channel x Num\ntic;\ninput_data = {prepare_image(im)};\ntoc;\n\n% do forward pass to get scores\n% scores are now Channels x Num, where Channels == 1000\ntic;\n% The net forward function. It takes in a cell array of N-D arrays\n% (where N == 4 here) containing data of input blob(s) and outputs a cell\n% array containing data from output blob(s)\nscores = net.forward(input_data);\ntoc;\n\nscores = scores{1};\nscores = mean(scores, 2); % take average scores over 10 crops\n\n[~, maxlabel] = max(scores);\n\n% call caffe.reset_all() to reset caffe\ncaffe.reset_all();\n\n% ------------------------------------------------------------------------\nfunction crops_data = prepare_image(im)\n% ------------------------------------------------------------------------\n% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that\n% is already in W x H x C with BGR channels\nd = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');\nmean_data = d.mean_data;\nIMAGE_DIM = 256;\nCROPPED_DIM = 227;\n\n% Convert an image returned by Matlab's imread to im_data in caffe's data\n% format: W x H x C with BGR channels\nim_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR\nim_data = permute(im_data, [2, 1, 3]); % flip width and height\nim_data = single(im_data); % convert from uint8 to single\nim_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data\nim_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)\n\n% oversample (4 corners, center, and their x-axis flips)\ncrops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');\nindices = [0 IMAGE_DIM-CROPPED_DIM] + 1;\nn = 1;\nfor i = indices\n for j = indices\n crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);\n crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);\n n = n + 1;\n end\nend\ncenter = floor(indices(2) / 2) + 1;\ncrops_data(:,:,:,5) = ...\n im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);\ncrops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);\n"} +{"plateform": "github", "repo_name": "karthik-kk/Autoware-master", "name": "velCapture.m", "ext": ".m", "path": "Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/velCapture.m", "size": 1047, "source_encoding": "utf_8", "md5": "994f8bb886b3e3ebef61b89d3c9c00a9", "text": "% Function to capture catvehicle velocity and plotting live graph\nfunction velCapture(ROS_IP, roboname)\n%If number of argument is not two, flag message and exit.\nif nargin < 2\n disp('Uage: velocityProfiler(192.168.0.32, catvehicle)');\n return;\nend\nclose all;\n%rosshutdown;\nmodelname = strcat('/',roboname);\n%Connect to ROS master\nmaster_uri= strcat('http://',ROS_IP);\nmaster_uri = strcat(master_uri,':11311');\n%rosinit(master_uri);\n\n%get handle for /catvehicle/vel topic for subscribing to the data\nspeedsub = rossubscriber(strcat(modelname,'/vel'));\ndt = datestr(now,'mmmm-dd-yyyy-HH-MM-SS');\nsprintf('Velocity capture starts at %s',dt)\n\nt = 0:0.05:50;\noutput = zeros(length(t),1);\nfigure;\ngrid on;\ntitle('Velocity [m/s]');\nfor i = 1:length(t)\n speedata = receive(speedsub,10);\n output(i) = speedata.Linear.X;\n \n plot([max(i-1,1),i], output([max(i-1,1),i]),'b-');\n hold on;\n drawnow; \nend\ndt = datestr(now,'mmmm-dd-yyyy-HH-MM-SS');\nfile = strcat(dt,'.mat');\n save(file, 'output');\ngrid on;\ntitle('Velocity [m/s]');\nend\n"} +{"plateform": "github", "repo_name": "karthik-kk/Autoware-master", "name": "profileByMatrix.m", "ext": ".m", "path": "Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/profileByMatrix.m", "size": 1840, "source_encoding": "utf_8", "md5": "f81181e46cb60adc3466c4779083ce0d", "text": "%Implementation of follower algorithm\n\n%Developed by Rahul Kumar Bhadani \n\n%ROS_IP = IP Address of ROS Master\n%lead = name of the model of leader AV Car\n%follower = name of the model of follower car\n\nfunction profileByMatrix(ROS_IP, roboname, vel_input, time_input, tire_angle)\n\n\n\n%If number of argument is not two, flag message and exit.\nif nargin < 4\n sprintf('Uage: velocityProfiler(192.168.0.32, catvehicle, velmatfile, timematfile)');\n return;\nend\n\nif nargin < 5\n tire_angle = 0.0;\nend\nrosshutdown;\nclose all;\nmodelname = strcat('/',roboname);\n%Connect to ROS master\nmaster_uri= strcat('http://',ROS_IP);\nmaster_uri = strcat(master_uri,':11311');\nrosinit(master_uri);\n\n%get handle for /catvehicle/cmd_vel topic for publishing the data\nvelpub = rospublisher(strcat(modelname,'/cmd_vel'),rostype.geometry_msgs_Twist);\n\n%get handle for /catvehicle/vel topic for subscribing to the data\nspeedsub = rossubscriber(strcat(modelname,'/vel'));\n\nvmat = load(vel_input);\ntmat = load(time_input);\nt = tmat.t;\n%Velocity profile\ninput = vmat.Vel;\n%Velocity profile will be sine\n%input = abs(2*sin(t));\n\n%Variable to store output velocity\noutput = zeros(length(t),1);\n\n%handle for rosmessage object for velpub topic\nvelMsgs = rosmessage(velpub);\nfor i=1:length(t)\n velMsgs.Linear.X = input(i);\n velMsgs.Angular.Z = tire_angle;\n %Publish on the topic /catvehicle/cmd_vel\n send(velpub, velMsgs);\n %Read from the topic /catvehicle/speed\n speedata = receive(speedsub,10);\n output(i) = speedata.Linear.X;\n pause(0.1);\n if i == 3000\n break;\n end\nend\n\n%Plot the input and output velocity profile\n[n, p] = size(output);\nT = 1:n;\nplot(T, input');\nhold on;\nplot(T, output);\ntitle('Original Data');\nlegend('Input function', 'Output response');\ngrid on;\n\nsave input.mat input output\n"} +{"plateform": "github", "repo_name": "karthik-kk/Autoware-master", "name": "velocityProfiler.m", "ext": ".m", "path": "Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/velocityProfiler.m", "size": 1758, "source_encoding": "utf_8", "md5": "d12bb47043d421e21fc4fd4fa8ce4b02", "text": "%Matlab scripto to publish velocity on /catvehicle/cmd_vel topic and\n%subscribe to catvehicle/speed topic\n\n%Developed by Rahul Kumar Bhadani \n\n%ROS_IP = IP Address of ROS Master\n%roboname = name of the model\nfunction velocityProfiler(ROS_IP, roboname, tire_angle)\n\n\n%If number of argument is not two, flag message and exit.\nif nargin < 2\n sprintf('Uage: velocityProfiler(192.168.0.32, catvehicle)');\n return;\nend\n\nif nargin < 3\n tire_angle = 0.0;\nend\nrosshutdown;\nclose all;\nmodelname = strcat('/',roboname);\n%Connect to ROS master\nmaster_uri= strcat('http://',ROS_IP);\nmaster_uri = strcat(master_uri,':11311');\nrosinit(master_uri);\n\n%get handle for /catvehicle/cmd_vel topic for publishing the data\nvelpub = rospublisher(strcat(modelname,'/cmd_vel'),rostype.geometry_msgs_Twist);\n\n%get handle for /catvehicle/vel topic for subscribing to the data\nspeedsub = rossubscriber(strcat(modelname,'/vel'));\n\n%Discretize timestamp\nt = 0:0.01:150;\nv1 = 3;\nv2 = 6;\nv3 = 0;\n\n%Velocity profile\ninput = v1.*(t<50) + v2.*(t>=50).*(t<100) + v3.*(t>= 100);\n\n%Velocity profile will be sine\n%input = abs(2*sin(t));\n\n%Variable to store output velocity\noutput = zeros(length(t),1);\n\n%handle for rosmessage object for velpub topic\nvelMsgs = rosmessage(velpub);\nfor i=1:length(t)\n velMsgs.Linear.X = input(i);\n velMsgs.Angular.Z = tire_angle;\n %Publish on the topic /catvehicle/cmd_vel\n send(velpub, velMsgs);\n %Read from the topic /catvehicle/speed\n speedata = receive(speedsub,10);\n output(i) = speedata.Linear.X;\nend\n\n%Plot the input and output velocity profile\n[n, p] = size(output);\nT = 1:n;\nplot(T, input');\nhold on;\nplot(T, output);\ntitle('Original Data');\nlegend('Input function', 'Output response');\ngrid on;\n"} +{"plateform": "github", "repo_name": "karthik-kk/Autoware-master", "name": "follower_profile.m", "ext": ".m", "path": "Autoware-master/ros/src/system/gazebo/catvehicle/matlab files/follower_profile.m", "size": 2381, "source_encoding": "utf_8", "md5": "ea7d00e67f5e7709a2cd7287216af4af", "text": "%Implementation of follower algorithm\n\n%Developed by Rahul Kumar Bhadani \n\n%ROS_IP = IP Address of ROS Master\n%lead = name of the model of leader AV Car\n%follower = name of the model of follower car\n\nfunction follower_profile(ROS_IP, lead, follower)\n\n%If number of argument is not two, flag message and exit.\nif nargin < 2\n sprintf('Usage: velocityProfiler(192.168.0.32, catvehicle)');\n return;\nend\n\nrosshutdown;\nclose all;\nmodelname1 = strcat('/',lead);\nmodelname2 = strcat('/',follower);\n%Connect to ROS master\nmaster_uri= strcat('http://',ROS_IP);\nmaster_uri = strcat(master_uri,':11311');\nrosinit(master_uri);\n\n%get handle for cmd_vel topic for publishing the data\nvelpub1 = rospublisher(strcat(modelname1,'/cmd_vel'),rostype.geometry_msgs_Twist);\nvelpub2 = rospublisher(strcat(modelname2,'/cmd_vel'),rostype.geometry_msgs_Twist);\n\n%get handle for speed topic for subscribing to the data\nspeedsub1 = rossubscriber(strcat(modelname1,'/vel'));\nspeedsub2 = rossubscriber(strcat(modelname2,'/vel'));\n\n%get handle for /DistanceEstimator\ndistanceEstimaterSub = rossubscriber('/DistanceEstimator/dist');\n\n%Discretize timestamp\nt = 0:0.05:150;\nv1 = 3;\nv2 = 6;\nv3 = 0;\n\n%Velocity profile\ninput = v1.*(t<50) + v2.*(t>=50).*(t<100) + v3.*(t>= 100);\n\n%Velocity profile will be sine\n%input = abs(2*sin(t));\n\n%Variable to store output velocity\noutput1 = zeros(length(t),1);\noutput2 = zeros(length(t),1);\n\n%handle for rosmessage object for velpub topic\nvelMsgs1 = rosmessage(velpub1);\nvelMsgs2 = rosmessage(velpub2);\nfor i=1:length(t)\n velMsgs1.Linear.X = input(i);\n velMsgs1.Angular.Z = 0.0;\n %Publish on the topic /catvehicle/cmd_vel\n send(velpub1, velMsgs1);\n %Read from the topic /catvehicle/speed\n speedata1 = receive(speedsub1,10);\n distance = receive(distanceEstimaterSub,10);\n x = distance.Data;\n \n %Follower control rule\n velMsgs2.Linear.X = (1/30.*x + 2/3).*speedata1.Linear.X;\n velMsgs2.Angular.Z = 0.0;\n send(velpub2, velMsgs2);\n speedata2 = receive(speedsub2,10);\n output1(i) = speedata1.Linear.X;\n output2(i) = speedata2.Linear.X;\nend\n\n%Plot the input and output velocity profile\n[n, p] = size(output1);\nT = 1:n;\nplot(T, input');\nhold on;\nplot(T, output1);\nplot(T, output2);\ntitle('Original Data');\nlegend('Input function', 'Output response of lead','Output response of follower');\ngrid on;\n"} +{"plateform": "github", "repo_name": "karthik-kk/Autoware-master", "name": "plotDisvout.m", "ext": ".m", "path": "Autoware-master/ros/src/system/gazebo/catvehicle/simulink/plotDisvout.m", "size": 241, "source_encoding": "utf_8", "md5": "241fa676f6444e00a60b8c69a5e19efd", "text": "% Author: Jonathan Sprinkle\n% plots the distance outputs from a data file\n\nfunction plotData( timeseries )\n\n% this timeseries is what we have\nfigure\nhold on\nplot(timeseries.Data);\nplot(timeseries.uVelOut);\nlegend({'Distance','VelOut'});\n\nend"} +{"plateform": "github", "repo_name": "karthik-kk/Autoware-master", "name": "plotData.m", "ext": ".m", "path": "Autoware-master/ros/src/system/gazebo/catvehicle/simulink/plotData.m", "size": 350, "source_encoding": "utf_8", "md5": "17951edcd31fa9c02deeb1c49a2e0d7b", "text": "% Author: Jonathan Sprinkle\n% plots the distance outputs from a data file\n\nfunction plotData( timeseries )\n\n% this timeseries is what we have\nfigure\nhold on\nplot(timeseries.dist);\nplot(timeseries.velConverted);\nplot(timeseries.vdot);\nplot(timeseries.vout);\nplot(timeseries.uTireAngle);\nlegend({'dist','velConverted','vdot','vout','uTireAngle'});\n\nend"} +{"plateform": "github", "repo_name": "karthik-kk/Autoware-master", "name": "plotDistances.m", "ext": ".m", "path": "Autoware-master/ros/src/system/gazebo/catvehicle/simulink/plotDistances.m", "size": 288, "source_encoding": "utf_8", "md5": "c0779b1561faff69c733c5ec8a3a9ac7", "text": "% Author: Jonathan Sprinkle\n% plots the distance outputs from a data file\n\nfunction plotDistances\nload distances.mat\n% this timeseries is what we have\nfigure\nhold on\nplot(DistanceEstimator.Data__signal_1_);\nplot(DistanceEstimator.Data__signal_2_);\nlegend({'Distance','Angle (rad)'});\n\nend"} +{"plateform": "github", "repo_name": "rohinkumarreddy/Iris-Detection-master", "name": "hamdist.m", "ext": ".m", "path": "Iris-Detection-master/hamdist.m", "size": 710, "source_encoding": "utf_8", "md5": "bc94aff9c7917be49e3bb10e78a5e3e4", "text": "\r\nfunction hd = hamdist(template1, template2, scales)\r\n\r\ntemplate1 = logical(template1);\r\n\r\ntemplate2 = logical(template2);\r\n\r\nhd = NaN;\r\n\r\n% shift template left and right, use the lowest Hamming distance\r\nfor shifts=-8:8\r\n \r\n template1s = shiftbits(template1, shifts,scales);\r\n \r\n totalbits = (size(template1s,1)*size(template1s,2));\r\n \r\n C = xor(template1s,template2);\r\n \r\n bitsdiff = sum(sum(C==1));\r\n \r\n if totalbits == 0\r\n \r\n hd = NaN;\r\n \r\n else\r\n \r\n hd1 = bitsdiff / totalbits;\r\n \r\n \r\n if hd1 < hd || isnan(hd)\r\n \r\n hd = hd1;\r\n \r\n end\r\n \r\n \r\n end\r\n \r\nend"} +{"plateform": "github", "repo_name": "YasaraPeiris/MNIST_Clusters-master", "name": "predict.m", "ext": ".m", "path": "MNIST_Clusters-master/TestMNIST/MatlabCodes/predict.m", "size": 1720, "source_encoding": "utf_8", "md5": "b06e9988934fa4b78b42512d26371e90", "text": "function predict(layerset, dataSize)\n\nglobal weights numLayers layers;\n\nlayers = [784, layerset, 10];\n[~, numLayers] = size(layers);\n\nimages = loadTrainImages();\nlabels = loadTrainLabels();\n\nselected = find(labels == 5 | labels == 1);\nlabels = labels(selected);\nimages = images(:, selected);\n\n[~, c] = size(images);\ndataSize = min(c, dataSize);\n\niterations = dataSize;\n\ntestLabels = [];\nclusters = [];\n\nresults = cell(numLayers);\n\nloadWeights();\np = 0.3;\n\nunclassified = 0;\n\nfor r = 1 : iterations\n \n results{1} = normc(mat2gray(images(:, r)));\n \n %results{1} = sigmf(mat2gray(images(:, r)), [5.0 0.5]);\n \n for k = 1 : numLayers - 1\n \n results{k + 1} = normc(weights{k} * results{k});\n \n %results{k + 1} = sigmf(weights{k} * results{k}, [5.0 0.5]);\n \n end\n \n [m, i] = max(results{numLayers});\n if(m >= p)\n testLabels = [testLabels; labels(r)];\n clusters = [clusters; i];\n else\n unclassified = unclassified + 1;\n end\n\n %{\n temp = [temp, [results{numLayers} ; ones(3, 1)]];\n c = c + 1;\n\n if mod(c, 100) == 0\n disp(c);\n picMap = [picMap ; temp];\n temp = [];\n c = 0;\n end\n %} \n \nend\n\nplotPerformance([1 : iterations]', [], testLabels, clusters, [2, 3]);\n\ndisp(['Unclassified: ', int2str(unclassified), ' out of ', int2str(dataSize)]);\n\n\nfunction loadWeights()\n\nglobal weights layers;\n\nfileName = sprintf('%d_', layers);\nfileName = strcat(fileName(1 : end - 1), '.mat');\nfileName = fullfile(fileparts(which(mfilename)), '..\\WeightDatabase\\Temp', fileName);\n\nif exist(fileName, 'file') == 2\n load(fileName, 'weights');\nelse\n disp('Trained network not available');\n exit;\nend"} +{"plateform": "github", "repo_name": "YasaraPeiris/MNIST_Clusters-master", "name": "trainModel_yas.m", "ext": ".m", "path": "MNIST_Clusters-master/TestMNIST/MatlabCodes/trainModel_yas.m", "size": 1924, "source_encoding": "utf_8", "md5": "6c4950f15dc3468e591c1a2c5aab6d28", "text": "\nfunction trainModel_yas(layerset, dataSize) % Using Oja's rule\n\ntrainingRatio = 0.8;\np = 0;\n\nimages = loadTrainImages();\nlabels = loadTrainLabels();\n\n\nselected = find(labels == 0 | labels == 1 );\nlabels = labels(selected);\nimages = images(:, selected');\n\n[~, c] = size(images);\n\ndataSize = min(c, dataSize);\niterations = dataSize;\n\nimage_batch = 10;\n\nnewIterations = fix(iterations/image_batch);\ntestLabels = [];\nclusters = [];\n\ntrainingSize = floor(double(dataSize) * trainingRatio)/image_batch;\n\nunclassified = 0;\nnorms = [];\n\nupdateTime = 0.0;\n\nnet = Network_new([784, layerset, 2]);\nnumLayers = net.numLayers;\ntempW = net.feedforwardConnections;\n%tempW = net.lateralConnections;\ntemp = net.feedforwardConnections;\n\nfor r= 1:newIterations\n images_new = [];\n for k=1:image_batch\n \n image_id = image_batch*(r-1)+k;\n images_new = [images_new mat2gray(images(:, image_id))];\n \n end\n \n results = net.getOutput(images_new,r);\n \n if(r > trainingSize)\n \n for u=1:image_batch\n \n image_id = image_batch*(r-1)+u;\n [m, i] = max(results{numLayers}(:,u));\n testLabels = [testLabels; labels(image_id)];\n clusters = [clusters; i];\n \n end\n \n end\n \n time = tic;\n net.STDP_update(results,r);\n updateTime = updateTime + toc(time);\n for u = 1 : image_batch\n \n norms = [norms; zeros(1, numLayers - 1)];\n \n weights = net.feedforwardConnections;\n \n for k = 1 : numLayers - 1\n \n norms(end, k) = norm(weights{k}(:,u) - tempW{k}(:,u),'fro') / numel(weights{k}(:,u));\n tempW{k}(:,u) = weights{k}(:,u);\n \n end\n \n end\nend\n\n\nplotPerformance([1 : iterations]', norms, testLabels, clusters, [1, 2, 3]);\n\nshowFinalImage(abs(weights{1} - temp{1}));\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "danielemarinazzo/GC_SS_PNAS-master", "name": "InstModelfilter.m", "ext": ".m", "path": "GC_SS_PNAS-master/InstModelfilter.m", "size": 2343, "source_encoding": "utf_8", "md5": "9ec58f552064a96d14d59ba96f833baf", "text": "%% realization of the instantaneous model : U = L*W\r\n%%% OUTPUT\r\n% U: N*M matrix of filtered noises\r\n\r\n% INPUT\r\n% N data length\r\n% C: input covariance matrix (may be interpreted as Su or Sw, see above)\r\n% B0: M*M matrix of instantaneous effects (when relevant)\r\n\r\n% when flag='StrictlyCausal':\r\n% given Su, applies Cholesky decomposition to find L and Sw\r\n% then generates U = L*W, for a realization of gaussian W of variance Sw\r\n\r\n% when flag='ExtendedGauss':\r\n% given Sw and B(0), computes L=[I-B(0)]^(-1)\r\n% then generates U = L*W, for a realization of gaussian W of variance Sw\r\n\r\n% when flag='ExtendedNonGauss':\r\n% given Swand B(0), computes L=[I-B(0)]^(-1)\r\n% then generates U = L*W, for a realization of nongaussian W of variance Sw\r\n\r\n\r\nfunction U=InstModelfilter(N,C,flag,B0)\r\n\r\nerror(nargchk(3,4,nargin));%min and max input arguments\r\n\r\n\r\nM=size(C,1);\r\n\r\n\r\nswitch flag\r\ncase {'StrictlyCausal'} % C is Su\r\n [L,Sw]=choldiag(C);\r\n W = randn(M,N); % W independent and gaussian\r\n for m=1:M % This normalizes W to have the appropriate variance (and zero mean)\r\n W(m,:)=sqrt(Sw(m,m))*(W(m,:)-mean(W(m,:)))/std(W(m,:));\r\n end\r\n U=L*W;\r\n \r\ncase {'ExtendedGauss'} % C is Sw\r\n invL=eye(M)-B0;\r\n if det(invL)==0, error('B0 is not invertible, ill-conditioned problem!'), end;\r\n L=inv(invL);\r\n W = randn(M,N); % W independent and gaussian\r\n for m=1:M % This normalizes W to have the appropriate variance (and zero mean)\r\n W(m,:)=sqrt(C(m,m))*(W(m,:)-mean(W(m,:)))/std(W(m,:));\r\n end\r\n U=L*W;\r\n \r\ncase {'ExtendedNonGauss'} % C is Sw\r\n invL=eye(M)-B0;\r\n if det(invL)==0, error('B0 is not invertible, ill-conditioned problem!'), end;\r\n L=inv(invL);\r\n %note: here we generate W independent but non-Gaussian\r\n % Nonlinearity exponent, selected to lie in [0.5, 0.8] or [1.2, 2.0]. (<1 gives subgaussian, >1 gives supergaussian)\r\n q = rand(M,1)*1.1+0.5; \r\n ind = find(q>0.8); \r\n q(ind) = q(ind)+0.4; \r\n % This generates the disturbance variables, which are mutually independent, and non-gaussian\r\n W = randn(M,N);\r\n W = sign(W).*(abs(W).^(q*ones(1,N)));\r\n % This normalizes the disturbance variables to have the appropriate scales\r\n W = W./( ( sqrt(mean((W').^2)') ./ sqrt(diag(C)) )*ones(1,N) );\r\n U=L*W; \r\n \r\nend\r\n"} +{"plateform": "github", "repo_name": "danielemarinazzo/GC_SS_PNAS-master", "name": "MVARfilter.m", "ext": ".m", "path": "GC_SS_PNAS-master/MVARfilter.m", "size": 614, "source_encoding": "utf_8", "md5": "0290e5ff7f6435096eed5fecafbf75e9", "text": "%% FILTER A VECTOR NOISE WITH A SPECIFIED STRICTLY CAUSAL MVAR MODEL: Y(n)=A(1)Y(n-1)+...+A(p)Y(n-p)+U(n)\r\n\r\n%%% INPUT\r\n% A=[A(1)...A(p)]: M*pM matrix of the MVAR model coefficients (strictly causal model)\r\n% U: M*N matrix of innovations\r\n\r\n%%% OUTPUT\r\n% Y: M*N matrix of simulated time series\r\n\r\nfunction [Y]=MVARfilter(A,U)\r\n\r\nN=length(U);\r\nM=size(A,1);\r\np=size(A,2)/M;\r\n\r\n% Y(n)=A(1)Y(n-1)+...+A(p)Y(n-p)+U(n)\r\nY=zeros(M,N);\r\nfor n=1:N\r\n for k=1:p\r\n if n-k<=0, break; end; % if n<=p, stop when k>=n\r\n Y(:,n)=Y(:,n) + ( A(:,(k-1)*M+(1:M)) * Y(:,n-k) );\r\n end\r\n Y(:,n)=Y(:,n)+U(:,n);\r\nend\r\n"} +{"plateform": "github", "repo_name": "danielemarinazzo/GC_SS_PNAS-master", "name": "varma2iss.m", "ext": ".m", "path": "GC_SS_PNAS-master/varma2iss.m", "size": 1206, "source_encoding": "utf_8", "md5": "200c8d913b3e3fe6f30cf6228c4453c9", "text": "%% VARMA with B0 term to (Innovations form) State Space parameters\r\n% computes innovations form parameters for a state space model from VARMA\r\n% parameters using Aoki's method - this version allows for zero-lag MA coefficients\r\n\r\nfunction [A,C,K,R,lambda0] = varma2iss(Am,Bm,V,B0)\r\n\r\n% INPUT: VARMA parameters Am, Bm, V=cov(U)\r\n% OUTPUT: innovations form SS parameters A, C, K, R\r\n\r\n%%%%% internal test\r\n%variables to be passed are Am, Bm, B0, V=Su\r\n% clear; close all; clc;\r\n% Am=[0.9 0 0 0.5; 0 0.6 0.2 0];\r\n% Bm=[0.5 0; 0 0.5]; B0=Bm./5;\r\n% V=eye(2);\r\n% \r\nM = size(Am,1); %dimension of observed process\r\np=floor(size(Am,2)/M); %number of AR lags\r\nq=floor(size(Bm,2)/M); %number of MA lags\r\n\r\nL=M*(p+q); % dimension of state process (SS order)\r\n\r\nC=[Am Bm];\r\nR=B0*V*B0';\r\n\r\nIp=eye(M*p);\r\nIq=eye(M*q);\r\nA11=[Am;Ip(1:end-M,:)];\r\n\r\nif q==0\r\n A=A11;\r\n K=[eye(M); zeros(M*(p-1),M)];\r\nelse\r\n A12=[Bm;zeros(M*(p-1),M*q)];\r\n A21=zeros(M*q,M*p);\r\n A22=[zeros(M,M*q); Iq(1:end-M,:)];\r\n A=[A11 A12; A21 A22];\r\n\r\n K=[eye(M); zeros(M*(p-1),M); inv(B0); zeros(M*(q-1),M)];\r\nend\r\n\r\n\r\n% determine the variance of the process lambda0=E[Yn Yn']\r\nO=dlyap(A,K*R*K');\r\nlambda0=C*O*C'+R;\r\n\r\nend\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "danielemarinazzo/GC_SS_PNAS-master", "name": "idMVAR.m", "ext": ".m", "path": "GC_SS_PNAS-master/idMVAR.m", "size": 1446, "source_encoding": "utf_8", "md5": "02db6f116c8164266a38371b50da5231", "text": "%% IDENTIFICATION OF STRICTLY CAUSAL MVAR MODEL: Y(n)=A(1)Y(n-1)+...+A(p)Y(n-p)+U(n)\r\n% makes use of autocovariance method (vector least squares)\r\n\r\n%%% input:\r\n% Y, M*N matrix of time series (each time series is in a row)\r\n% p, model order\r\n% Mode, determines estimation algorithm (0:builtin least squares, else other methods [see mvar.m from biosig package])\r\n\r\n%%% output:\r\n% Am=[A(1)...A(p)], M*pM matrix of the estimated MVAR model coefficients\r\n% S, estimated M*M input covariance matrix\r\n% Yp, estimated time series\r\n% Up, estimated residuals\r\n% Z, observation matrix (often optional, useful e.g. for resampling)\r\n\r\n\r\nfunction [Am,S,Yp,Up,Z,Yb]=idMVAR(Y,p,Mode)\r\n\r\n% error(nargchk(1,3,nargin));\r\n% if nargin < 3, Mode=0; end % default use least squares estimate\r\n% if nargin < 2, p=10; end % default model order\r\n\r\n[M,N]=size(Y);\r\n\r\n%% IDENTIFICATION\r\nZ=NaN*ones(p*M,N-p); % observation matrix\r\nfor j=1:p\r\n for i=1:M\r\n Z((j-1)*M+i,1:N-p)=Y(i, p+1-j:N-j);\r\n end\r\nend\r\n\r\nif Mode==0\r\n Yb=NaN*ones(M,N-p); % Ybar\r\n for i=1:M\r\n Yb(i,1:N-p)=Y(i,p+1:N);\r\n end\r\n Am=Yb/Z; % least squares!\r\n% fprintf('using least squares\\n'); \r\nelse\r\n Am = mvar(Y', p, Mode); % estimates from biosig code\r\n% fprintf(['using biosig ' int2str(Mode) ' mode\\n']); \r\nend\r\n\r\nYp=Am*Z; \r\nYp=[NaN*ones(M,p) Yp]; % Vector of predicted data\r\n\r\nUp=Y-Yp; Up=Up(:,p+1:N); % residuals of strictly causal model\r\nS=cov(Up');\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "danielemarinazzo/GC_SS_PNAS-master", "name": "block_fdMVAR.m", "ext": ".m", "path": "GC_SS_PNAS-master/block_fdMVAR.m", "size": 5321, "source_encoding": "utf_8", "md5": "c0626e923c90c31b6156e254a5e1785f", "text": "%% FREQUENCY DOMAIN BLOCK MVAR ANALYSIS\r\n% References:\r\n% L.Faes and G. Nollo, \"Measuring Frequency Domain Granger Causality for Multiple Blocks of Interacting Time Series\", Biological Cybernetics 2013. DOI: 10.1007/s00422-013-0547-5\r\n% L.Faes, S. Erla and G. Nollo, \"Block Partial Directed Coherence: a New Tool for the Structural Analysis of Brain Networks\", International Journal of Bioelectromagnetism, Vol. 14, No. 4, pp. 162 - 166, 2012\r\n\r\n%%% inputs: \r\n% Am=[A(1)...A(p)]: Q*pQ matrix of the MVAR model coefficients (strictly causal model)\r\n% Su: Q*Q covariance matrix of the input noises\r\n% Mv: number of series in each block\r\n% N= number of points for calculation of the spectral functions (nfft)\r\n% Fs= sampling frequency\r\n\r\n%%% outputs:\r\n% bDC= block Directed Coherence (Eq. 14a)\r\n% bPDC= block Partial Directed Coherence (Eq. 14b)\r\n% mF= multivariate total causality (Eq. 13a)\r\n% mG= multivariate direct causality (Eq. 13b)\r\n% bS= block spectral density matrix (Eq. 12a)\r\n% bP= inverse block spectral density matrix (Eq. 12b)\r\n% bH= block transfer matrix\r\n% bAf= block spectral coefficient matrix\r\n% f= vector of frequencies\r\n\r\n\r\nfunction [bDC,bPDC,mF,mG,bS,bP,bH,bAf,f] = block_fdMVAR(Am,Su,Mv,N,Fs)\r\n% clear; close all; clc;\r\n% [Bm,B0,Sw]=simuMVARcoeff(1);\r\n% Am=Bm;Su=Sw;\r\n% Mv=[2 1 1]'; % vector of Mi (dimension of each block)\r\n% N=512;\r\n% Fs=1;\r\n% f = (0:N-1)*(Fs/(2*N));\r\n\r\n%%\r\nQ= size(Am,1); % Am has dim Q*pQ\r\nM=length(Mv);\r\np = size(Am,2)/Q; % p is the order of the MVAR model\r\n\r\nif nargin<5, Fs= 1; end; \r\nif nargin<4, N = 512; end;\r\nif all(size(N)==1),\t %if N is scalar\r\n f = (0:N-1)*(Fs/(2*N)); % frequency axis\r\nelse % if N is a vector, we assume that it is the vector of the frequencies\r\n f = N; N = length(N);\r\nend;\r\n\r\ns = exp(sqrt(-1)*2*pi*f/Fs); % vector of complex exponentials\r\nz = sqrt(-1)*2*pi/Fs;\r\n\r\n\r\n%% Initializations: spectral matrices have M rows, M columns and are calculated at each of the N frequencies\r\nA = [eye(Q) -Am]; % matrix from which M*M blocks are selected to calculate spectral functions\r\ninvSu=inv(Su);\r\n% i-j block of Su and Su^(-1)\r\nbSu=cell(M,M); binvSu=cell(M,M); \r\nfor i=1:M\r\n for j=1:M\r\n i1=sum(Mv(1:i)); i0=i1-Mv(i)+1;\r\n j1=sum(Mv(1:j)); j0=j1-Mv(j)+1;\r\n bSu{i,j}=Su(i0:i1,j0:j1);\r\n binvSu{i,j}=invSu(i0:i1,j0:j1);\r\n end\r\nend\r\n\r\n% whole QxQ matrices\r\nAf=zeros(Q,Q,N); % Coefficient Matrix in the frequency domain (it is Abar(w))\r\nH=zeros(Q,Q,N); % Transfer Matrix H(w)\r\nS=zeros(Q,Q,N); % Spectral Matrix S(w)\r\nP=zeros(Q,Q,N); % Inverse Spectral Matrix P(w)\r\n% corresponding cell array of matrices (blocks of size Mi x Mj)\r\nbAf=cell(M,M,N);\r\nbH=cell(M,M,N); \r\nbS=cell(M,M,N); \r\nbP=cell(M,M,N);\r\n% causality functions\r\nbDC=zeros(M,M,N); % block directed coherence\r\nbPDC=zeros(M,M,N); % block partial directed coherence\r\nmF=NaN*ones(M,M,N); % multivariate logarithmic causality f\r\nmG=NaN*ones(M,M,N); % multivariate logarithmic direct causality g\r\n\r\n%%% computation of spectral functions\r\nfor n=1:N, % at each frequency \r\n %%% Coefficient matrix in the frequency domain\r\n As = zeros(Q,Q); % matrix As(z)=I-sum(A(k))\r\n for k = 1:p+1,\r\n As = As + A(:,k*Q+(1-Q:0))*exp(-z*(k-1)*f(n)); %indicization (:,k*Q+(1-M:0)) extracts the k-th Q*Q block from the matrix B (A(1) is in the second block, and so on)\r\n end; \r\n Af(:,:,n) = As; %%% Coefficient matrix\r\n H(:,:,n) = inv(As); %%% Transfer matrix \r\n S(:,:,n) = H(:,:,n)*Su*H(:,:,n)'; %%% Spectral matrix - ' stands for Hermitian transpose\r\n P(:,:,n) = inv(S(:,:,n)); %%% Inverse Spectral matrix P(:,:,n) = As'*invSu*As;\r\n \r\n %%% extraction of blocks indexes\r\n for i=1:M\r\n for j=1:M\r\n %indexes of the i-j block\r\n i1=sum(Mv(1:i)); i0=i1-Mv(i)+1;\r\n j1=sum(Mv(1:j)); j0=j1-Mv(j)+1;\r\n % i-j block of all matrices of interest\r\n bAf{i,j,n}=Af(i0:i1,j0:j1,n);\r\n bH{i,j,n}=H(i0:i1,j0:j1,n);\r\n bS{i,j,n}=S(i0:i1,j0:j1,n);\r\n bP{i,j,n}=P(i0:i1,j0:j1,n); \r\n end\r\n end\r\n \r\n % computation of causality measures at frequency n\r\n for i=1:M\r\n for j=1:M\r\n \r\n% if det(bP{j,j,n}) < -0.000001, error('determinante negativo!'); end\r\n% if det(bS{i,i,n}) < -0.000001, error('determinante negativo!'); end\r\n% if det(bP{j,j,n} - bAf{i,j,n}'*binvSu{i,i}*bAf{i,j,n}) < -0.000001, error('determinante negativo!'); end\r\n% if det(bS{i,i,n} - bH{i,j,n}*bSu{j,j}*bH{i,j,n}') < -0.000001, error('determinante negativo!'); end\r\n \r\n bDC(i,j,n) = 1 - abs(det(bS{i,i,n} - bH{i,j,n}*bSu{j,j}*bH{i,j,n}')) / abs(det(bS{i,i,n}));\r\n bPDC(i,j,n) = 1 - abs(det(bP{j,j,n} - bAf{i,j,n}'*binvSu{i,i}*bAf{i,j,n})) / abs(det(bP{j,j,n}));\r\n if i~=j\r\n mF(i,j,n) = log( abs(det(bS{i,i,n})) / abs(det(bS{i,i,n} - bH{i,j,n}*bSu{j,j}*bH{i,j,n}')) );\r\n mG(i,j,n) = log( abs(det(bP{j,j,n})) / abs(det(bP{j,j,n} - bAf{i,j,n}'*binvSu{i,i}*bAf{i,j,n})) );\r\n end\r\n end\r\n end \r\n \r\nend;\r\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "bipartite_matching.m", "ext": ".m", "path": "netalign-master/experiments/misc/gaimc/bipartite_matching.m", "size": 6580, "source_encoding": "utf_8", "md5": "bd3212ac06f51f9037ca7a7d80b45981", "text": "function [val m1 m2 mi]=bipartite_matching(varargin)\n% BIPARTITE_MATCHING Solve a maximum weight bipartite matching problem\n%\n% [val m1 m2]=bipartite_matching(A) for a rectangular matrix A \n% [val m1 m2 mi]=bipartite_matching(x,ei,ej,n,m) for a matrix stored\n% in triplet format. This call also returns a matching indicator mi so\n% that val = x'*mi.\n%\n% The maximum weight bipartite matching problem tries to pick out elements\n% from A such that each row and column get only a single non-zero but the\n% sum of all the chosen elements is as large as possible.\n%\n% This function is slightly atypical for a graph library, because it will\n% be primarily used on rectangular inputs. However, these rectangular\n% inputs model bipartite graphs and we take advantage of that stucture in\n% this code. The underlying graph adjency matrix is \n% G = spaugment(A,0); \n% where A is the rectangular input to the bipartite_matching function.\n%\n% Matlab already has the dmperm function that computes a maximum\n% cardinality matching between the rows and the columns. This function\n% gives us the maximum weight matching instead. For unweighted graphs, the\n% two functions are equivalent.\n%\n% Note: If ei and ej contain duplicate edges, the results of this function\n% are incorrect.\n%\n% See also DMPERM\n%\n% Example:\n% A = rand(10,8); % bipartite matching between random data\n% [val mi mj] = bipartite_matching(A);\n% val\n\n% David F. Gleich and Ying Wang\n% Copyright, Stanford University, 2008-2009\n% Computational Approaches to Digital Stewardship\n\n% 2008-04-24: Initial coding (copy from Ying Wang matching_sparse_mex.cpp)\n% 2008-11-15: Added triplet input/output\n% 2009-04-30: Modified for gaimc library\n% 2009-05-15: Fixed error with empty inputs and triple added example.\n\n[rp ci ai tripi n m] = bipartite_matching_setup(varargin{:});\n\nif isempty(tripi)\n error(nargoutchk(0,3,nargout,'struct'));\nelse \n error(nargoutchk(0,4,nargout,'struct'));\nend\n\n\nif ~isempty(tripi) && nargout>3\n [val m1 m2 mi] = bipartite_matching_primal_dual(rp, ci, ai, tripi, n, m);\nelse\n [val m1 m2] = bipartite_matching_primal_dual(rp, ci, ai, tripi, n, m);\nend\n\nfunction [rp ci ai tripi n m]= bipartite_matching_setup(A,ei,ej,n,m)\n% convert the input\n\nif nargin == 1\n if isstruct(A)\n [nzi nzj nzv]=csr_to_sparse(A.rp,A.ci,A.ai);\n else\n [nzi nzj nzv]=find(A); \n end\n [n m]=size(A);\n triplet = 0;\nelseif nargin >= 3 && nargin <= 5 \n nzi = ei;\n nzj = ej;\n nzv = A;\n if ~exist('n','var') || isempty(n), n = max(nzi); end\n if ~exist('m','var') || isempty(m), m = max(nzj); end\n triplet = 1;\nelse \n error(nargchk(3,5,nargin,'struct'));\nend\nnedges = length(nzi);\n\nrp = ones(n+1,1); % csr matrix with extra edges\nci = zeros(nedges+n,1);\nai = zeros(nedges+n,1);\nif triplet, tripi = zeros(nedges+n,1); % triplet index\nelse tripi = [];\nend\n\n%\n% 1. build csr representation with a set of extra edges from vertex i to\n% vertex m+i\n%\nrp(1)=0;\nfor i=1:nedges\n rp(nzi(i)+1)=rp(nzi(i)+1)+1;\nend\nrp=cumsum(rp); \nfor i=1:nedges\n if triplet, tripi(rp(nzi(i))+1)=i; end % triplet index\n ai(rp(nzi(i))+1)=nzv(i);\n ci(rp(nzi(i))+1)=nzj(i);\n rp(nzi(i))=rp(nzi(i))+1;\nend\nfor i=1:n % add the extra edges\n if triplet, tripi(rp(i)+1)=-1; end % triplet index\n ai(rp(i)+1)=0;\n ci(rp(i)+1)=m+i;\n rp(i)=rp(i)+1;\nend\n% restore the row pointer array\nfor i=n:-1:1\n rp(i+1)=rp(i);\nend\nrp(1)=0;\nrp=rp+1;\n\n%\n% 1a. check for duplicates in the data\n%\ncolind = false(m+n,1);\nfor i=1:n\n for rpi=rp(i):rp(i+1)-1\n if colind(ci(rpi)), error('bipartite_matching:duplicateEdge',...\n 'duplicate edge detected (%i,%i)',i,ci(rpi)); \n end\n colind(ci(rpi))=1;\n end\n for rpi=rp(i):rp(i+1)-1, colind(ci(rpi))=0; end % reset indicator\nend\n\n\nfunction [val m1 m2 mi]=bipartite_matching_primal_dual(...\n rp, ci, ai, tripi, n, m)\n% BIPARTITE_MATCHING_PRIMAL_DUAL \n\nalpha=zeros(n,1); % variables used for the primal-dual algorithm\nbeta=zeros(n+m,1);\nqueue=zeros(n,1);\nt=zeros(n+m,1);\nmatch1=zeros(n,1);\nmatch2=zeros(n+m,1);\ntmod = zeros(n+m,1);\nntmod=0;\n\n\n% \n% initialize the primal and dual variables\n%\nfor i=1:n\n for rpi=rp(i):rp(i+1)-1\n if ai(rpi) > alpha(i), alpha(i)=ai(rpi); end\n end\nend\n% dual variables (beta) are initialized to 0 already\n% match1 and match2 are both 0, which indicates no matches\ni=1;\nwhile i<=n\n % repeat the problem for n stages\n \n % clear t(j)\n for j=1:ntmod, t(tmod(j))=0; end\n ntmod=0;\n \n\n % add i to the stack\n head=1; tail=1;\n queue(head)=i; % add i to the head of the queue\n while head <= tail && match1(i)==0\n k=queue(head);\n for rpi=rp(k):rp(k+1)-1\n j = ci(rpi);\n if ai(rpi) < alpha(k)+beta(j) - 1e-8, continue; end % skip if tight\n if t(j)==0,\n tail=tail+1; queue(tail)=match2(j);\n t(j)=k;\n ntmod=ntmod+1; tmod(ntmod)=j;\n if match2(j)<1,\n while j>0, \n match2(j)=t(j);\n k=t(j);\n temp=match1(k);\n match1(k)=j;\n j=temp;\n end\n break; % we found an alternating path\n end\n end\n end\n head=head+1;\n end\n \n if match1(i) < 1, % still not matched, so update primal, dual and repeat\n theta=inf;\n for j=1:head-1\n t1=queue(j);\n for rpi=rp(t1):rp(t1+1)-1\n t2=ci(rpi);\n if t(t2) == 0 && alpha(t1) + beta(t2) - ai(rpi) < theta,\n theta = alpha(t1) + beta(t2) - ai(rpi);\n end\n end\n end\n \n for j=1:head-1, alpha(queue(j)) = alpha(queue(j)) - theta; end\n \n for j=1:ntmod, beta(tmod(j)) = beta(tmod(j)) + theta; end\n \n continue;\n end\n \n i=i+1; % increment i\nend\n\nval=0;\nfor i=1:n\n for rpi=rp(i):rp(i+1)-1\n if ci(rpi)==match1(i), val=val+ai(rpi); end\n end\nend\nnoute = 0; % count number of output edges\nfor i=1:n\n if match1(i)<=m, noute=noute+1; end\nend\nm1=zeros(noute,1); m2=m1; % copy over the 0 array\nnoute=1;\nfor i=1:n\n if match1(i)<=m, m1(noute)=i; m2(noute)=match1(i);noute=noute+1; end\nend\n\nif nargout>3\n mi= false(length(tripi)-n,1);\n for i=1:n\n for rpi=rp(i):rp(i+1)-1\n if match1(i)<=m && ci(rpi)==match1(i), mi(tripi(rpi))=1; end\n end\n end\nend\n\n\n\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "graph_draw.m", "ext": ".m", "path": "netalign-master/experiments/misc/gaimc/graph_draw.m", "size": 23504, "source_encoding": "utf_8", "md5": "83adf66de4bc94aea62f934d2e1e3da0", "text": "function h = graph_draw(adj, xy, varargin)\n% GRAPH_DRAW Draw a picture of a graph when the coordinates are known\n%\n% graph_draw(A, xy) draws a picture of graph A where node i is placed\n% at x = xy(i,1), y = xy(i,2). In the drawing, shaded nodes have \n% self loops.\n%\n% Some of the parameters of the drawing are controlled by specifying\n% optional parameters in the call graph_draw(A, xy, key, value). The keys\n% and default values are \n% 'linestyle' - default '-' \n% 'linewidth' - default .5\n% 'linecolor' - default Black\n% 'fontsize' - fontsize for labels, default 8 \n% 'labels' - Cell array containing labels \n% 'shapes' - 1 if node is a box, 0 if oval \n% \n% h = graph_draw(A,xy,...) returns a handle for each object. h(i,1) is\n% the text handle for vertex i, and h(i,2) is the circle handle for\n% vertex i. \n%\n% Originally written by Erik A. Johnson, Ali Taylan Cemgil, and Leon Peskin\n% Modified by David F. Gleich for gaimc package.\n%\n% See also GPLOT\n% \n% Example:\n% load_gaimc_graph('dfs_example');\n% graph_draw(A,xy);\n\n\n% 2009-02-26 interface modified by David Gleich \n% to remove automatic layout\n% 2009-05-15: Added example\n\n% 24 Feb 2004 cleaned up, optimized and corrected by Leon Peshkin pesha @ ai.mit.edu \n% Apr-2000 draw_graph Ali Taylan Cemgil \n% 1995-1997 arrow Erik A. Johnson \n\nlinestyle = '-'; % -- -. \nlinewidth = .5; % 2 \nlinecolor = 'Black'; % Red\nfontsize = 8;\nN = size(adj,1);\ncolor = ones(N, 3); % colors of elipses around text \nlabels = cellstr(int2str((1:N)')); % labels = cellstr(char(zeros(N,1)+double('+')));\nnode_t = zeros(N,1); % \nfor i = 1:2:length(varargin) % get optional args\n switch varargin{i}\n case 'linestyle', linestyle = varargin{i+1};\n case 'linewidth', linewidth = varargin{i+1};\n case 'linecolor', linecolor = varargin{i+1};\n case 'labels', labels = varargin{i+1};\n case 'fontsize', fontsize = varargin{i+1}; \n case 'shapes', node_t = varargin{i+1}; node_t = node_t(:);\n end\nend\n\nx = xy(:,1);\nx = x - min(x);\ny = xy(:,2);\ny = y - min(y);\n% scale the graph so it's between 0 and 1\nxrange = max(x);\nyrange = max(y);\nscalefactor = max(xrange,yrange);\nx = x/scalefactor;\ny = y/scalefactor;\n\nlp_ndx = find(diag(adj)); % recover from self-loops = diagonal ones \ncolor(lp_ndx,:) = repmat([.8 .8 .8],length(lp_ndx),1); % makes self-looped nodes blue\nadj = adj - diag(diag(adj)); % clean up the diagonal \n\naxis([-0.1 1.1 -0.1 1.1]);\naxis off; \nset(gcf,'Color',[1 1 1]);\nset(gca,'XTick',[], 'YTick',[], 'box','on'); % axis('square'); %colormap(flipud(gray));\n\nidx1 = find(node_t == 0); wd1 = []; % Draw nodes \nif ~isempty(idx1),\n [h1 wd1] = textoval(x(idx1), y(idx1), labels(idx1), fontsize, color);\nend;\n\nidx2 = find(node_t ~= 0); wd2 = [];\nif ~isempty(idx2),\n [h2 wd2] = textbox(x(idx2), y(idx2), labels(idx2), color);\nend;\n\nwd = zeros(size(wd1,1) + size(wd2,1),2);\nif ~isempty(idx1), wd(idx1, :) = wd1; end;\nif ~isempty(idx2), wd(idx2, :) = wd2; end;\n\nfor node = 1:N % Draw edges \n edges = find(adj(node,:) == 1);\n for node2 = edges\n sign = 1;\n if ((x(node2) - x(node)) == 0)\n\t if (y(node) > y(node2)), alpha = -pi/2; else alpha = pi/2; end;\n else\n alpha = atan((y(node2)-y(node))/(x(node2)-x(node)));\n\t if (x(node2) <= x(node)), sign = -1; end;\n end;\n dy1 = sign.*wd(node,2).*sin(alpha); dx1 = sign.*wd(node,1).*cos(alpha);\n dy2 = sign.*wd(node2,2).*sin(alpha); dx2 = sign.*wd(node2,1).*cos(alpha); \n if (adj(node2,node) == 0) % if directed edge\n my_arrow([x(node)+dx1 y(node)+dy1], [x(node2)-dx2 y(node2)-dy2]);\n else\t \n line([x(node)+dx1 x(node2)-dx2], [y(node)+dy1 y(node2)-dy2], ...\n 'Color', linecolor, 'LineStyle', linestyle, 'LineWidth', linewidth);\n adj(node2,node) = -1; % Prevent drawing lines twice\n end;\n end;\nend;\n\nif nargout > 2\n h = zeros(length(wd),2);\n if ~isempty(idx1), h(idx1,:) = h1; end;\n if ~isempty(idx2), h(idx2,:) = h2; end;\nend;\n\nfunction [t, wd] = textoval(x, y, str, fontsize, c)\n% [t, wd] = textoval(x, y, str, fontsize) Draws an oval around text objects\n% INPUT: x, y - Coordinates\n% str - Strings\n% c - colors \n% OUTPUT: t - Object Handles\n% width - x and y width of ovals \nif ~isa(str,'cell'), str = cellstr(str); end;\nN = length(str); \nwd = zeros(N,2);\ntemp = zeros(N,2);\nfor i = 1:N,\n tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle','FontSize', fontsize);\n sz = get(tx, 'Extent');\n wy = sz(4);\n wx = max(2/3*sz(3), wy); \n wx = 0.9 * wx; % might want to play with this .9 and .5 coefficients \n wy = 0.5 * wy;\n ptc = ellipse(x(i), y(i), wx, wy, c(i,:));\n set(ptc, 'FaceColor', c(i,:)); % 'w'\n wd(i,:) = [wx wy];\n delete(tx);\n tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle', 'FontSize', fontsize); \n temp(i,:) = [tx ptc];\nend;\nt = temp; \n\nfunction [p] = ellipse(x, y, rx, ry, c)\n% [p] = ellipse(x, y, rx, ry) Draws Ellipse shaped patch objects\n% INPUT: x,y - N x 1 vectors of x and y coordinates\n% Rx, Ry - Radii\n% C - colors \n% OUTPUT: p - Handles of Ellipse shaped path objects\n\n if length(rx)== 1, rx = ones(size(x)).*rx; end;\n if length(ry)== 1, ry = ones(size(x)).*ry; end;\nN = length(x);\np = zeros(size(x));\nt = 0:pi/30:2*pi;\nfor i = 1:N\n\tpx = rx(i) * cos(t) + x(i); py = ry(i) * sin(t) + y(i);\n\tp(i) = patch(px, py, c(i,:));\nend;\n\nfunction [h, wd] = textbox(x,y,str,c)\n% [h, wd] = textbox(x,y,str) draws a box around the text \n% INPUT: x, y - Coordinates\n% str - Strings\n% OUTPUT: h - Object Handles\n% wd - x and y Width of boxes \n\nif ~isa(str,'cell'), str=cellstr(str); end\nN = length(str);\nwd = zeros(N,2);\nh = zeros(N,2);\nfor i = 1:N,\n tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle');\n sz = get(tx, 'Extent');\n wy = 2/3 * sz(4); wyB = y(i) - wy; wyT = y(i) + wy;\n wx = max(2/3 * sz(3), wy); wxL = x(i) - wx; wxR = x(i) + wx;\n ptc = patch([wxL wxR wxR wxL], [wyT wyT wyB wyB], c(i,:)); \n set(ptc, 'FaceColor', c(i,:)); % 'w' \n wd(i,:) = [wx wy];\n delete(tx);\n tx = text(x(i),y(i),str{i},'HorizontalAlignment','center','VerticalAlign','middle'); \n h(i,:) = [tx ptc];\nend;\n\nfunction [h,yy,zz] = my_arrow(varargin)\n% [h,yy,zz] = my_arrow(varargin) Draw a line with an arrowhead.\n\n% A lot of the original code is removed and most of the remaining can probably go too\n% since it comes from a general use function only being called inone context. - Leon Peshkin \n% Copyright 1997, Erik A. Johnson , 8/14/97\n\nax = []; % set values to empty matrices\ndeflen = 12; % 16\ndefbaseangle = 45; % 90\ndeftipangle = 16;\ndefwid = 0; defpage = 0; defends = 1;\nArrowTag = 'Arrow'; % The 'Tag' we'll put on our arrows\nstart = varargin{1}; % fill empty arguments\nstop = varargin{2}; \ncrossdir = [NaN NaN NaN]; \nlen = NaN; baseangle = NaN; tipangle = NaN; wid = NaN; \npage = 0; ends = NaN; \nstart = [start NaN]; stop = [stop NaN];\no = 1; % expand single-column arguments\nax = gca;\n% set up the UserData data (here so not corrupted by log10's and such)\nud = [start stop len baseangle tipangle wid page crossdir ends];\n% Get axes limits, range, min; correct for aspect ratio and log scale\naxm = zeros(3,1); axr = axm; axrev = axm; ap = zeros(2,1);\nxyzlog = axm; limmin = ap; limrange = ap; oldaxlims = zeros(1,7);\noneax = 1; % all(ax==ax(1)); LPM\nif (oneax),\n\tT = zeros(4,4); invT = zeros(4,4);\nelse\n\tT = zeros(16,1); invT = zeros(16,1); \nend\naxnotdone = 1; % logical(ones(size(ax))); LPM \nwhile (any(axnotdone))\n\tii = 1; % LPM min(find(axnotdone));\n\tcurax = ax(ii);\n\tcurpage = page(ii);\n\t% get axes limits and aspect ratio\n\taxl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')];\n\toldaxlims(find(oldaxlims(:,1)==0, 1),:) = [curax reshape(axl',1,6)];\n\t% get axes size in pixels (points)\n\tu = get(curax,'Units');\n\taxposoldunits = get(curax,'Position');\n\treally_curpage = curpage & strcmp(u,'normalized');\n\tif (really_curpage)\n\t\tcurfig = get(curax,'Parent'); \t\tpu = get(curfig,'PaperUnits');\n\t\tset(curfig,'PaperUnits','points'); pp = get(curfig,'PaperPosition');\n\t\tset(curfig,'PaperUnits',pu); set(curax,'Units','pixels');\n\t\tcurapscreen = get(curax,'Position'); set(curax,'Units','normalized');\n\t\tcurap = pp.*get(curax,'Position');\n else\n\t\tset(curax,'Units','pixels');\n\t\tcurapscreen = get(curax,'Position');\n\t\tcurap = curapscreen;\n end\n\tset(curax,'Units',u); set(curax,'Position',axposoldunits);\n\t% handle non-stretched axes position\n\tstr_stretch = {'DataAspectRatioMode'; 'PlotBoxAspectRatioMode' ; 'CameraViewAngleMode' };\n\tstr_camera = {'CameraPositionMode' ; 'CameraTargetMode' ; ...\n\t 'CameraViewAngleMode' ; 'CameraUpVectorMode'};\n\tnotstretched = strcmp(get(curax,str_stretch),'manual');\n\tmanualcamera = strcmp(get(curax,str_camera),'manual');\n\tif ~arrow_WarpToFill(notstretched,manualcamera,curax)\n\t\t% find the true pixel size of the actual axes\n\t\ttexttmp = text(axl(1,[1 2 2 1 1 2 2 1]), ...\n\t\t axl(2,[1 1 2 2 1 1 2 2]), axl(3,[1 1 1 1 2 2 2 2]),'');\n\t\tset(texttmp,'Units','points');\n\t\ttextpos = get(texttmp,'Position');\n\t\tdelete(texttmp);\n\t\ttextpos = cat(1,textpos{:});\n\t\ttextpos = max(textpos(:,1:2)) - min(textpos(:,1:2));\n\t\t% adjust the axes position\n\t\tif (really_curpage) \t\t\t% adjust to printed size\n\t\t\ttextpos = textpos * min(curap(3:4)./textpos);\n\t\t\tcurap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos];\n else % adjust for pixel roundoff\n\t\t\ttextpos = textpos * min(curapscreen(3:4)./textpos);\n\t\t\tcurap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos];\n end\n end\n\t% adjust limits for log scale on axes\n\tcurxyzlog = [strcmp(get(curax,'XScale'),'log'); ...\n\t strcmp(get(curax,'YScale'),'log'); strcmp(get(curax,'ZScale'),'log')];\n\tif (any(curxyzlog))\n\t\tii = find([curxyzlog;curxyzlog]);\n\t\tif (any(axl(ii)<=0))\n\t\t\terror([upper(mfilename) ' does not support non-positive limits on log-scaled axes.']);\n else\n\t\t\taxl(ii) = log10(axl(ii));\n end\n end\n\t% correct for 'reverse' direction on axes;\n\tcurreverse = [strcmp(get(curax,'XDir'),'reverse'); ...\n\t strcmp(get(curax,'YDir'),'reverse'); strcmp(get(curax,'ZDir'),'reverse')];\n\tii = find(curreverse);\n\tif ~isempty(ii)\n\t\taxl(ii,[1 2])=-axl(ii,[2 1]);\n end\n\t% compute the range of 2-D values\n\tcurT = get(curax,'Xform');\n\tlim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1];\n\tlim = lim(1:2,:)./([1;1]*lim(4,:));\n\tcurlimmin = min(lim,[],2);\n\tcurlimrange = max(lim,[],2) - curlimmin;\n\tcurinvT = inv(curT);\n\tif ~oneax\n curT = curT.'; curinvT = curinvT.'; curT = curT(:); curinvT = curinvT(:);\n end\n\t% check which arrows to which cur corresponds\n\tii = find((ax==curax)&(page==curpage));\n\too = ones(1,length(ii)); \taxr(:,ii) = diff(axl,1,2) * oo;\n\taxm(:,ii) = axl(:,1) * oo; axrev(:,ii) = curreverse * oo;\n\tap(:,ii) = curap(3:4)' * oo; xyzlog(:,ii) = curxyzlog * oo;\n\tlimmin(:,ii) = curlimmin * oo; limrange(:,ii) = curlimrange * oo;\n\tif (oneax),\n\t\tT = curT; invT = curinvT;\n else\n\t\tT(:,ii) = curT * oo; invT(:,ii) = curinvT * oo;\n\tend;\n\taxnotdone(ii) = zeros(1,length(ii));\nend;\noldaxlims(oldaxlims(:,1)==0,:) = [];\n\n% correct for log scales\ncurxyzlog = xyzlog.'; ii = find(curxyzlog(:));\nif ~isempty(ii)\n\tstart(ii) = real(log10(start(ii))); stop(ii) = real(log10(stop(ii)));\n\tif (all(imag(crossdir)==0)) % pulled (ii) subscript on crossdir, 12/5/96 eaj\n\t\tcrossdir(ii) = real(log10(crossdir(ii)));\n end\nend\nii = find(axrev.'); % correct for reverse directions\nif ~isempty(ii)\n\tstart(ii) = -start(ii); stop(ii) = -stop(ii); crossdir(ii) = -crossdir(ii);\nend\nstart = start.'; stop = stop.'; % transpose start/stop values\n% take care of defaults, page was done above\nii = find(isnan(start(:))); if ~isempty(ii), start(ii) = axm(ii)+axr(ii)/2; end;\nii = find(isnan(stop(:))); if ~isempty(ii), stop(ii) = axm(ii)+axr(ii)/2; end;\nii = find(isnan(crossdir(:))); if ~isempty(ii), crossdir(ii) = zeros(length(ii),1); end;\nii = find(isnan(len)); if ~isempty(ii), len(ii) = ones(length(ii),1)*deflen; end;\nbaseangle(ii) = ones(length(ii),1)*defbaseangle; tipangle(ii) = ones(length(ii),1)*deftipangle; \nwid(ii) = ones(length(ii),1) * defwid; ends(ii) = ones(length(ii),1) * defends;\n% transpose rest of values\nlen = len.'; baseangle = baseangle.'; tipangle = tipangle.'; wid = wid.'; \npage = page.'; crossdir = crossdir.'; ends = ends.'; ax = ax.';\n\n% for all points with start==stop, start=stop-(verysmallvalue)*(up-direction);\nii = find(all(start==stop));\nif ~isempty(ii)\n\t% find an arrowdir vertical on screen and perpendicular to viewer\n\t%\ttransform to 2-D\n\t\ttmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))];\n\t\tif (oneax), twoD=T*tmp1;\n else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1;\n\t\t tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:);\n\t\t twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; \n end\n\t\ttwoD=twoD./(ones(4,1)*twoD(4,:));\n\t%\tmove the start point down just slightly\n\t\ttmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii));\n\t%\ttransform back to 3-D\n\t\tif (oneax), threeD=invT*tmp1;\n else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1;\n\t\t tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:);\n\t\t threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; \n end\n\t\tstart(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii);\nend;\n% compute along-arrow points\n%\ttransform Start points\n\ttmp1 = [(start-axm)./axr; 1];\n\tif (oneax), X0=T*tmp1;\n else tmp1 = [tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;\n\t tmp2 = zeros(4,4); tmp2(:)=tmp1(:);\n\t X0=zeros(4,1); X0(:)=sum(tmp2)'; \n end\n\tX0=X0./(ones(4,1)*X0(4,:));\n%\ttransform Stop points\n\ttmp1=[(stop-axm)./axr; 1];\n\tif (oneax), Xf=T*tmp1;\n else tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;\n\t tmp2=zeros(4,4); tmp2(:)=tmp1(:);\n\t Xf=zeros(4,1); Xf(:)=sum(tmp2)'; \n end\n\tXf=Xf./(ones(4,1)*Xf(4,:));\n%\tcompute pixel distance between points\n\tD = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2));\n%\tcompute and modify along-arrow distances\n\tlen1 = len;\n\tlen2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi);\n\tslen0 = 0; \tslen1 = len1 .* ((ends==2)|(ends==3));\n\tslen2 = len2 .* ((ends==2)|(ends==3));\n\tlen0 = 0; len1 = len1 .* ((ends==1)|(ends==3));\n\tlen2 = len2 .* ((ends==1)|(ends==3));\n ii = find((ends==1)&(D\n% check if we are in \"WarpToFill\" mode.\n\tout = strcmp(get(curax,'WarpToFill'),'on');\n\t% 'WarpToFill' is undocumented, so may need to replace this by\n\t% out = ~( any(notstretched) & any(manualcamera) );\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "netalignmr2.m", "ext": ".m", "path": "netalign-master/experiments/crystalize_mr/netalignmr2.m", "size": 6168, "source_encoding": "utf_8", "md5": "4973769c6f25dc607067664b4d9444ae", "text": "function [xbest,status,hist] = netalignmr(S,w,a,b,li,lj,gamma,stepm,rtype,maxiter,verbose)\n% NETALIGNMR Compute the matching relaxation heuristic for network alignment\n%\n% Given a network alignment problem, the matching heuristic solves a\n% sequence of matching problems to generate good upper and lower bounds on\n% the solutions.\n%\n% [xbest,status,hist] = netalignmr(S,w,a,b,li,lj,stepm,rtype,\n% maxiter,verbose) \n% fully specifies all inputs and outputs. \n%\n% Input\n% -----\n% S : the complete set of squares\n% w : the matching weights for all edges in the link graph L\n% a : the value of alpha in the netalign objective\n% b : the value of beta in the netalign objective\n% li : the start point of each edge in L (a vertex number from graph A)\n% lj : the end point of each edge in L (a vertex number from graph B)\n% gamma : the starting step value (default = 0.5)\n% stepm : number of non-decreasing iterations adjusting the step length\n% (default = 100)\n% rtype : the rounding type (default = 1)\n% rtype = 1 : only consider the current matching\n% rtype = 2 : try enriching the matching with info from other squares\n% maxiter : maximum number of iterations to take (default = 1000)\n% verbose : output verbose information at each iteration (default = true)\n%\n% Output\n% ------\n% xbest : the best heuristic solution, it may or may not be a matching\n% status : three values to describe the status of the solution\n% status(1) = 1 if the problem is solved to optimality, 0 otherwise\n% status(2) = best lower bound\n% status(3) = best upper bound\n% hist : the history of properties of each iteration\n% hist(k,) = \n% hist(k,) = best lower bound at iteration k\n% hist(k,) = best upper bound at iteration k\n% hist(k,) = current value at iteration k\n% hist(k,) = matching weight at iteration k\n% hist(k,) = matching cardinality at iteration k\n% hist(k,) = overlap at iteration k\n%\n% Example:\n% load('../data/natalie_graphs');\n% netalignmr(S,w,0,1,li,lj);\n\n% David F. Gleich, Ying Wang, and Mohsen Bayati\n% Copyright, Stanford University, 2008-2009\n% Computational Approaches to Digital Stewardship\n\n% 2009-06-11: Initial coding (David and Ying)\n% 2009-06-15: Cleanup and optimization (David)\n\nif ~exist('a','var') || isempty(a), a=1; end\nif ~exist('b','var') || isempty(b), b=1; end\nif ~exist('stepm','var') || isempty(stepm), stepm=25; end\nif ~exist('rtype','var') || isempty(rtype), rtype=1; end\nif ~exist('maxiter', 'var') || isempty(maxiter), maxiter=1000; end\nif ~exist('verbose', 'var') || isempty(verbose), verbose=1; end \nif ~exist('gamma', 'var') || isempty(gamma), gamma = 0.4; end\n\nm = max(li);\nn = max(lj);\n\n[rp ci ai tripi matn matm] = bipartite_matching_setup(w,li,lj,m,n); \nmperm = tripi(tripi>0); % a permutation for the matching problem\n\nS = double(S);\nU = sparse(size(S,1),size(S,2));\n\nxbest = w;\nxbest(:) = 0;\n\nflower = 0; % best lower bound on the solution\nfupper = Inf; % best upper bound on the solution\nnext_reduction_iteration = stepm; % reduce the step\ncrystalize_phase = 0; % a variable to indicate we are in the crystalization phase\ncrystalize_gamma = 1e-20;\ncrystalize_stepm = 5;\n\n\n\nhist = zeros(maxiter,7);\n\nif verbose % print the header\n fprintf('%5s %4s %8s %7s %7s %7s %7s %7s %7s %7s\\n', ...\n 'best', 'iter', 'norm-u', 'lower','upper', 'cur', 'obj', 'weight', 'card', 'overlap');\nend \nfor iter = 1:maxiter \n [q,SM] = maxrowmatch((b/2)*S + U-U',li,lj,m,n);\n x = a*w + q;\n \n %[val ma mb mi]= bipartite_matching(nw,li,lj,m,n);\n ai=zeros(length(tripi),1); ai(tripi>0)=x(mperm);\n [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm);\n \n % compute statistics \n matchval = mi'*w;\n overlap = mi'*S*mi/2; \n card = length(ma);\n f = a*matchval + b*overlap;\n \n if valflower\n flower=f;\n itermark = '*';\n xbest = mi;\n else\n itermark = ' ';\n end \n \n if rtype==1\n % no work\n elseif rtype==2\n mw = S*x;\n mw = a*w + b/2*mw;\n \n ai=zeros(length(tripi),1); ai(tripi>0)=mw(mperm);\n [val ma mb mx] = bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm);\n \n card = length(ma);\n matchval = mx'*w;\n overlap = mx'*S*mx/2;\n f = a*matchval + b*overlap;\n \n if f>flower\n flower=f;\n itermark = '**';\n mi = mx;\n xbest = mw;\n end\n end\n \n % report on current iter\n hist(iter,1:end) = [norm(nonzeros(U),1), flower, fupper, f, matchval, card, overlap];\n \n if verbose\n fprintf('%5s %4i %8.1e %7g %7g %7g %7g %7g %7i %7i\\n', ...\n itermark, iter, norm(nonzeros(U),1), ...\n flower, fupper, val, ...\n f, matchval, card, overlap);\n end\n \n if iter==next_reduction_iteration\n gamma = gamma*0.5;\n if verbose\n fprintf('%5s %4s reducing step to %g\\n', '', '', gamma);\n end\n if gamma < 1e-24, break; end\n if crystalize_phase\n next_reduction_iteration = iter+crystalize_stepm;\n else\n next_reduction_iteration = iter+stepm;\n end\n end\n \n if (fupper-flower)<1e-2\n break;\n end\n \n % check if we need to enter the crystalization phase\n num_crystalize_iters = crystalize_stepm*(log(crystalize_gamma)-log(gamma))/log(0.5);\n if ~crystalize_phase && num_crystalize_iters > maxiter - iter\n crystalize_phase = 1;\n next_reduction_iteration = iter+crystalize_stepm;\n fprintf('%5s %4s switching to crystalization phase\\n', '', '');\n end\n \n U = U - diag(sparse(gamma*mi))*triu(SM) + tril(SM)'*diag(sparse(gamma*mi));\n \n U = bound(U, -.5, .5);\nend\nhist = hist(1:iter,:);\nstatus = zeros(1,3);\nstatus(1) = (fupper-flower)<1e-2;\nstatus(2) = flower;\nstatus(3) = fupper;\n\nfunction S=bound(S,a,b)\nS=spfun(@(x) min(max(x,a),b), S);\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "netalignbp_y.m", "ext": ".m", "path": "netalign-master/experiments/old/rounding/netalignbp_y.m", "size": 6447, "source_encoding": "utf_8", "md5": "60b9cf0f094a4f2449195b5ec82a82d9", "text": "function [mbest hista histb] = netalignbp(S,w,a,b,li,lj,gamma,maxiter,verbose)\n% NETALIGNBP Solve the network alignment problem with Belief Propagation\n%\n% \n\n% David F. Gleich, Ying Wang, and Mohsen Bayati\n% Copyright, Stanford University, 2007-2008\n% Computational Approaches to Digital Stewardship\n\nif ~exist('a','var') || isempty(a), a=1; end\nif ~exist('b','var') || isempty(b), b=1; end\nif ~exist('gamma','var') || isempty(gamma), gamma=0.85; end\nif ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end\nif ~exist('verbose', 'var') || isempty(verbose), verbose=1; end \n\nnedges = length(li);\nnsquares = nnz(S)/2;\nm = max(li);\nn = max(lj);\n\n% compute a vector that allows us to transpose data between squares. \n% Recall the BP algorithm requires edge(i,j) to send messages to edge(r,s)\n% when (i,j) and (r,s) form a square. However, edge(i,j) needs information\n% the information that (r,s) sent it from the previous iteraton. \n% If we imagine that each non-zero of S has a value, we want to tranpose\n% these values.\n[sui suj] = find(triu(S,1)); % only consider each square once.\nSI = sparse(sui,suj,1:length(sui),size(S,1),size(S,2)); % assign indices \nSI = SI + SI'; % SI now has symmetric indices \n[si sj sind] = find(SI);\nSP = sparse(si,sind,true,size(S,1),nsquares); % each column in SP has 2 nz\n[sij sijrs] = find(SP);\nsind = (1:nnz(SP))';\nspair = sind; spair(1:2:end) = sind(2:2:end); spair(2:2:end) = sind(1:2:end);\n% sij, sijrs maps between rows and squares\n% spair is now an indexing vector that accomplishes what we need\n\n% Initialize the messages\nma = zeros(nedges,1);\nmb = ma;\nms = zeros(nnz(S),1);\n\ndamping = gamma;\ncurdamp = 1;\niter = 1;\nalpha = a;\nbeta = b;\n\n% Initialize history\nhista = zeros(maxiter,4); % history of messages from ei->a vertices\nhistb = zeros(maxiter,4); % history of messages from ei->b vertices\nfbest = 0; fbestiter = 0;\nif verbose % print the header\n fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\\n', ...\n 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ...\n 'obj_mb', 'wght_mb', 'card_mb', 'over_mb');\nend\n\n% setup the matching problem once\n[rp ci ai tripi matn matm] = bipartite_matching_setup(...\n w,li,lj,m,n); \nclear ai;\n\nwhile iter<=maxiter\n prevma = ma;\n prevmb = mb;\n prevms = ms;\n curdamp = damping*curdamp;\n \n omaxb = othermaxplus(2,li,lj,mb,m,n);\n omaxa = othermaxplus(1,li,lj,ma,m,n);\n \n msflip = ms(spair); % swap ij->ijrs to rs->ijrs \n mymsflip = msflip+beta;\n mymsflip = min(beta,mymsflip);\n mymsflip = max(0,mymsflip);\n \n sums = accumarray(sij,mymsflip,[nedges 1],@sum,0);\n \n ma = alpha*w - omaxb + sums;\n mb = alpha*w - omaxa + sums;\n \n ms = alpha*w(sij)-(omaxb(sij) + omaxa(sij));\n ms = ms + othersum(sij,sijrs,mymsflip,nedges,nsquares);\n \n ma = curdamp*(ma) + (1-curdamp)*(prevma);\n mb = curdamp*(mb) + (1-curdamp)*(prevmb);\n ms = curdamp*(ms) + (1-curdamp)*(prevms);\n \n % now compute the matchings\n sums1 = accumarray(sij,mymsflip,[nedges 1],@sum,0);\n sums2 = accumarray(sij,mymsflip,[nedges 1],@sum,0);\n hista(iter,:) = round_messages(alpha*w + beta*sums1,S,w,alpha,beta,rp,ci,tripi,matn,matm);\n histb(iter,:) = round_messages(alpha*w + beta*sums2,S,w,alpha,beta,rp,ci,tripi,matn,matm);\n if hista(iter,1)>fbest\n fbestiter=iter; mbest=sums1; fbest=hista(iter,1);\n end\n if histb(iter,1)>fbest\n fbestiter=-iter; mbest=sums2; fbest=histb(iter,1);\n end\n \n if verbose\n if fbestiter==iter, bestchar='*a'; \n elseif fbestiter==-iter, bestchar='*b';\n else bestchar='';\n end\n fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\\n', ...\n bestchar, iter, hista(iter,:), histb(iter,:));\n end\n iter=iter+1;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m)\nai=zeros(length(tripi),1); ai(tripi>0)=messages;\n[val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m);\nmatchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*mi))/2; \nf = alpha*matchweight + beta*overlap;\ninfo = [f matchweight cardinality overlap];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction omp=othermaxplus(dim,li,lj,lw,m,n)\n% OTHERMAXPLUS Apply the other-max-plus operator to a sparse matrix\n%\n% The other-max-plus operator applies the max-plus aggegration function\n% over the rows or columns of the matrix, where, for \n% each non-zeros, the non-zero itself cannot be the maximum. Consequently,\n% Hence, it's the max-plus of all the \"other\" elements in the row or column\n% (which is controlled by dim).\n%\n% omp=othermaxplus(dim,li,lj,lw,m,n) applies the other-max-plus operator\n% to the matrix sparse(li, lj, lw, m, n). The return value omp gives\n% the other-max-plus value for each non-zero element, e.g. the matrix\n% is sparse(li, lj, omp, m, n).\n\nif dim==1\n % max-plus over cols\n i1 = lj;\n i2 = li;\n N = n;\nelse\n % max-plus over rows\n i1 = li;\n i2 = lj;\n N = m;\nend\n\n% the output of the other-max-plus is either the maximum element \n% in the row or column (if the element itself isn't the maximum) or\n% the second largest element in the row or column (if the element itself\n% IS the maximum).\n\ndimmax1 =0*ones(N,1); % largest value\ndimmax2 = 0*ones(N,1); % second largest value, \n% this is correct because of the definition of the max-plus function. \ndimmaxind = zeros(N,1); % index of largest value\nnedges = length(li);\n\nfor i=1:nedges\n if lw(i) > dimmax2(i1(i))\n if lw(i) > dimmax1(i1(i))\n dimmax2(i1(i)) = dimmax1(i1(i));\n dimmax1(i1(i)) = lw(i);\n dimmaxind(i1(i)) = i2(i);\n else\n dimmax2(i1(i)) = lw(i);\n end\n end \nend\n\nomp = zeros(size(lw));\nfor i=1:nedges\n if i2(i) == dimmaxind(i1(i))\n omp(i) = dimmax2(i1(i));\n else\n omp(i) = dimmax1(i1(i));\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction os=othersum(si,sj,s,m,n) %#ok\n% OTHERSUM Compute the sum of each column of the matrix, without each\n% individual entry. This corresponds to a matrix where each entry is the\n% sum of each column but with each entry subtracted. \n\nrowsum=accumarray(si,s,[m,1]);\nos=rowsum(si)-s; \n\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "netalignbp_yz.m", "ext": ".m", "path": "netalign-master/experiments/old/rounding/netalignbp_yz.m", "size": 6465, "source_encoding": "utf_8", "md5": "3bd7d5f146af758410916577c9f26650", "text": "function [mbest hista histb] = netalignbp(S,w,a,b,li,lj,gamma,maxiter,verbose)\n% NETALIGNBP Solve the network alignment problem with Belief Propagation\n%\n% \n\n% David F. Gleich, Ying Wang, and Mohsen Bayati\n% Copyright, Stanford University, 2007-2008\n% Computational Approaches to Digital Stewardship\n\nif ~exist('a','var') || isempty(a), a=1; end\nif ~exist('b','var') || isempty(b), b=1; end\nif ~exist('gamma','var') || isempty(gamma), gamma=0.85; end\nif ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end\nif ~exist('verbose', 'var') || isempty(verbose), verbose=1; end \n\nnedges = length(li);\nnsquares = nnz(S)/2;\nm = max(li);\nn = max(lj);\n\n% compute a vector that allows us to transpose data between squares. \n% Recall the BP algorithm requires edge(i,j) to send messages to edge(r,s)\n% when (i,j) and (r,s) form a square. However, edge(i,j) needs information\n% the information that (r,s) sent it from the previous iteraton. \n% If we imagine that each non-zero of S has a value, we want to tranpose\n% these values.\n[sui suj] = find(triu(S,1)); % only consider each square once.\nSI = sparse(sui,suj,1:length(sui),size(S,1),size(S,2)); % assign indices \nSI = SI + SI'; % SI now has symmetric indices \n[si sj sind] = find(SI);\nSP = sparse(si,sind,true,size(S,1),nsquares); % each column in SP has 2 nz\n[sij sijrs] = find(SP);\nsind = (1:nnz(SP))';\nspair = sind; spair(1:2:end) = sind(2:2:end); spair(2:2:end) = sind(1:2:end);\n% sij, sijrs maps between rows and squares\n% spair is now an indexing vector that accomplishes what we need\n\n% Initialize the messages\nma = zeros(nedges,1);\nmb = ma;\nms = zeros(nnz(S),1);\n\ndamping = gamma;\ncurdamp = 1;\niter = 1;\nalpha = a;\nbeta = b;\n\n% Initialize history\nhista = zeros(maxiter,4); % history of messages from ei->a vertices\nhistb = zeros(maxiter,4); % history of messages from ei->b vertices\nfbest = 0; fbestiter = 0;\nif verbose % print the header\n fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\\n', ...\n 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ...\n 'obj_mb', 'wght_mb', 'card_mb', 'over_mb');\nend\n\n% setup the matching problem once\n[rp ci ai tripi matn matm] = bipartite_matching_setup(...\n w,li,lj,m,n); \nclear ai;\n\nwhile iter<=maxiter\n prevma = ma;\n prevmb = mb;\n prevms = ms;\n curdamp = damping*curdamp;\n \n omaxb = othermaxplus(2,li,lj,mb,m,n);\n omaxa = othermaxplus(1,li,lj,ma,m,n);\n \n msflip = ms(spair); % swap ij->ijrs to rs->ijrs \n mymsflip = msflip+beta;\n mymsflip = min(beta,mymsflip);\n mymsflip = max(0,mymsflip);\n \n sums = accumarray(sij,mymsflip,[nedges 1],@sum,0);\n \n ma = alpha*w - omaxb + sums;\n mb = alpha*w - omaxa + sums;\n \n ms = alpha*w(sij)-(omaxb(sij) + omaxa(sij));\n ms = ms + othersum(sij,sijrs,mymsflip,nedges,nsquares);\n \n ma = curdamp*(ma) + (1-curdamp)*(prevma);\n mb = curdamp*(mb) + (1-curdamp)*(prevmb);\n ms = curdamp*(ms) + (1-curdamp)*(prevms);\n \n % now compute the matchings\n sums1 = accumarray(sij,mymsflip.*ma(sij),[nedges 1],@sum,0);\n sums2 = accumarray(sij,mymsflip.*ma(sij),[nedges 1],@sum,0);\n hista(iter,:) = round_messages(alpha*w + beta*sums1,S,w,alpha,beta,rp,ci,tripi,matn,matm);\n histb(iter,:) = round_messages(alpha*w + beta*sums2,S,w,alpha,beta,rp,ci,tripi,matn,matm);\n if hista(iter,1)>fbest\n fbestiter=iter; mbest=sums1; fbest=hista(iter,1);\n end\n if histb(iter,1)>fbest\n fbestiter=-iter; mbest=sums2; fbest=histb(iter,1);\n end\n \n if verbose\n if fbestiter==iter, bestchar='*a'; \n elseif fbestiter==-iter, bestchar='*b';\n else bestchar='';\n end\n fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\\n', ...\n bestchar, iter, hista(iter,:), histb(iter,:));\n end\n iter=iter+1;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m)\nai=zeros(length(tripi),1); ai(tripi>0)=messages;\n[val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m);\nmatchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*mi))/2; \nf = alpha*matchweight + beta*overlap;\ninfo = [f matchweight cardinality overlap];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction omp=othermaxplus(dim,li,lj,lw,m,n)\n% OTHERMAXPLUS Apply the other-max-plus operator to a sparse matrix\n%\n% The other-max-plus operator applies the max-plus aggegration function\n% over the rows or columns of the matrix, where, for \n% each non-zeros, the non-zero itself cannot be the maximum. Consequently,\n% Hence, it's the max-plus of all the \"other\" elements in the row or column\n% (which is controlled by dim).\n%\n% omp=othermaxplus(dim,li,lj,lw,m,n) applies the other-max-plus operator\n% to the matrix sparse(li, lj, lw, m, n). The return value omp gives\n% the other-max-plus value for each non-zero element, e.g. the matrix\n% is sparse(li, lj, omp, m, n).\n\nif dim==1\n % max-plus over cols\n i1 = lj;\n i2 = li;\n N = n;\nelse\n % max-plus over rows\n i1 = li;\n i2 = lj;\n N = m;\nend\n\n% the output of the other-max-plus is either the maximum element \n% in the row or column (if the element itself isn't the maximum) or\n% the second largest element in the row or column (if the element itself\n% IS the maximum).\n\ndimmax1 =0*ones(N,1); % largest value\ndimmax2 = 0*ones(N,1); % second largest value, \n% this is correct because of the definition of the max-plus function. \ndimmaxind = zeros(N,1); % index of largest value\nnedges = length(li);\n\nfor i=1:nedges\n if lw(i) > dimmax2(i1(i))\n if lw(i) > dimmax1(i1(i))\n dimmax2(i1(i)) = dimmax1(i1(i));\n dimmax1(i1(i)) = lw(i);\n dimmaxind(i1(i)) = i2(i);\n else\n dimmax2(i1(i)) = lw(i);\n end\n end \nend\n\nomp = zeros(size(lw));\nfor i=1:nedges\n if i2(i) == dimmaxind(i1(i))\n omp(i) = dimmax2(i1(i));\n else\n omp(i) = dimmax1(i1(i));\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction os=othersum(si,sj,s,m,n) %#ok\n% OTHERSUM Compute the sum of each column of the matrix, without each\n% individual entry. This corresponds to a matrix where each entry is the\n% sum of each column but with each entry subtracted. \n\nrowsum=accumarray(si,s,[m,1]);\nos=rowsum(si)-s; \n\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "netalignmr.m", "ext": ".m", "path": "netalign-master/matlab/netalignmr.m", "size": 5472, "source_encoding": "utf_8", "md5": "3bba17d17e4d620f961d10dc0048c844", "text": "function [xbest,status,hist] = netalignmr(S,w,a,b,li,lj,gamma,stepm,rtype,maxiter,verbose)\n% NETALIGNMR Compute the matching relaxation heuristic for network alignment\n%\n% Given a network alignment problem, the matching heuristic solves a\n% sequence of matching problems to generate good upper and lower bounds on\n% the solutions.\n%\n% [xbest,status,hist] = netalignmr(S,w,a,b,li,lj,stepm,rtype,\n% maxiter,verbose) \n% fully specifies all inputs and outputs. \n%\n% Input\n% -----\n% S : the complete set of squares\n% w : the matching weights for all edges in the link graph L\n% a : the value of alpha in the netalign objective\n% b : the value of beta in the netalign objective\n% li : the start point of each edge in L (a vertex number from graph A)\n% lj : the end point of each edge in L (a vertex number from graph B)\n% gamma : the starting step value (default = 0.5)\n% stepm : number of non-decreasing iterations adjusting the step length\n% (default = 100)\n% rtype : the rounding type (default = 1)\n% rtype = 1 : only consider the current matching\n% rtype = 2 : try enriching the matching with info from other squares\n% maxiter : maximum number of iterations to take (default = 1000)\n% verbose : output verbose information at each iteration (default = true)\n%\n% Output\n% ------\n% xbest : the best heuristic solution, it may or may not be a matching\n% status : three values to describe the status of the solution\n% status(1) = 1 if the problem is solved to optimality, 0 otherwise\n% status(2) = best lower bound\n% status(3) = best upper bound\n% hist : the history of properties of each iteration\n% hist(k,) = \n% hist(k,) = best lower bound at iteration k\n% hist(k,) = best upper bound at iteration k\n% hist(k,) = current value at iteration k\n% hist(k,) = matching weight at iteration k\n% hist(k,) = matching cardinality at iteration k\n% hist(k,) = overlap at iteration k\n%\n% Example:\n% load('../data/natalie_graphs');\n% netalignmr(S,w,0,1,li,lj);\n\n% David F. Gleich, Ying Wang, and Mohsen Bayati\n% Copyright, Stanford University, 2008-2009\n% Computational Approaches to Digital Stewardship\n\n% 2009-06-11: Initial coding (David and Ying)\n% 2009-06-15: Cleanup and optimization (David)\n\nif ~exist('a','var') || isempty(a), a=1; end\nif ~exist('b','var') || isempty(b), b=1; end\nif ~exist('stepm','var') || isempty(stepm), stepm=25; end\nif ~exist('rtype','var') || isempty(rtype), rtype=1; end\nif ~exist('maxiter', 'var') || isempty(maxiter), maxiter=1000; end\nif ~exist('verbose', 'var') || isempty(verbose), verbose=1; end \nif ~exist('gamma', 'var') || isempty(gamma), gamma = 0.4; end\n\nm = max(li);\nn = max(lj);\n\n[rp ci ai tripi matn matm] = bipartite_matching_setup(w,li,lj,m,n); \nmperm = tripi(tripi>0); % a permutation for the matching problem\n\nS = double(S);\nU = sparse(size(S,1),size(S,2));\n\nxbest = w;\nxbest(:) = 0;\n\nflower = 0; % best lower bound on the solution\nfupper = Inf; % best upper bound on the solution\nnext_reduction_iteration = stepm; % reduce the step\n\n\nhist = zeros(maxiter,7);\n\nif verbose % print the header\n fprintf('%5s %4s %8s %7s %7s %7s %7s %7s %7s %7s\\n', ...\n 'best', 'iter', 'norm-u', 'lower','upper', 'cur', 'obj', 'weight', 'card', 'overlap');\nend \nfor iter = 1:maxiter \n [q,SM] = maxrowmatch((b/2)*S + U-U',li,lj,m,n);\n x = a*w + q;\n \n %[val ma mb mi]= bipartite_matching(nw,li,lj,m,n);\n ai=zeros(length(tripi),1); ai(tripi>0)=x(mperm);\n [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm);\n \n % compute statistics \n matchval = mi'*w;\n overlap = mi'*S*mi/2; \n card = length(ma);\n f = a*matchval + b*overlap;\n \n if valflower\n flower=f;\n itermark = '*';\n xbest = mi;\n else\n itermark = ' ';\n end \n \n if rtype==1\n % no work\n elseif rtype==2\n mw = S*x;\n mw = a*w + b/2*mw;\n \n ai=zeros(length(tripi),1); ai(tripi>0)=mw(mperm);\n [val ma mb mx] = bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm);\n \n card = length(ma);\n matchval = mx'*w;\n overlap = mx'*S*mx/2;\n f = a*matchval + b*overlap;\n \n if f>flower\n flower=f;\n itermark = '**';\n mi = mx;\n xbest = mw;\n end\n end\n \n % report on current iter\n hist(iter,1:end) = [norm(nonzeros(U),1), flower, fupper, f, matchval, card, overlap];\n \n if verbose\n fprintf('%5s %4i %8.1e %7g %7g %7g %7g %7g %7i %7i\\n', ...\n itermark, iter, norm(nonzeros(U),1), ...\n flower, fupper, val, ...\n f, matchval, card, overlap);\n end\n \n if iter==next_reduction_iteration\n gamma = gamma*0.5;\n if verbose\n fprintf('%5s %4s reducing step to %g\\n', '', '', gamma);\n end\n if gamma < 1e-24, break; end\n next_reduction_iteration = iter+stepm;\n end\n \n if (fupper-flower)<1e-2\n break;\n end\n \n U = U - diag(sparse(gamma*mi))*triu(SM) + tril(SM)'*diag(sparse(gamma*mi));\n \n U = bound(U, -.5, .5);\nend\nhist = hist(1:iter,:);\nstatus = zeros(1,3);\nstatus(1) = (fupper-flower)<1e-2;\nstatus(2) = flower;\nstatus(3) = fupper;\n\nfunction S=bound(S,a,b)\nS=spfun(@(x) min(max(x,a),b), S);\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "netalignbp.m", "ext": ".m", "path": "netalign-master/matlab/netalignbp.m", "size": 7067, "source_encoding": "utf_8", "md5": "366425d10c4e61e2ec0d1782c9ac8c30", "text": "function [mbest hista histb] = netalignbp(S,w,a,b,li,lj,gamma,dtype,maxiter,verbose)\n% NETALIGNBP Solve the network alignment problem with Belief Propagation\n%\n% \n\n% David F. Gleich, Ying Wang, and Mohsen Bayati\n% Copyright, Stanford University, 2007-2009\n% Computational Approaches to Digital Stewardship\n\n% History\n% 2009-06-02: Implemented Mohsen's new updates to get a higher overlap\n\nif ~exist('a','var') || isempty(a), a=1; end\nif ~exist('b','var') || isempty(b), b=1; end\nif ~exist('gamma','var') || isempty(gamma), gamma=0.99; end\nif ~exist('dtype', 'var') || isempty(dtype), dtype=2; end\nif ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end\nif ~exist('verbose', 'var') || isempty(verbose), verbose=1; end \n\nnedges = length(li);\nnsquares = nnz(S)/2;\nm = max(li);\nn = max(lj);\n\n% compute a vector that allows us to transpose data between squares. \n% Recall the BP algorithm requires edge(i,j) to send messages to edge(r,s)\n% when (i,j) and (r,s) form a square. However, edge(i,j) needs information\n% the information that (r,s) sent it from the previous iteraton. \n% If we imagine that each non-zero of S has a value, we want to tranpose\n% these values.\n[sui suj] = find(triu(S,1)); % only consider each square once.\nSI = sparse(sui,suj,1:length(sui),size(S,1),size(S,2)); % assign indices \nSI = SI + SI'; % SI now has symmetric indices \n[si sj sind] = find(SI);\nSP = sparse(si,sind,true,size(S,1),nsquares); % each column in SP has 2 nz\n[sij sijrs] = find(SP);\nsind = (1:nnz(SP))';\nspair = sind; spair(1:2:end) = sind(2:2:end); spair(2:2:end) = sind(1:2:end);\n% sij, sijrs maps between rows and squares\n% spair is now an indexing vector that accomplishes what we need\n\n% Initialize the messages\nma = zeros(nedges,1);\nmb = ma;\nms = zeros(nnz(S),1);\nsums = zeros(nedges,1);\n\ndamping = gamma;\ncurdamp = 1;\niter = 1;\nalpha = a;\nbeta = b;\n\n% Initialize history\nhista = zeros(maxiter,4); % history of messages from ei->a vertices\nhistb = zeros(maxiter,4); % history of messages from ei->b vertices\nfbest = 0; fbestiter = 0;\nif verbose % print the header\n fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\\n', ...\n 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ...\n 'obj_mb', 'wght_mb', 'card_mb', 'over_mb');\nend\n\n% setup the matching problem once\n[rp ci ai tripi matn matm] = bipartite_matching_setup(...\n w,li,lj,m,n); \nmperm = tripi(tripi>0); % a permutation for the matching problem\nclear ai;\n\nwhile iter<=maxiter\n prevma = ma;\n prevmb = mb;\n prevms = ms;\n prevsums = sums;\n curdamp = damping*curdamp;\n \n omaxb = max(othermaxplus(2,li,lj,mb,m,n),0);\n omaxa = max(othermaxplus(1,li,lj,ma,m,n),0);\n \n msflip = ms(spair); % swap ij->ijrs to rs->ijrs \n mymsflip = msflip+beta;\n mymsflip = min(beta,mymsflip);\n mymsflip = max(0,mymsflip);\n \n sums = accumarray(sij,mymsflip,[nedges 1],@sum,0);\n \n ma = alpha*w - omaxb + sums;\n mb = alpha*w - omaxa + sums;\n \n ms = alpha*w(sij)-(omaxb(sij) + omaxa(sij));\n ms = ms + othersum(sij,sijrs,mymsflip,nedges,nsquares);\n\n % Original updates\n if dtype==1\n ma = curdamp*(ma) + (1-curdamp)*(prevma);\n mb = curdamp*(mb) + (1-curdamp)*(prevmb);\n ms = curdamp*(ms) + (1-curdamp)*(prevms);\n elseif dtype==2\n ma = ma + (1-curdamp)*(prevma+prevmb-alpha*w+prevsums);\n mb = mb + (1-curdamp)*(prevmb+prevma-alpha*w+prevsums);\n ms = ms + (1-curdamp)*(prevms+prevms(spair)-beta);\n elseif dtype==3\n ma = curdamp*ma + (1-curdamp)*(prevma+prevmb-alpha*w+prevsums);\n mb = curdamp*mb + (1-curdamp)*(prevmb+prevma-alpha*w+prevsums);\n ms = curdamp*ms + (1-curdamp)*(prevms+prevms(spair)-beta);\n end\n \n % now compute the matchings\n hista(iter,:) = round_messages(ma,S,w,alpha,beta,rp,ci,tripi,matn,matm,mperm);\n histb(iter,:) = round_messages(mb,S,w,alpha,beta,rp,ci,tripi,matn,matm,mperm);\n if hista(iter,1)>fbest\n fbestiter=iter; mbest=ma; fbest=hista(iter,1);\n end\n if histb(iter,1)>fbest\n fbestiter=-iter; mbest=mb; fbest=histb(iter,1);\n end\n \n if verbose\n if fbestiter==iter, bestchar='*a'; \n elseif fbestiter==-iter, bestchar='*b';\n else bestchar='';\n end\n fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\\n', ...\n bestchar, iter, hista(iter,:), histb(iter,:));\n end\n iter=iter+1;\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m,perm)\nai=zeros(length(tripi),1); ai(tripi>0)=messages(perm);\n[val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m);\nmatchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*double(mi)))/2; \nf = alpha*matchweight + beta*overlap;\ninfo = [f matchweight cardinality overlap];\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction omp=othermaxplus(dim,li,lj,lw,m,n)\n% OTHERMAXPLUS Apply the other-max-plus operator to a sparse matrix\n%\n% The other-max-plus operator applies the max-plus aggegration function\n% over the rows or columns of the matrix, where, for \n% each non-zeros, the non-zero itself cannot be the maximum. Consequently,\n% Hence, it's the max-plus of all the \"other\" elements in the row or column\n% (which is controlled by dim).\n%\n% omp=othermaxplus(dim,li,lj,lw,m,n) applies the other-max-plus operator\n% to the matrix sparse(li, lj, lw, m, n). The return value omp gives\n% the other-max-plus value for each non-zero element, e.g. the matrix\n% is sparse(li, lj, omp, m, n).\n\nif dim==1\n % max-plus over cols\n i1 = lj;\n i2 = li;\n N = n;\nelse\n % max-plus over rows\n i1 = li;\n i2 = lj;\n N = m;\nend\n\n% the output of the other-max-plus is either the maximum element \n% in the row or column (if the element itself isn't the maximum) or\n% the second largest element in the row or column (if the element itself\n% IS the maximum).\n\ndimmax1 =0*ones(N,1); % largest value\ndimmax2 = 0*ones(N,1); % second largest value, \n% this is correct because of the definition of the max-plus function. \ndimmaxind = zeros(N,1); % index of largest value\nnedges = length(li);\n\nfor i=1:nedges\n if lw(i) > dimmax2(i1(i))\n if lw(i) > dimmax1(i1(i))\n dimmax2(i1(i)) = dimmax1(i1(i));\n dimmax1(i1(i)) = lw(i);\n dimmaxind(i1(i)) = i2(i);\n else\n dimmax2(i1(i)) = lw(i);\n end\n end \nend\n\nomp = zeros(size(lw));\nfor i=1:nedges\n if i2(i) == dimmaxind(i1(i))\n omp(i) = dimmax2(i1(i));\n else\n omp(i) = dimmax1(i1(i));\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction os=othersum(si,sj,s,m,n) %#ok\n% OTHERSUM Compute the sum of each column of the matrix, without each\n% individual entry. This corresponds to a matrix where each entry is the\n% sum of each column but with each entry subtracted. \n\nrowsum=accumarray(si,s,[m,1]);\nos=rowsum(si)-s; \n\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "evaluate_alignment.m", "ext": ".m", "path": "netalign-master/matlab/evaluate_alignment.m", "size": 4797, "source_encoding": "utf_8", "md5": "11f4dfb2cdec144b885fe302325fedc0", "text": "function [s Mcc]=evaluate_alignment(A,B,mi,li,lj)\n% EVALUATE_ALIGNMENT Report properties of the graph alignment\n%\n% evaluate_alignment(A,B,mi,li,lj) returns properties of an alignment\n% between graphs A and B.\n% evaluate_alignment(A,B,ma,mb) returns properties of an alignment\n% between graphs A and B.\n%\n% Edges - number of edges (2-cliques) preserved by the mapping\n% Triangles - number of triangles (3-cliques) preserved by the mapping\n% Largest Component - largest connected component with the mapping\n%\n\n% History\n% 2009-07-01: Initial coding\n\nif nargin==4\n ma = mi;\n mb = li;\n % given as pairs\n X = sparse(ma,mb,1,size(A,1),size(B,1));\nelse\n % given as an indicator\n % make sure x is binary\n if any(logical(mi)~=mi)\n error('netalign:invalidMatching',...\n 'the matching indicator mi is not binary')\n end\n X = sparse(li,lj,mi,size(A,1),size(B,1));\nend\n% make sure x is a matching\ns1 = sum(X,1);\ns2 = sum(X,2);\nif any(s1~=logical(s1)) || any(s2~=logical(s2))\n error('netalign:invalidMatching',...\n 'the given alignment is not a matching');\nend\n\n[rpA ciA] = sparse_to_csr(A);\n[rpB ciB] = sparse_to_csr(B);\nAs = struct('rp',rpA,'ci',ciA);\nBs = struct('rp',rpB,'ci',ciB);\nnA = length(rpA)-1;\nnB = length(rpB)-1;\n\n[ma mb] = find(X);\n\n% the overlapped graph\n[nedges,OA,OB]=count_overlap(As,Bs,[ma mb]);\nG = [OA X; X' OB];\n[ci,sizes] = scomponents(G);\n\n[ma mb] = find(X);\n\n\n% create the output as a structure\ns = [];\ns.size = length(ma);\n[s.largest_component,max_ci] = max(sizes);\ns.edges = count_overlap(As,Bs,[ma mb]);\ns.triangles = count_triangle_overlap(As,Bs,[ma mb]);\n\ns.largest_component_A = sum(ci(1:nA)==max_ci);\ns.largest_component_B = sum(ci(nA+1:end)==max_ci);\n\nMcc = sparse(find(ci(1:nA)==max_ci), find(ci(nA+1:end)==max_ci), 1, nA, nB);\n% display output unless requested\nif nargout == 0\n fprintf('%25s %i\\n', 'Size', s.size);\n fprintf('%25s %i\\n', 'Edge Overlap', s.edges);\n fprintf('%25s %i\\n', 'Triangle Overlap', s.triangles);\n fprintf('%25s %i\\n', 'Largest Component', s.largest_component);\n fprintf('%25s %i\\n', 'Largest Component (A)', s.largest_component_A);\n fprintf('%25s %i\\n', 'Largest Component (B)', s.largest_component_B);\nend\n \n\nfunction [ntris]=count_triangle_overlap(A,B,m)\n\nif ~isstruct(A)\n [rpA ciA] = sparse_to_csr(A);\nelse\n rpA = A.rp;\n ciA = A.ci;\nend\n\nif ~isstruct(B)\n [rpB ciB] = sparse_to_csr(B);\nelse\n rpB = B.rp;\n ciB = B.ci;\nend\n\nnA = length(rpA)-1;\nnB = length(rpB)-1;\n\n% index the matches in a to b\nmAB = zeros(nA,1);\nmAB(m(:,1)) = m(:,2);\nmBA = zeros(nB,1);\nmBA(m(:,2)) = m(:,1);\n\nntris = 0;\nnmatches = size(m,1);\n\n\naindex = zeros(nA,1);\nbindex = zeros(nB,1); % bindex is a work vector\n\nfor i=1:nmatches\n % count the number of triangles from this match\n va = m(i,1);\n vb = m(i,2);\n \n % index the neighbors in A\n for riA=rpA(va):rpA(va+1)-1\n if ciA(riA)==va, continue; end % skip self loops\n aindex(ciA(riA))=1;\n end\n \n % index the edges in B\n for riB=rpB(vb):rpB(vb+1)-1\n if ciB(riB)==vb, continue; end % skip self loops\n bindex(ciB(riB))=1;\n end\n \n % for all the edges in A, see if there is an edge in B too\n for riA=rpA(va):rpA(va+1)-1\n % va2 is the neighbor of va\n va2 = ciA(riA);\n \n % skip self-loops\n if va2 == va, continue; end \n \n va2image = mAB(va2); % get the image\n if va2image\n if bindex(va2image)\n % let's see if we can complete a triangle in A from\n % this edge\n for riA2=rpA(va2):rpA(va2+1)-1\n va3 = ciA(riA2);\n if va3 == va2, continue; end % skip self-loops\n if aindex(va3)\n % va,va2,va3 is a triangle and va,va2 is in b\n % so check if (va,va3) and (va2,va3) are \n % preserved by the mapping\n \n va3image = mAB(va3);\n if va3image && bindex(va3image)\n % (va,va3) is present, check (va2,va3)\n for riB=rpB(va2image):rpB(va2image+1)-1\n b3 = ciB(riB);\n if mBA(b3)==va3\n ntris = ntris + 1;\n end\n end\n end\n end \n end\n end\n end\n end\n \n % clear the index of edges in A\n for riA=rpA(va):rpA(va+1)-1\n aindex(ciA(riA))=0;\n end\n \n % clear the index of edges in B\n for riB=rpB(vb):rpB(vb+1)-1\n bindex(ciB(riB))=0;\n end\nend\nntris = ntris/6;\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "netalign_lagrange.m", "ext": ".m", "path": "netalign-master/matlab/netalign_lagrange.m", "size": 3194, "source_encoding": "utf_8", "md5": "c002a2f87068662095111cbc700b4541", "text": "function [xbest fupper hist] = netalign_lagrange(S,w,a,b,li,lj,stepm,rtype,maxiter,verbose)\n% NETALIGN_LAGRANGE Solve the network alignment problem\n% with Lagrangean relaxation\n% \n\n% David F. Gleich, Ying Wang, and Mohsen Bayati\n% Copyright, Stanford University, 2008-2009\n% Computational Approaches to Digital Stewardship\n\nif ~exist('a','var') || isempty(a), a=1; end\nif ~exist('b','var') || isempty(b), b=1; end\nif ~exist('stepm','var') || isempty(stepm), stepm=100; end\nif ~exist('rtype','var') || isempty(rtype), rtype=1; end\nif ~exist('maxiter', 'var') || isempty(maxiter), maxiter=1000; end\nif ~exist('verbose', 'var') || isempty(verbose), verbose=1; end \n\nm = max(li);\nn = max(lj);\n\n[rp ci ai tripi matn matm] = bipartite_matching_setup(w,li,lj,m,n); \nmperm = tripi(tripi>0); % a permutation for the matching problem\n\nS = triu(S);\nS = double(S);\nU = sparse(size(S,1),size(S,2));\nxbest = w;\nxbest(:) = 0;\n\nflower = 0;\nfupper = Inf;\nnext_reduction_iteration = stepm; % reduce the step\ngamma = 1;\n\nhist = zeros(maxiter,7);\n\nif verbose % print the header\n fprintf('%5s %4s %8s %7s %7s %7s %7s %7s %7s\\n', ...\n 'best', 'iter', 'norm-u', 'lower','upper', 'obj', 'weight', 'card', 'overlap');\nend \nfor iter = 1:maxiter\n nw = a * w + b * (sum(max(0, .5 * S + U), 2) + sum(max(0, .5 * S - U),1)');\n %[val ma mb mi]= bipartite_matching(nw,li,lj,m,n);\n ai=zeros(length(tripi),1); ai(tripi>0)=nw(mperm);\n [val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm);\n % compute statistics \n matchval = mi'*w;\n overlap = mi'*S*mi; % no divide by 2 is okay, because S = triu(S) :-).\n card = length(ma);\n f = a*matchval + b*overlap;\n \n if valflower\n flower=f;\n itermark = '*';\n xbest = mi;\n else\n itermark = ' ';\n end \n \n if rtype==1\n % no work\n elseif rtype==2\n mw = S*mi;\n mw = mw + S'*mi;\n mw = a*w + b/2*mw;\n \n ai=zeros(length(tripi),1); ai(tripi>0)=mw(mperm);\n [val ma mb mx] = bipartite_matching_primal_dual(rp,ci,ai,tripi,matn,matm);\n \n card = length(ma);\n matchval = mx'*w;\n overlap = mx'*S*mx;\n f = a*matchval + b*overlap;\n \n if f>flower\n flower=f;\n itermark = '**';\n mi = mx;\n xbest = mw;\n end\n end\n \n % report on current iter\n hist(iter,1:end) = [norm(nonzeros(U),1), flower, fupper, f, matchval, card, overlap];\n \n if verbose\n fprintf('%5s %4i %8.1e %7g %7g %7g %7g %7i %7i\\n', ...\n itermark, iter, norm(nonzeros(U),1), ...\n flower, fupper, ...\n f, matchval, card, overlap);\n end\n \n if iter==next_reduction_iteration\n gamma = gamma*0.5;\n if verbose\n fprintf('%5s %4s reducing step to %g\\n', '', '', gamma);\n end\n next_reduction_iteration = iter+stepm;\n end\n \n U = bound(U - (diag(sparse(mi)) * S - S * diag(sparse(mi))) * gamma, -.5, .5);\n \nend\n\nfunction S=bound(S,a,b)\nS=spfun(@(x) min(max(x,a),b), S);\n\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "netalignbpmr.m", "ext": ".m", "path": "netalign-master/matlab/netalignbpmr.m", "size": 4762, "source_encoding": "utf_8", "md5": "7286539d79a120310bfc2d322d442ccc", "text": "function [mbest hista histb] = netalignbpmr(S,w,a,b,li,lj,gamma,dtype,maxiter,verbose)\n% NETALIGNMBP Solve the network alignment problem with Belief Propagation\n%\n% This version of network alignment uses the matrix formulation of the \n% algorithm.\n\n% David F. Gleich, Ying Wang, and Mohsen Bayati\n% Copyright, Stanford University, 2007-2009\n% Computational Approaches to Digital Stewardship\n\nif ~exist('a','var') || isempty(a), a=1; end\nif ~exist('b','var') || isempty(b), b=1; end\nif ~exist('gamma','var') || isempty(gamma), gamma=0.99; end\nif ~exist('dtype', 'var') || isempty(dtype), dtype=2; end\nif ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end\nif ~exist('verbose', 'var') || isempty(verbose), verbose=1; end \n\nnedges = length(li); nsquares = nnz(S)/2; m = max(li); n = max(lj);\n\n% the following is elegant, but inefficient :-(\n%Ar = sparse(li,1:nedges,1,m,nedges); [ari arj arv]=find(Ar'*Ar-speye(nedges));\n%Ac = sparse(lj,1:nedges,1,n,nedges); [aci acj acv]=find(Ac'*Ac-speye(nedges));\n\n% Initialize the messages\ny = zeros(nedges,1); z = y; Sk = 0*S; \nif dtype>1, d = y; end % needed for damping scheme\n% Initialize a few parameters\ndamping = gamma; curdamp = 1; iter = 1; \n\n% Initialize history\nhista = zeros(maxiter,4); % history of messages from ei->a vertices\nhistb = zeros(maxiter,4); % history of messages from ei->b vertices\nfbest = 0; fbestiter = 0;\nif verbose % print the header\n fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\\n', ...\n 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ...\n 'obj_mb', 'wght_mb', 'card_mb', 'over_mb');\nend\n\n% setup the matching problem once\n[rp ci ai tripi matn matm] = bipartite_matching_setup(...\n w,li,lj,m,n);\nmperm = tripi(tripi>0);\n\nwhile iter<=maxiter\n curdamp = damping*curdamp;\n %Sknew = bound(Sk' + b*S,0,b);\n if dtype>1, dold=d; end\n [d,SM] = maxrowmatch(Sk' + b*S,li,lj,matn,matm);\n SM = bound(SM,0,b);\n \n ynew = a*w - max(0,implicit_maxprod(m,li,z)) + d;\n znew = a*w - max(0,implicit_maxprod(n,lj,y)) + d;\n % NOTE in comparison netalignbp, othersum isn't needed because othersum\n % of Sknew = d*S - Sknew\n Skt = diag(sparse(ynew+znew-a*w-d))*S-SM;\n if dtype==1\n Sk = curdamp*Skt+ (1-curdamp)*Sk;\n y = curdamp*ynew+(1-curdamp)*y;\n z = curdamp*znew+(1-curdamp)*z;\n elseif dtype==2\n prev = (y+z-a*w+dold);\n y = ynew+(1-curdamp)*prev;\n z = znew+(1-curdamp)*prev;\n clear prev;\n Sk = Skt + (1-curdamp)*(Sk+Sk'-b*S);\n elseif dtype==3\n prev = (y+z-a*w+dold);\n y = curdamp*ynew+(1-curdamp)*prev;\n z = curdamp*znew+(1-curdamp)*prev;\n clear prev;\n Sk = curdamp*Skt + (1-curdamp)*(Sk+Sk'-b*S);\n end\n hista(iter,:) = round_messages(y,S,w,a,b,rp,ci,tripi,matn,matm,mperm);\n histb(iter,:) = round_messages(z,S,w,a,b,rp,ci,tripi,matn,matm,mperm);\n if hista(iter,1)>fbest\n fbestiter=iter; mbest=y; fbest=hista(iter,1);\n end\n if histb(iter,1)>fbest\n fbestiter=-iter; mbest=z; fbest=histb(iter,1);\n end\n \n if verbose\n if fbestiter==iter, bestchar='*a'; \n elseif fbestiter==-iter, bestchar='*b';\n else bestchar='';\n end\n fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\\n', ...\n bestchar, iter, hista(iter,:), histb(iter,:));\n end\n iter=iter+1;\nend\n\nend\n\nfunction S=bound(S,a,b)\n S=spfun(@(x) min(b,max(x,a)),S); \nend\nfunction y=maxprod(ai,aj,av,m,x) \n y=-inf*ones(m,1);\n for i=1:numel(ai), y(ai(i)) = max(y(ai(i)),av(i)*x(aj(i))); end\nend\nfunction y=implicit_maxprod(n,ai,x)\n% implicitly compute \n% Ai=sparse(ai,1:length(ai),1,n,length(z))\n% A=Ar'*Ar - speye(length(z))\n% maxprod(A,x)\n% which has a very nice structure if you look at the actual summation\n% definition. It is just the maximum value \n N = length(ai);\n y=-inf*ones(N,1);\n max1 = -inf*ones(n,1);\n max2 = -inf*ones(n,1);\n max1ind = zeros(n,1);\n for i=1:N\n if x(i)>max2(ai(i))\n if x(i)>max1(ai(i))\n max2(ai(i)) = max1(ai(i));\n max1(ai(i)) = x(i);\n max1ind(ai(i)) = i;\n else\n max2(ai(i)) = x(i);\n end\n end\n end\n for i=1:N\n if i==max1ind(ai(i))\n y(i)=max2(ai(i));\n else\n y(i)=max1(ai(i));\n end\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m,perm)\nai=zeros(length(tripi),1); ai(tripi>0)=messages(perm);\n[val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m);\nmatchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*double(mi)))/2; \nf = alpha*matchweight + beta*overlap;\ninfo = [f matchweight cardinality overlap];\nend\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "netalignscbp.m", "ext": ".m", "path": "netalign-master/matlab/netalignscbp.m", "size": 7240, "source_encoding": "utf_8", "md5": "4d86fc6727c6040b65240c5e0079a468", "text": "function [mbest hista histb Sk] = netalignscbp(S,w,a,b,li,lj,gamma,dtype,maxiter,verbose)\n% NETALIGNMPSC Solve the network alignment problem with message passing\n%\n% This version of network alignment uses the matrix formulation of the \n% algorithm.\n\n% David F. Gleich, Ying Wang, and Mohsen Bayati\n% Copyright, Stanford University, 2010\n% Computational Approaches to Digital Stewardship\n\nif ~exist('a','var') || isempty(a), a=1; end\nif ~exist('b','var') || isempty(b), b=1; end\nif ~exist('gamma','var') || isempty(gamma), gamma=0.99; end\nif ~exist('dtype', 'var') || isempty(dtype), dtype=2; end\nif ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end\nif ~exist('verbose', 'var') || isempty(verbose), verbose=1; end \n\nnedges = length(li); nsquares = nnz(S); m = max(li); n = max(lj);\n\n% Initialize the messages\ny = zeros(nedges,1); \nz = y; % copy z as the same size\nSk = zeros(nsquares, 1); % messages and their \"reversed/transposed\" copies\nSkt = zeros(nsquares, 1);\nSw = b * ones(nsquares, 1);\nMSc = b * ones(nsquares, 4); MScnew = zeros(nsquares, 4); MP = zeros(nsquares, 4);\nif dtype>1, d = y; end % needed for damping scheme\n% Initialize a few parameters\ndamping = gamma; curdamp = 1; iter = 1; \n\n% Initialize history\nhista = zeros(maxiter,4); % history of messages from ei->a vertices\nhistb = zeros(maxiter,4); % history of messages from ei->b vertices\nfbest = 0; fbestiter = 0;\nif verbose % print the header\nfprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\\n', ...\n 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ...\n 'obj_mb', 'wght_mb', 'card_mb', 'over_mb');\nend\n\n% setup the matching problem once\n[rp ci ai tripi matn matm] = bipartite_matching_setup(...\n\t\t\t\t\t\t w,li,lj,m,n);\nmperm = tripi(tripi>0);\n[rpS ciS] = sparse_to_csr(S);\nriS = zeros(nsquares, 1);\nfor i=1:nedges\nfor j=rpS(i):rpS(i+1)-1\nriS(j) = i;\n end\nend\n\nStmp = sparse(riS, ciS, [1:nsquares]');\n[ti tj transmap] = find(Stmp);\n\nSC = findSC(S, li, lj);\nr = 1;\n\nwhile iter<=maxiter\n curdamp = damping*curdamp;\n if dtype>1, dold=d; end\n\n x = Sw;\n % updates for M_{ii'->f_i} and M_{ii'->g_{i'}}, y, z\n d = zeros(nedges, 1);\n Sk_tran = Sk(transmap);\n for i=1:nedges\n for j=rpS(i):rpS(i+1)-1\n % d(i) = d(i) + max(0, b + Sk_tran(j)) - max(0, Sk_tran(j));\nd(i) = d(i) + max(0, (r + 1) * Sw(j) + Sk_tran(j)) - max(0, r * Sw(j) + Sk_tran(j));\n end\n end\nynew = a*w - max(0,implicit_maxprod(m,li,z)) + d;\nznew = a*w - max(0,implicit_maxprod(n,lj,y)) + d;\n\n % updates for M_{ii'->h_{ii'jj'}}, Sk\n t = 0;\n for i=1:nedges\n t = ynew(i) + znew(i) - a*w(i) - d(i);\n for j=rpS(i):rpS(i+1)-1\n% Skt(j) = t - max(0, b + Sk_tran(j)) + max(0, Sk_tran(j));\n Skt(j) = t - max(0, (r + 1) * Sw(j) + Sk_tran(j)) - max(0, r * Sw(j) + Sk_tran(j));\n end\n end\n \n St = Sk + Sk(transmap) + Sw;\n \n %updates for M_{ii'jj'->h_{ii'jj'}}, Sw\n for i=1:4\n MP(:,i) = max(0, implicit_maxprod(max(SC(:,i)), SC(:,i), MSc(:, i)));\n end\n Sw = -(MP(:,1) + MP(:,2) + MP(:,3) + MP(:,4)) + b;\n \n %updates for M_{ii'jj'->d_{ii'j}}, MSc\n tmp = Sk + Sk(transmap);\n for i=1:4\n MSc(:, i) = Sw + MP(:, i) + min(tmp, min(Sk, Sk(transmap)));;\n end\n \n if dtype==1\n Sk = curdamp*Skt+ (1-curdamp)*Sk;\n y = curdamp*ynew+(1-curdamp)*y;\n z = curdamp*znew+(1-curdamp)*z;\n elseif dtype==2\n prev = (y+z-a*w+dold);\n y = ynew+(1-curdamp)*prev;\n z = znew+(1-curdamp)*prev;\n clear prev;\n Sk = Skt + (1-curdamp)*St;\n Sw = Sw + (1-curdamp)*St;\n for i=1:4\n MSc(:, i) = MSc(:, i) + (1-curdamp)*St;\n end\n elseif dtype==3\n prev = (y+z-a*w+dold);\n y = curdamp*ynew+(1-curdamp)*prev;\n z = curdamp*znew+(1-curdamp)*prev;\n clear prev;\n Sk = curdamp * Skt + (1-curdamp)*St;\n Sw = curdamp * Sw + (1-curdamp)*St;\n for i=1:4\n MSc(:, i) = curdamp * MSc(:, i) + (1-curdamp)*St;\n end\n end\n %tot = roundbyS(Sk, li, lj, riS, ciS, m, n);\n %tot2 = roundbyyz(S, y, z, li, lj, m, n);\n iter=iter+1;\n hista(iter,:) = round_messages(y,S,w,a,b,rp,ci,tripi,matn,matm,mperm);\n histb(iter,:) = round_messages(z,S,w,a,b,rp,ci,tripi,matn,matm,mperm);\n\n if hista(iter,1)>fbest\n fbestiter=iter; mbest=y; fbest=hista(iter,1);\n end\n if histb(iter,1)>fbest\n fbestiter=-iter; mbest=z; fbest=histb(iter,1);\n end\n %fbest = max(fbest, tot);\n %fbest = max(fbest, tot2);\n \n if verbose\n if fbestiter==iter, bestchar='*a'; \n elseif fbestiter==-iter, bestchar='*b';\n else bestchar='';\n end\n fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\\n', ...\n bestchar, iter, hista(iter,:), histb(iter,:));\n end\nend\n\nend\n\nfunction S=bound(S,a,b)\n S=spfun(@(x) max(b+x,a)-max(x,a),S);\nend\n\nfunction y=maxprod(ai,aj,av,m,x) \n y=-inf*ones(m,1);\n for i=1:numel(ai), y(ai(i)) = max(y(ai(i)),av(i)*x(aj(i))); end\nend\nfunction y=implicit_maxprod(n,ai,x)\n% implicitly compute \n% Ai=sparse(ai,1:length(ai),1,n,length(z))\n % A=Ar'*Ar - speye(length(z))\n% maxprod(A,x)\n% which has a very nice structure if you look at the actual summation\n% definition. It is just the maximum value \n N = length(ai);\n y=-inf*ones(N,1);\n max1 = -inf*ones(n,1);\n max2 = -inf*ones(n,1);\n max1ind = zeros(n,1);\n for i=1:N\n if x(i)>max2(ai(i))\n if x(i)>max1(ai(i))\n max2(ai(i)) = max1(ai(i));\n max1(ai(i)) = x(i);\n max1ind(ai(i)) = i;\n else\n max2(ai(i)) = x(i);\n end\n end\n end\n for i=1:N\n if i==max1ind(ai(i))\n y(i)=max2(ai(i));\n else\n y(i)=max1(ai(i));\n end\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m,perm)\nai=zeros(length(tripi),1); ai(tripi>0)=messages(perm);\n[val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m);\nmatchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*double(mi)))/2; \nf = alpha*matchweight + beta*overlap;\ninfo = [f matchweight cardinality overlap];\nend\n\nfunction tot=roundbyS(Sk, li, lj, ri, ci, m, n)\n [v ind] = sort(Sk, 'descend');\n markA = zeros(m, 1);\n markB = zeros(n, 1);\n chosen = zeros(size(li, 1), 1);\n tot = 0;\n for i=1:size(Sk, 1)\n v1 = ri(ind(i));\n v2 = ci(ind(i));\n if (v1 > v2)\n continue;\n end\n if ((~chosen(v1) && (markA(li(v1)) || markB(lj(v1)))) || (~chosen(v2) && (markA(li(v2)) || markB(lj(v2)))))\n continue;\n end\n tot = tot + 1;\n chosen(v1) = 1;\n chosen(v2) = 1;\n markA(li(v1)) = 1;\n markA(li(v2)) = 1;\n markB(lj(v1)) = 1;\n markB(lj(v2)) = 1;\n end\nend\n\nfunction tot=roundbyyz(S, y, z, li, lj, m, n)\n [v ind] = sort(y+z, 'descend');\n markA = zeros(m, 1);\n markB = zeros(n, 1);\n x = zeros(size(y));\n for i=1:size(ind,1)\n if (~markA(li(ind(i))) && ~markB(lj(ind(i))))\n x(ind(i)) = 1;\n markA(li(ind(i))) = 1;\n markB(lj(ind(i))) = 1;\n end\n end\n tot = x' * S * x / 2;\nend\n"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "expand_match.m", "ext": ".m", "path": "netalign-master/matlab/expand_match.m", "size": 2500, "source_encoding": "utf_8", "md5": "f69e78b513c268f81a604be27667dd91", "text": "function L = expand_match(A,B,L)\n% EXPAND_MATCH Expand a set of possible matchings with breadth first search\n%\n% L2 = expand_match(A,B,L) returns a new sparse match matrix L2 for the\n% network alignment problem where L2 includes the neighbors of all existing\n% matchings.\n%\n% \n\n% David F. Gleich and Ying Wang\n% Copyright, Stanford University, 2009\n\n% TODO Example\n\n% History\n% 2009-05-29 Initial coding, based on old c code\n\n\nnA = size(A,1);\n\n\n[rpB ciB vB] = sparse_to_csr(B);\n[lai laj lav] = compute_expanded_match(nA,rpB,ciB,vB,L);\nclear rpB ciB vB\n\nnB = size(B,1);\n[rpA ciA vA] = sparse_to_csr(A);\n[lbj lbi lbv] = compute_expanded_match(nB,rpA,ciA,vA,L');\nclear rpA ciA vA\n\nlai = [lai; lbi];\nlaj = [laj; lbj];\nlav = [lav; lbv];\nclear lbi lbj lbv\n\nL = sparse(lai, laj, lav, nA, nB);\n\n\n\nfunction [l2i l2j l2v]=compute_expanded_match(nA,rpB,ciB,vB,L)\n% just do one step of bfs and expand the current match\n\n% allocate edges\nl2i = zeros(nnz(L),1);\nl2j = l2i;\nl2v = l2i;\ncuredge = 0;\n\n% convert to CSR\n[rpAB ciAB vAB] = sparse_to_csr(L);\nnB = length(rpB)-1;\n% allocate temp arrays\nwork = zeros(nB,1);\nwork_used = zeros(nB,1);\ndwork = zeros(nB,1);\nfor i=1:nA\n num_adj = 0;\n for ri=rpAB(i):rpAB(i+1)-1\n j = ciAB(ri);\n deg_in_B = rpB(j+1)-rpB(j);\n for ri2=rpB(j):rpB(j+1)-1\n k = ciB(ri2);\n if work(k) == 0\n dwork(num_adj+1) = vAB(ri)/deg_in_B;\n work_used(num_adj+1) = k;\n work(k) = num_adj+1;\n num_adj = num_adj + 1;\n else\n dwork(work(k)) = max( dwork(work(k)), vAB(ri)/deg_in_B );\n end\n end\n % make sure we include j\n if work(j) == 0\n dwork(num_adj+1) = vAB(ri);\n work_used(num_adj+1) = j;\n work(j) = num_adj+1;\n num_adj = num_adj + 1;\n else\n dwork(work(k)) = max( dwork(work(k)), vAB(ri) );\n end\n end\n % copy the data and reset the arrays\n % first check if there is enough space\n while curedge + num_adj > length(l2i)\n % double the arrays\n l2i = [l2i; l2i]; l2j = [l2j; l2j]; l2v = [l2v; l2v]; %#ok\n end\n for j=1:num_adj\n curedge = curedge + 1;\n l2i(curedge) = i;\n l2j(curedge) = work_used(j);\n l2v(curedge) = dwork(j);\n work(work_used(j)) = 0;\n work_used(j) = 0;\n dwork(j) = 0;\n end\nend\n% resize at the end\nl2i = l2i(1:curedge);\nl2j = l2j(1:curedge);\nl2v = l2v(1:curedge);"} +{"plateform": "github", "repo_name": "bill-codes/netalign-master", "name": "netalignmbp.m", "ext": ".m", "path": "netalign-master/matlab/netalignmbp.m", "size": 4716, "source_encoding": "utf_8", "md5": "e294c5801bc3cd3fa0ee4deed6698ebf", "text": "function [mbest hista histb] = netalignmbp(S,w,a,b,li,lj,gamma,dtype,maxiter,verbose)\n% NETALIGNMBP Solve the network alignment problem with Belief Propagation\n%\n% This version of network alignment uses the matrix formulation of the \n% algorithm.\n\n% David F. Gleich, Ying Wang, and Mohsen Bayati\n% Copyright, Stanford University, 2007-2009\n% Computational Approaches to Digital Stewardship\n\nif ~exist('a','var') || isempty(a), a=1; end\nif ~exist('b','var') || isempty(b), b=1; end\nif ~exist('gamma','var') || isempty(gamma), gamma=0.99; end\nif ~exist('dtype', 'var') || isempty(dtype), dtype=2; end\nif ~exist('maxiter', 'var') || isempty(maxiter), maxiter=100; end\nif ~exist('verbose', 'var') || isempty(verbose), verbose=1; end \n\nnedges = length(li); nsquares = nnz(S)/2; m = max(li); n = max(lj);\n\n% the following is elegant, but inefficient :-(\n%Ar = sparse(li,1:nedges,1,m,nedges); [ari arj arv]=find(Ar'*Ar-speye(nedges));\n%Ac = sparse(lj,1:nedges,1,n,nedges); [aci acj acv]=find(Ac'*Ac-speye(nedges));\n\n% Initialize the messages\ny = zeros(nedges,1); z = y; Sk = 0*S; \nif dtype>1, d = y; end % needed for damping scheme\n% Initialize a few parameters\ndamping = gamma; curdamp = 1; iter = 1; \n\n% Initialize history\nhista = zeros(maxiter,4); % history of messages from ei->a vertices\nhistb = zeros(maxiter,4); % history of messages from ei->b vertices\nfbest = 0; fbestiter = 0;\nif verbose % print the header\n fprintf('%4s %4s %7s %7s %7s %7s %7s %7s %7s %7s\\n', ...\n 'best', 'iter', 'obj_ma', 'wght_ma', 'card_ma', 'over_ma', ...\n 'obj_mb', 'wght_mb', 'card_mb', 'over_mb');\nend\n\n% setup the matching problem once\n[rp ci ai tripi matn matm] = bipartite_matching_setup(...\n w,li,lj,m,n);\nmperm = tripi(tripi>0);\n\nwhile iter<=maxiter\n curdamp = damping*curdamp;\n Sknew = bound(Sk' + b*S,0,b);\n if dtype>1, dold=d; end\n d = sum(Sknew,2);\n \n ynew = a*w - max(0,implicit_maxprod(n,lj,z)) + d;\n znew = a*w - max(0,implicit_maxprod(m,li,y)) + d;\n % NOTE in comparison netalignbp, othersum isn't needed because othersum\n % of Sknew = d*S - Sknew\n Skt = diag(sparse(ynew+znew-a*w-d))*S-Sknew;\n if dtype==1\n Sk = curdamp*Skt+ (1-curdamp)*Sk;\n y = curdamp*ynew+(1-curdamp)*y;\n z = curdamp*znew+(1-curdamp)*z;\n elseif dtype==2\n prev = (y+z-a*w+dold);\n y = ynew+(1-curdamp)*prev;\n z = znew+(1-curdamp)*prev;\n clear prev;\n Sk = Skt + (1-curdamp)*(Sk+Sk'-b*S);\n elseif dtype==3\n prev = (y+z-a*w+dold);\n y = curdamp*ynew+(1-curdamp)*prev;\n z = curdamp*znew+(1-curdamp)*prev;\n clear prev;\n Sk = curdamp*Skt + (1-curdamp)*(Sk+Sk'-b*S);\n end\n hista(iter,:) = round_messages(y,S,w,a,b,rp,ci,tripi,matn,matm,mperm);\n histb(iter,:) = round_messages(z,S,w,a,b,rp,ci,tripi,matn,matm,mperm);\n if hista(iter,1)>fbest\n fbestiter=iter; mbest=y; fbest=hista(iter,1);\n end\n if histb(iter,1)>fbest\n fbestiter=-iter; mbest=z; fbest=histb(iter,1);\n end\n \n if verbose\n if fbestiter==iter, bestchar='*a'; \n elseif fbestiter==-iter, bestchar='*b';\n else bestchar='';\n end\n fprintf('%4s %4i %7g %7g %7i %7i %7g %7g %7i %7i\\n', ...\n bestchar, iter, hista(iter,:), histb(iter,:));\n end\n iter=iter+1;\nend\n\nend\n\nfunction S=bound(S,a,b)\n S=spfun(@(x) max(x+b,0) - max(x+a,0),S); \nend\nfunction y=maxprod(ai,aj,av,m,x) \n y=-inf*ones(m,1);\n for i=1:numel(ai), y(ai(i)) = max(y(ai(i)),av(i)*x(aj(i))); end\nend\nfunction y=implicit_maxprod(n,ai,x)\n% implicitly compute \n% Ai=sparse(ai,1:length(ai),1,n,length(z))\n% A=Ar'*Ar - speye(length(z))\n% maxprod(A,x)\n% which has a very nice structure if you look at the actual summation\n% definition. It is just the maximum value \n N = length(ai);\n y=-inf*ones(N,1);\n max1 = -inf*ones(n,1);\n max2 = -inf*ones(n,1);\n max1ind = zeros(n,1);\n for i=1:N\n if x(i)>max2(ai(i))\n if x(i)>max1(ai(i))\n max2(ai(i)) = max1(ai(i));\n max1(ai(i)) = x(i);\n max1ind(ai(i)) = i;\n else\n max2(ai(i)) = x(i);\n end\n end\n end\n for i=1:N\n if i==max1ind(ai(i))\n y(i)=max2(ai(i));\n else\n y(i)=max1(ai(i));\n end\n end\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction info=round_messages(messages,S,w,alpha,beta,rp,ci,tripi,n,m,perm)\nai=zeros(length(tripi),1); ai(tripi>0)=messages(perm);\n[val ma mb mi]= bipartite_matching_primal_dual(rp,ci,ai,tripi,n,m);\nmatchweight = sum(w(mi)); cardinality = sum(mi); overlap = (mi'*(S*double(mi)))/2; \nf = alpha*matchweight + beta*overlap;\ninfo = [f matchweight cardinality overlap];\nend\n"} +{"plateform": "github", "repo_name": "snipsco/kaldi-master", "name": "Generate_mcTrainData_cut.m", "ext": ".m", "path": "kaldi-master/egs/reverb/s5/local/Generate_mcTrainData_cut.m", "size": 7311, "source_encoding": "utf_8", "md5": "f59dd892f0f8da04a515a2c58ff50a69", "text": "function Generate_mcTrainData_cut(WSJ_dir_name, save_dir)\n%\n% Input variables:\n% WSJ_dir_name: string name of user's clean wsjcam0 corpus directory \n% (*Directory structure for wsjcam0 corpushas to be kept as it is after obtaining it from LDC. \n% Otherwise this script does not work.)\n%\n% This function generates multi-condition traiing data\n% based on the following items:\n% 1. wsjcam0 corpus (distributed from the LDC)\n% 2. room impulse responses (ones under ./RIR/)\n% 3. noise (ones under ./NOISE/).\n% Generated data has the same directory structure as original wsjcam0 corpus. \n%\n\nif nargin<2\n error('Usage: Generate_mcTrainData(WSJCAM0_data_path, save_dir) *Note that the input variable WSJCAM0_data_path should indicate the directory name of your clean WSJCAM0 corpus. '); \nend\nif exist([WSJ_dir_name,'/data/'])==0\n error(['Could not find wsjcam0 corpus : Please confirm if ',WSJ_dir_name,' is a correct path to your clean WSJCAM0 corpus']); \nend\n\nif ~exist('save_dir', 'var')\n error('You have to set the save_dir variable in the code before running this script!')\nend\n\ndisplay(['Name of directory for original wsjcam0: ',WSJ_dir_name])\ndisplay(['Name of directory to save generated multi-condition training data: ',save_dir])\nunix(['chmod u+x sphere_to_wave.csh']);\nunix(['chmod u+x bin/*']);\n\n% Parameters related to acoustic conditions\nSNRdB=20;\n\n% List of WSJ speech data\nflist1='etc/audio_si_tr.lst';\n\n%\n% List of RIRs\n%\nnum_RIRvar=24;\nRIR_sim1='./RIR/RIR_SmallRoom1_near_AnglA.wav'; \nRIR_sim2='./RIR/RIR_SmallRoom1_near_AnglB.wav'; \nRIR_sim3='./RIR/RIR_SmallRoom1_far_AnglA.wav'; \nRIR_sim4='./RIR/RIR_SmallRoom1_far_AnglB.wav'; \nRIR_sim5='./RIR/RIR_MediumRoom1_near_AnglA.wav';\nRIR_sim6='./RIR/RIR_MediumRoom1_near_AnglB.wav';\nRIR_sim7='./RIR/RIR_MediumRoom1_far_AnglA.wav'; \nRIR_sim8='./RIR/RIR_MediumRoom1_far_AnglB.wav'; \nRIR_sim9='./RIR/RIR_LargeRoom1_near_AnglA.wav'; \nRIR_sim10='./RIR/RIR_LargeRoom1_near_AnglB.wav';\nRIR_sim11='./RIR/RIR_LargeRoom1_far_AnglA.wav'; \nRIR_sim12='./RIR/RIR_LargeRoom1_far_AnglB.wav'; \nRIR_sim13='./RIR/RIR_SmallRoom2_near_AnglA.wav';\nRIR_sim14='./RIR/RIR_SmallRoom2_near_AnglB.wav';\nRIR_sim15='./RIR/RIR_SmallRoom2_far_AnglA.wav'; \nRIR_sim16='./RIR/RIR_SmallRoom2_far_AnglB.wav'; \nRIR_sim17='./RIR/RIR_MediumRoom2_near_AnglA.wav';\nRIR_sim18='./RIR/RIR_MediumRoom2_near_AnglB.wav';\nRIR_sim19='./RIR/RIR_MediumRoom2_far_AnglA.wav'; \nRIR_sim20='./RIR/RIR_MediumRoom2_far_AnglB.wav'; \nRIR_sim21='./RIR/RIR_LargeRoom2_near_AnglA.wav'; \nRIR_sim22='./RIR/RIR_LargeRoom2_near_AnglB.wav'; \nRIR_sim23='./RIR/RIR_LargeRoom2_far_AnglA.wav'; \nRIR_sim24='./RIR/RIR_LargeRoom2_far_AnglB.wav'; \n\n%\n% List of noise\n% \nnum_NOISEvar=6;\nnoise_sim1='./NOISE/Noise_SmallRoom1';\nnoise_sim2='./NOISE/Noise_MediumRoom1';\nnoise_sim3='./NOISE/Noise_LargeRoom1';\nnoise_sim4='./NOISE/Noise_SmallRoom2';\nnoise_sim5='./NOISE/Noise_MediumRoom2';\nnoise_sim6='./NOISE/Noise_LargeRoom2';\n\n%\n% Start generating noisy reverberant data with creating new directories\n%\n\nfcount=1;\nrcount=1;\nncount=1;\n\nif save_dir(end)=='/';\n save_dir_tr=[save_dir,'data/mc_train/'];\nelse\n save_dir_tr=[save_dir,'/data/mc_train/'];\nend\nmkdir([save_dir_tr]);\n%mkdir([save_dir,'/taskfiles/'])\n\nmic_idx=['A';'B';'C';'D';'E';'F';'G';'H'];\nprev_fname='dummy';\n\nfor nlist=1:1\n % Open file list\n eval(['fid=fopen(flist',num2str(nlist),',''r'');']);\n\n while 1\n \n % Set data file name\n fname=fgetl(fid);\n if ~ischar(fname);\n break;\n end\n \n idx1=find(fname=='/'); \n \n % Make directory if there isn't any\n if ~strcmp(prev_fname,fname(1:idx1(end)))\n mkdir([save_dir_tr fname(1:idx1(end))])\n end\n prev_fname=fname(1:idx1(end));\n \n % load (sphere format) speech signal \n x=read_sphere([WSJ_dir_name,'/data/', fname]);\n x=x/(2^15); % conversion from short-int to float\n \n % load RIR and noise for \"THIS\" utterance\n eval(['RIR=wavread(RIR_sim',num2str(rcount),');']);\n eval(['NOISE=wavread([noise_sim',num2str(ceil(rcount/4)),',''_',num2str(ncount),'.wav'']);']);\n\n % Generate 8ch noisy reverberant data \n y=gen_obs(x,RIR,NOISE,SNRdB);\n\n % cut to length of original signal\n y = y(1:size(x,2),:);\n \n % rotine to cyclicly switch RIRs and noise, utterance by utterance \n rcount=rcount+1;\n if rcount>num_RIRvar;rcount=1;ncount=ncount+1;end\n if ncount>10;ncount=1;end\n\n % save the data\n\n y=y/4; % common normalization to all the data to prevent clipping\n % denominator was decided experimentally\n\n for ch=1:8 \n eval(['wavwrite(y(:,',num2str(ch),'),16000,''',save_dir_tr fname,'_ch',num2str(ch),'.wav'');']);\n end\n \n display(['sentence ',num2str(fcount),' (out of 7861) finished! (Multi-condition training data)'])\n fcount=fcount+1;\n\n end\nend\n\n\n%%%%\nfunction [y]=gen_obs(x,RIR,NOISE,SNRdB)\n% function to generate noisy reverberant data\n\nx=x';\n\n% calculate direct+early reflection signal for calculating SNR\n[val,delay]=max(RIR(:,1));\nbefore_impulse=floor(16000*0.001);\nafter_impulse=floor(16000*0.05);\nRIR_direct=RIR(delay-before_impulse:delay+after_impulse,1);\ndirect_signal=fconv(x,RIR_direct);\n\n% obtain reverberant speech\nfor ch=1:8\n rev_y(:,ch)=fconv(x,RIR(:,ch));\nend\n\n% normalize noise data according to the prefixed SNR value\nNOISE=NOISE(1:size(rev_y,1),:);\nNOISE_ref=NOISE(:,1);\n\niPn = diag(1./mean(NOISE_ref.^2,1));\nPx = diag(mean(direct_signal.^2,1));\nMsnr = sqrt(10^(-SNRdB/10)*iPn*Px);\nscaled_NOISE = NOISE*Msnr;\ny = rev_y + scaled_NOISE;\ny = y(delay:end,:);\n\n\n%%%%\nfunction [y]=fconv(x, h)\n%FCONV Fast Convolution\n% [y] = FCONV(x, h) convolves x and h, and normalizes the output \n% to +-1.\n%\n% x = input vector\n% h = input vector\n% \n% See also CONV\n%\n% NOTES:\n%\n% 1) I have a short article explaining what a convolution is. It\n% is available at http://stevem.us/fconv.html.\n%\n%\n%Version 1.0\n%Coded by: Stephen G. McGovern, 2003-2004.\n%\n%Copyright (c) 2003, Stephen McGovern\n%All rights reserved.\n%\n%THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n%AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n%IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n%ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n%LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n%CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n%SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n%INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n%CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n%ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n%POSSIBILITY OF SUCH DAMAGE.\n\nLy=length(x)+length(h)-1; % \nLy2=pow2(nextpow2(Ly)); % Find smallest power of 2 that is > Ly\nX=fft(x, Ly2);\t\t % Fast Fourier transform\nH=fft(h, Ly2);\t % Fast Fourier transform\nY=X.*H; \t % \ny=real(ifft(Y, Ly2)); % Inverse fast Fourier transform\ny=y(1:1:Ly); % Take just the first N elements\n"} +{"plateform": "github", "repo_name": "h-delgado/binary-key-diarizer-master", "name": "pdist22.m", "ext": ".m", "path": "binary-key-diarizer-master/matlab/external/pdist22.m", "size": 5461, "source_encoding": "utf_8", "md5": "173103b09eefbe457c081a3d41cddd3d", "text": "% This function belongs to Piotr Dollar's Toolbox\n% http://vision.ucsd.edu/~pdollar/toolbox/doc/index.html\n% Please refer to the above web page for definitions and clarifications\n%\n% Calculates the distance between sets of vectors.\n%\n% Let X be an m-by-p matrix representing m points in p-dimensional space\n% and Y be an n-by-p matrix representing another set of points in the same\n% space. This function computes the m-by-n distance matrix D where D(i,j)\n% is the distance between X(i,:) and Y(j,:). This function has been\n% optimized where possible, with most of the distance computations\n% requiring few or no loops.\n%\n% The metric can be one of the following:\n%\n% 'euclidean' / 'sqeuclidean':\n% Euclidean / SQUARED Euclidean distance. Note that 'sqeuclidean'\n% is significantly faster.\n%\n% 'chisq'\n% The chi-squared distance between two vectors is defined as:\n% d(x,y) = sum( (xi-yi)^2 / (xi+yi) ) / 2;\n% The chi-squared distance is useful when comparing histograms.\n%\n% 'cosine'\n% Distance is defined as the cosine of the angle between two vectors.\n%\n% 'emd'\n% Earth Mover's Distance (EMD) between positive vectors (histograms).\n% Note for 1D, with all histograms having equal weight, there is a simple\n% closed form for the calculation of the EMD. The EMD between histograms\n% x and y is given by the sum(abs(cdf(x)-cdf(y))), where cdf is the\n% cumulative distribution function (computed simply by cumsum).\n%\n% 'L1'\n% The L1 distance between two vectors is defined as: sum(abs(x-y));\n%\n%\n% USAGE\n% D = pdist2( X, Y, [metric] )\n%\n% INPUTS\n% X - [m x p] matrix of m p-dimensional vectors\n% Y - [n x p] matrix of n p-dimensional vectors\n% metric - ['sqeuclidean'], 'chisq', 'cosine', 'emd', 'euclidean', 'L1'\n%\n% OUTPUTS\n% D - [m x n] distance matrix\n%\n% EXAMPLE\n% [X,IDX] = demoGenData(100,0,5,4,10,2,0);\n% D = pdist2( X, X, 'sqeuclidean' );\n% distMatrixShow( D, IDX );\n%\n% See also PDIST, DISTMATRIXSHOW\n\n% Piotr's Image&Video Toolbox Version 2.0\n% Copyright (C) 2007 Piotr Dollar. [pdollar-at-caltech.edu]\n% Please email me if you find bugs, or have suggestions or questions!\n% Licensed under the Lesser GPL [see external/lgpl.txt]\n\nfunction D = pdist2( X, Y, metric )\n\nif( nargin<3 || isempty(metric) ); metric=0; end;\n\nswitch metric\n case {0,'sqeuclidean'}\n D = distEucSq( X, Y );\n case 'euclidean'\n D = sqrt(distEucSq( X, Y ));\n case 'L1' \n D = distL1( X, Y );\n case 'cosine'\n D = distCosine( X, Y );\n case 'emd'\n D = distEmd( X, Y );\n case 'chisq'\n D = distChiSq( X, Y );\n otherwise\n error(['pdist2 - unknown metric: ' metric]);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction D = distL1( X, Y )\n\nm = size(X,1); n = size(Y,1);\nmOnes = ones(1,m); D = zeros(m,n);\nfor i=1:n\n yi = Y(i,:); yi = yi( mOnes, : );\n D(:,i) = sum( abs( X-yi),2 );\nend\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction D = distCosine( X, Y )\n\nif( ~isa(X,'double') || ~isa(Y,'double'))\n error( 'Inputs must be of type double'); end;\n\np=size(X,2);\nXX = sqrt(sum(X.*X,2)); X = X ./ XX(:,ones(1,p));\nYY = sqrt(sum(Y.*Y,2)); Y = Y ./ YY(:,ones(1,p));\nD = 1 - X*Y';\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction D = distEmd( X, Y )\n\nXcdf = cumsum(X,2);\nYcdf = cumsum(Y,2);\n\nm = size(X,1); n = size(Y,1);\nmOnes = ones(1,m); D = zeros(m,n);\nfor i=1:n\n ycdf = Ycdf(i,:);\n ycdfRep = ycdf( mOnes, : );\n D(:,i) = sum(abs(Xcdf - ycdfRep),2);\nend\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction D = distChiSq( X, Y )\n\n%%% supposedly it's possible to implement this without a loop!\nm = size(X,1); n = size(Y,1);\nmOnes = ones(1,m); D = zeros(m,n);\nfor i=1:n\n yi = Y(i,:); yiRep = yi( mOnes, : );\n s = yiRep + X; d = yiRep - X;\n D(:,i) = sum( d.^2 ./ (s+eps), 2 );\nend\nD = D/2;\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nfunction D = distEucSq( X, Y )\n\n%if( ~isa(X,'double') || ~isa(Y,'double'))\n % error( 'Inputs must be of type double'); end;\nm = size(X,1); n = size(Y,1);\n%Yt = Y';\nXX = sum(X.*X,2);\nYY = sum(Y'.*Y',1);\nD = XX(:,ones(1,n)) + YY(ones(1,m),:) - 2*X*Y';\n\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% function D = distEucSq( X, Y )\n%%%% code from Charles Elkan with variables renamed\n% m = size(X,1); n = size(Y,1);\n% D = sum(X.^2, 2) * ones(1,n) + ones(m,1) * sum(Y.^2, 2)' - 2.*X*Y';\n\n\n%%% LOOP METHOD - SLOW\n% [m p] = size(X);\n% [n p] = size(Y);\n%\n% D = zeros(m,n);\n% onesM = ones(m,1);\n% for i=1:n\n% y = Y(i,:);\n% d = X - y(onesM,:);\n% D(:,i) = sum( d.*d, 2 );\n% end\n\n\n%%% PARALLEL METHOD THAT IS SUPER SLOW (slower then loop)!\n% % From \"MATLAB array manipulation tips and tricks\" by Peter J. Acklam\n% Xb = permute(X, [1 3 2]);\n% Yb = permute(Y, [3 1 2]);\n% D = sum( (Xb(:,ones(1,n),:) - Yb(ones(1,m),:,:)).^2, 3);\n\n\n%%% USELESS FOR EVEN VERY LARGE ARRAYS X=16000x1000!! and Y=100x1000\n% call recursively to save memory\n% if( (m+n)*p > 10^5 && (m>1 || n>1))\n% if( m>n )\n% X1 = X(1:floor(end/2),:);\n% X2 = X((floor(end/2)+1):end,:);\n% D1 = distEucSq( X1, Y );\n% D2 = distEucSq( X2, Y );\n% D = cat( 1, D1, D2 );\n% else\n% Y1 = Y(1:floor(end/2),:);\n% Y2 = Y((floor(end/2)+1):end,:);\n% D1 = distEucSq( X, Y1 );\n% D2 = distEucSq( X, Y2 );\n% D = cat( 2, D1, D2 );\n% end\n% return;\n% end\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "bern_sem_basis.m", "ext": ".m", "path": "WADG_Matlab-master/bern_sem_basis.m", "size": 1476, "source_encoding": "utf_8", "md5": "a00141b6425a6b137bfc093d5ed345aa", "text": "% wedge basis \n% function V = bern_sem_basis(N,r,s,t)\n% Vtri = bern_tri(N,r(:),s(:));\n% % [r2D s2D] = Nodes2D(N); [r2D s2D] = xytors(r2D,s2D);\n% % VWB = Vandermonde2D(N,r2D,s2D); Vtri = Vandermonde2D(N,r(:),s(:))/VWB;\n% r1D = JacobiGL(0,0,N);\n% VSEM = Vandermonde1D(N,r1D(:));\n% V1D = Vandermonde1D(N,t(:))/VSEM; % sem in vertical direction\n% \n% Np = (N+1)*(N+2)/2;\n% \n% sk = 1;\n% for i = 1:N+1\n% for j = 1:Np\n% V(:,sk) = Vtri(:,j).*V1D(:,i);\n% sk = sk + 1;\n% end\n% end\n\nfunction [V Vr Vs Vt V1 V2 V3] = bern_sem_basis(N,r,s,t)\n\n% [Vtri Vrtri Vstri V1tri V2tri V3tri] = bern_tri(N,r(:),s(:));\n\n[r2D s2D] = Nodes2D(N); [r2D s2D] = xytors(r2D,s2D);\nVWB = Vandermonde2D(N,r2D,s2D);\nVtri = Vandermonde2D(N,r(:),s(:))/VWB;\n[Vrtri Vstri] = GradVandermonde2D(N,r(:),s(:));\nVrtri = Vrtri/VWB; Vstri = Vstri/VWB;\nV1tri = Vrtri*0; V2tri = Vrtri*0; V3tri = Vrtri*0; % dummy arrays\n\nr1D = JacobiGL(0,0,N);\nVSEM = Vandermonde1D(N,r1D(:));\nV1D = Vandermonde1D(N,t(:))/VSEM; % sem in vertical direction\nVt1D = GradVandermonde1D(N,t(:))/VSEM; % sem in vertical direction\n\nNptri = (N+1)*(N+2)/2;\n\nsk = 1;\nfor i = 1:N+1\n for j = 1:Nptri\n V(:,sk) = Vtri(:,j).*V1D(:,i);\n Vr(:,sk) = Vrtri(:,j).*V1D(:,i);\n Vs(:,sk) = Vstri(:,j).*V1D(:,i);\n Vt(:,sk) = Vtri(:,j).*Vt1D(:,i);\n V1(:,sk) = V1tri(:,j).*V1D(:,i);\n V2(:,sk) = V2tri(:,j).*V1D(:,i);\n V3(:,sk) = V3tri(:,j).*V1D(:,i);\n sk = sk + 1;\n end\nend"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "bern_basis_1D.m", "ext": ".m", "path": "WADG_Matlab-master/bern_basis_1D.m", "size": 424, "source_encoding": "utf_8", "md5": "d9d840acea7aa008762de1bb0bfe1d93", "text": "function [V Vr] = bern_basis_1D(N,r)\n\nr = (1+r)/2; % convert to unit\nfor i = 0:N\n V(:,i+1) = bern_1D(N,i,r);\n Vr(:,i+1) = d_bern(N,i,r)*.5; % change of vars\nend\n\nfunction bi = bern_1D(N,i,r)\n\nbi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i);\n\nfunction dbi = d_bern(N,i,r)\n\nif (i==0)\n dbi = -N*(1-r).^(N-1);\nelseif (i==N)\n dbi = N*(r.^(N-1));\nelse\n dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r);\nend\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "bern_quad.m", "ext": ".m", "path": "WADG_Matlab-master/bern_quad.m", "size": 689, "source_encoding": "utf_8", "md5": "355d83ac78285e23030c96d0fadf8fcc", "text": "function [V Vr Vs] = bern_quad(N,r,s)\n\nr = (1+r)/2; % convert to unit\ns = (1+s)/2; % convert to unit\n\nV = zeros(length(r),(N+1)^2);\nVr = zeros(length(r),(N+1)^2);\nVs = zeros(length(r),(N+1)^2);\nsk = 1;\nfor j = 0:N\n for i = 0:N \n V(:,sk) = bern_1D(N,i,r).*bern_1D(N,j,s);\n Vr(:,sk) = .5*d_bern_1D(N,i,r).*bern_1D(N,j,s);\n Vs(:,sk) = .5*bern_1D(N,i,r).*d_bern_1D(N,j,s);\n sk = sk + 1;\n end\nend\n\nfunction bi = bern_1D(N,i,r)\n\nbi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i);\n\nfunction dbi = d_bern_1D(N,i,r)\n\nif (i==0)\n dbi = -N*(1-r).^(N-1);\nelseif (i==N)\n dbi = N*(r.^(N-1));\nelse\n dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r);\nend\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "bern_basis_tet.m", "ext": ".m", "path": "WADG_Matlab-master/bern_basis_tet.m", "size": 1786, "source_encoding": "utf_8", "md5": "402f402665ab18ed94d19eb13672619c", "text": "% V = VDM. Vrst = deriv matrices. V1-4 barycentric derivs. ids =\n% permutation to match equispaced node ordering on tet. \n\nfunction [V, Vr, Vs, Vt, V1, V2, V3, V4, id] = bern_basis_tet(N,r,s,t)\n\n%[L1 L2 L3 L4] = rsttobary(r,s,t);\n\nL1 = -(1+r+s+t)/2;\nL2 = (1+r)/2;\nL3 = (1+s)/2;\nL4 = (1+t)/2;\ndL1r = -.5; dL2r = .5; dL3r = 0; dL4r = 0;\ndL1s = -.5; dL2s = 0; dL3s = .5; dL4s = 0;\ndL1t = -.5; dL2t = 0; dL3t = 0; dL4t = .5;\n\nsk = 1;\nfor l = 0:N\n for k = 0:N-l\n for j = 0:N-k-l;\n i = N-j-k-l;\n C=factorial(N)/(factorial(i)*factorial(j)*factorial(k)*factorial(l));\n% C = 1;\n V(:,sk) = C*(L1.^i).*(L2.^j).*(L3.^k).*(L4.^l);\n \n dL1 = C*i*(L1.^(i-1)).*(L2.^j).*(L3.^k).*(L4.^l);\n dL2 = C*j*(L1.^(i)).*(L2.^(j-1)).*(L3.^k).*(L4.^l);\n dL3 = C*k*(L1.^(i)).*(L2.^j).*(L3.^(k-1)).*(L4.^l);\n dL4 = C*l*(L1.^(i)).*(L2.^j).*(L3.^k).*(L4.^(l-1));\n if i==0\n dL1 = zeros(size(dL1));\n end\n if j==0\n dL2 = zeros(size(dL1));\n end\n if k ==0\n dL3 = zeros(size(dL1));\n end\n if l ==0\n dL4 = zeros(size(dL1));\n end\n Vr(:,sk) = dL1.*dL1r + dL2.*dL2r + dL3.*dL3r + dL4.*dL4r;\n Vs(:,sk) = dL1.*dL1s + dL2.*dL2s + dL3.*dL3s + dL4.*dL4s;\n Vt(:,sk) = dL1.*dL1t + dL2.*dL2t + dL3.*dL3t + dL4.*dL4t;\n V1(:,sk) = dL1;\n V2(:,sk) = dL2;\n V3(:,sk) = dL3;\n V4(:,sk) = dL4;\n sk = sk + 1;\n end\n end\nend\n\nfunction bi = bern(N,i,r)\n\nbi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i);\n\nfunction dbi = d_bern(N,i,r)\n\ndbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r);\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "Wave3D.m", "ext": ".m", "path": "WADG_Matlab-master/Wave3D.m", "size": 4005, "source_encoding": "utf_8", "md5": "61a2d10ebd5610a1443301f0f99b2ba0", "text": "clear\n\nGlobals3D;\n\nN = 4;\nFinalTime = 1;\ncfun = @(x,y,z) ones(size(x));\n%cfun = @(x,y,z) 1 + 0.5*sin(pi*x).*sin(pi*y).*sin(pi*z); % smooth velocity\n%cfun = @(x,y,z) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity\n\n%pfun = @(x,y,z,t) cos(pi*x).*cos(pi*y).*cos(pi*z).*cos(sqrt(3)*pi*t);\n\n pfun = @(x,y,z,t) sin(pi*x).*sin(pi*y).*sin(pi*z).*cos(pi*t);\n ufun = @(x,y,z,t) -cos(pi*x).*sin(pi*y).*sin(pi*z).*sin(pi*t);\n vfun = @(x,y,z,t) -sin(pi*x).*cos(pi*y).*sin(pi*z).*sin(pi*t);\n wfun = @(x,y,z,t) -sin(pi*x).*sin(pi*y).*cos(pi*z).*sin(pi*t);\n %ffun = @(x,y,z,t) sqrt(3)*pi*(1-1./cfun(x,y,z)).*cos(pi*x).*cos(pi*y).*cos(pi*z).*sin(sqrt(3)*pi*t);\n ffun = @(x,y,z,t) pi*2*sin(pi*x).*sin(pi*y).*sin(pi*z).*sin(pi*t);\n\n%generate 3D mesh\n[Nv, VX, VY, VZ, K, EToV] = MeshReaderGmsh3D('cube2.msh');\n\nStartUp3D;\n\n\nDr(abs(Dr)<1e-8) = 0; \n\nNq = 2*N+1;\n\n[rq sq tq wq] = tet_cubature(Nq); % integrate u*v*c\n\nVq = Vandermonde3D(N,rq,sq,tq)/V;\n\nxq = Vq*x; yq = Vq*y; zq=Vq*z;\n \nPq=V*V'*Vq'*diag(wq);\n \nCq = cfun(xq,yq,zq);\n\nLift3D(N, r, s, t);\n% %% Adptive m on each element\n% VMq = Vandermonde3D(M,rq,sq,tq);\n% CqM = VMq*VMq'*diag(wq)*Cq;\n\n\n\n%% initial condition\np = pfun(x,y,z,0);\nu = ufun(x,y,z,0);\nv = vfun(x,y,z,0);\nw = wfun(x,y,z,0);\n\n% p = pfun(x,y,z,0);\n% u = zeros(Np,K);\n% v = zeros(Np,K);\n% w = zeros(Np,K);\n\n\n\n%%\ntime = 0;\n\n% Runge-Kutta residual storage\nresu = zeros(Np,K); resv = zeros(Np,K); resw = zeros(Np,K); resp = zeros(Np,K);\n\nCN = (N+1)*(N+2)*(N+3)/6; % trace inequality constant\nCNh = max(CN*max(Fscale(:)));\ndt = 2/CNh;\n\n%dt = 0.00390625; %coincide with the time step in occa\n% outer time step loop\ntstep = 0;\n\n\n\n\nwhile (timeFinalTime), dt = FinalTime-time; end\n \n for INTRK = 1:5\n \n timelocal = time + rk4c(INTRK)*dt;\n \n f=ffun(x,y,z,timelocal);\n \n [rhsp, rhsu, rhsv, rhsw] = acousticsRHS3D_WADG(p,u,v,w,f);\n \n % initiate and increment Runge-Kutta residuals\n resp = rk4a(INTRK)*resp + dt*rhsp;\n resu = rk4a(INTRK)*resu + dt*rhsu;\n resv = rk4a(INTRK)*resv + dt*rhsv;\n resw = rk4a(INTRK)*resw + dt*rhsw;\n \n % update fields\n u = u+rk4b(INTRK)*resu;\n v = v+rk4b(INTRK)*resv;\n w = w+rk4b(INTRK)*resw;\n p = p+rk4b(INTRK)*resp;\n \n \n end\n \n time = time+dt; tstep = tstep+1;\n\n \n \n \nend\n\np_exact = pfun(x,y,z,FinalTime);\n\np_exact_quadrature = pfun(xq,yq,zq,FinalTime);\n\np_quadrature = Vq * p;\n\n[d1,d2]=size(p_quadrature);\n\nerror_accumulation = 0;\n\nfor j1=1:d2\n for j2=1:d1\n err = p_quadrature(j2,j1)-p_exact_quadrature(j2,j1);\n error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1);\n end\nend\n\nerror_l2 = sqrt(error_accumulation)\n%error_fro = norm(p-p_exact,'fro'); \n\n\n\nfunction [rhsp, rhsu, rhsv, rhsw] = acousticsRHS3D_WADG(p,u,v,w,f)\n\nGlobals3D;\n\n% Define field differences at faces\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM);\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM);\ndv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM);\ndw = zeros(Nfp*Nfaces,K); dw(:) = w(vmapP)-w(vmapM);\n\n% evaluate upwind fluxes\nndotdU = nx.*du + ny.*dv + nz.*dw;\n\n% % Impose reflective boundary conditions (p+ = -p-)\n% ndotdU(mapB) = 0;\n% dp(mapB) = -2*p(vmapB);\n\n% Impose Dirichlet BCs\nndotdU(mapB) = 0;\np(vmapB) = 0;\ndp(mapB) = 0;\n\n\ntau = 1;\nfluxp = tau*dp - ndotdU;\nfluxu = (tau*ndotdU - dp).*nx;\nfluxv = (tau*ndotdU - dp).*ny;\nfluxw = (tau*ndotdU - dp).*nz;\n\npr = Dr*p; ps = Ds*p; pt = Dt*p;\n\ndpdx = rx.*pr + sx.*ps + tx.*pt;\ndpdy = ry.*pr + sy.*ps + ty.*pt;\ndpdz = rz.*pr + sz.*ps + tz.*pt;\n\ndivU = Dr*(u.*rx + v.*ry + w.*rz) + Ds*(u.*sx + v.*sy + w.*sz)+ Dt*(u.*tx + v.*ty + w.*tz);\n\n% compute right hand sides of the PDE's\nrhsp = -divU + f + LIFT*(Fscale.*fluxp)/2.0;\nrhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0;\nrhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0;\nrhsw = -dpdz + LIFT*(Fscale.*fluxw)/2.0;\n\nrhsp = Pq*(Cq.*(Vq*rhsp));\n\nreturn;\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "bern_hex.m", "ext": ".m", "path": "WADG_Matlab-master/bern_hex.m", "size": 930, "source_encoding": "utf_8", "md5": "c1ba4aade744a74da97433f578142f21", "text": "function [V Vr Vs Vt] = bern_hex(N,r,s,t)\n\nr = (1+r)/2; % convert to unit\ns = (1+s)/2; % convert to unit\nt = (1+t)/2; % convert to unit\n\nNp = (N+1)^3;\nV = zeros(length(r),Np);\nVr = zeros(length(r),Np);\nVs = zeros(length(r),Np);\nVt = zeros(length(r),Np);\nsk = 1;\nfor k = 0:N\n for j = 0:N\n for i = 0:N\n \n V(:,sk) = bern_1D(N,i,r).*bern_1D(N,j,s).*bern_1D(N,k,t);\n Vr(:,sk) = .5*d_bern_1D(N,i,r).*bern_1D(N,j,s).*bern_1D(N,k,t);\n Vs(:,sk) = .5*bern_1D(N,i,r).*d_bern_1D(N,j,s).*bern_1D(N,k,t);\n Vt(:,sk) = .5*bern_1D(N,i,r).*bern_1D(N,j,s).*d_bern_1D(N,k,t);\n sk = sk + 1;\n end\n end\nend\n\nfunction bi = bern_1D(N,i,r)\n\nbi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i);\n\nfunction dbi = d_bern_1D(N,i,r)\n\nif (i==0)\n dbi = -N*(1-r).^(N-1);\nelseif (i==N)\n dbi = N*(r.^(N-1));\nelse\n dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r);\nend\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "bern_tet.m", "ext": ".m", "path": "WADG_Matlab-master/bern_tet.m", "size": 2132, "source_encoding": "utf_8", "md5": "4dc141800a89b218f1b7dff33be86eef", "text": "% V = VDM. Vrst = deriv matrices. V1-4 barycentric derivs. ids =\n% permutation to match equispaced node ordering on tet. \n\n% function [V Vr Vs Vt V1 V2 V3 V4 id] = bern_basis_tet(N,r,s,t)\n% \n% % use equivalence between W&B and equispaced nodes - get ordering\n% [re se te] = EquiNodes3D(N);\n% Ve = bern_tet(N,re,se,te);\n% for i = 1:size(Ve,2)\n% [val iid] = max(Ve(:,i)); \n% id(i) = iid;\n% end\n% \n% [V Vr Vs Vt V1 V2 V3 V4] = bern_tet(N,r,s,t);\n% V = V(:,id);\n% Vr = Vr(:,id);\n% Vs = Vs(:,id);\n% Vt = Vt(:,id);\n% V1 = V1(:,id);\n% V2 = V2(:,id);\n% V3 = V3(:,id);\n% V4 = V4(:,id);\n\nfunction [V Vr Vs Vt V1 V2 V3 V4] = bern_tet(N,r,s,t)\n\n% [L1 L2 L3 L4] = rsttobary(r,s,t);\nL1 = -(1+r+s+t)/2;\nL2 = (1+r)/2;\nL3 = (1+s)/2;\nL4 = (1+t)/2;\n\ndL1r = -.5; dL2r = .5; dL3r = 0; dL4r = 0;\ndL1s = -.5; dL2s = 0; dL3s = .5; dL4s = 0;\ndL1t = -.5; dL2t = 0; dL3t = 0; dL4t = .5;\n\nsk = 1;\n% for i = 0:N\n% for j = 0:N-i\n% for k = 0:N-i-j\n% l = N-i-j-k;\nfor l = 0:N\n for k = 0:N-l\n for j = 0:N-l-k\n i = N-j-k-l;\n C=factorial(N)/(factorial(i)*factorial(j)*factorial(k)*factorial(l));\n V(:,sk) = C*(L1.^i).*(L2.^j).*(L3.^k).*(L4.^l);\n \n dL1 = C*i*(L1.^(i-1)).*(L2.^j).*(L3.^k).*(L4.^l);\n dL2 = C*j*(L1.^(i)).*(L2.^(j-1)).*(L3.^k).*(L4.^l);\n dL3 = C*k*(L1.^(i)).*(L2.^j).*(L3.^(k-1)).*(L4.^l);\n dL4 = C*l*(L1.^(i)).*(L2.^j).*(L3.^k).*(L4.^(l-1));\n if i==0\n dL1 = zeros(size(dL1));\n end\n if j==0\n dL2 = zeros(size(dL1));\n end\n if k ==0\n dL3 = zeros(size(dL1));\n end\n if l ==0\n dL4 = zeros(size(dL1));\n end\n Vr(:,sk) = dL1.*dL1r + dL2.*dL2r + dL3.*dL3r + dL4.*dL4r;\n Vs(:,sk) = dL1.*dL1s + dL2.*dL2s + dL3.*dL3s + dL4.*dL4s;\n Vt(:,sk) = dL1.*dL1t + dL2.*dL2t + dL3.*dL3t + dL4.*dL4t;\n V1(:,sk) = dL1;\n V2(:,sk) = dL2;\n V3(:,sk) = dL3;\n V4(:,sk) = dL4;\n sk = sk + 1;\n end\n end\nend\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "Wave2D_mesh_fullquadrature.m", "ext": ".m", "path": "WADG_Matlab-master/Wave2D_mesh_fullquadrature.m", "size": 4216, "source_encoding": "utf_8", "md5": "8353d0375b964df4092a4909937506a5", "text": "clear\nGlobals2D\n\nkd=[4 8 16 32];\nh=2./kd;\nN = 4;\nM = 1;\n\nfor i = 1:length(kd)\n\nK1D = kd(i);\nFinalTime = 1.0;\n[Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D);\nStartUp2D;\n\n%% Set up wavespeed function\n%cfun = @(x,y) ones(size(x));\ncfun = @(x,y) 1+ sin(pi*x).*sin(pi*y); % smooth velocity\n%cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity\n\n%% generate quadrature points\nNq = 2*N+1;\n[rq sq wq] = Cubature2D(Nq); % integrate u*v*c\nVq = Vandermonde2D(N,rq,sq)/V;\nxq = Vq*x; yq = Vq*y;\n\n%% construct the projection matrix for nodal basis Pq\nPq = V*V'*Vq'*diag(wq);\n\n%% construct matrix Cq\nCq = cfun(xq,yq);\n\n%% construct the projection matrix for cfun to degree M\nVMq = Vandermonde2D(M,rq,sq);\nCqM = VMq*VMq'*diag(wq)*Cq;\n\n%% initial condition\nx0 = 0; y0 = .1;\np = exp(-25*((x-x0).^2 + (y-y0).^2));\nu = zeros(Np, K);\nv=zeros(Np,K);\n\np_M = p;\nu_M = u;\nv_M = v;\n\ntime = 0;\n\n%% Runge-Kutta residual storage\nresu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K);\nresu_M = resu; resv_M = resv; resp_M = resp;\n\n%% compute time step size\nCN = (N+1)*(N+2)/2; % trace inequality constant\nCNh = max(CN*max(Fscale(:)));\ndt = 2/CNh;\n\n%% outer time step loop\ntstep = 0;\n\nwhile (timeFinalTime), dt = FinalTime-time; end\n \n for INTRK = 1:5\n \n timelocal = time + rk4c(INTRK)*dt;\n \n [rhsp, rhsu, rhsv] = acousticsRHS2D_fullWADG(p,u,v);\n [rhsp_M, rhsu_M, rhsv_M] = acousticsRHS2D_adaptiveWADG(p_M,u_M,v_M);\n \n % initiate and increment Runge-Kutta residuals\n resp = rk4a(INTRK)*resp + dt*rhsp;\n resu = rk4a(INTRK)*resu + dt*rhsu;\n resv = rk4a(INTRK)*resv + dt*rhsv;\n \n resp_M = rk4a(INTRK)*resp_M + dt*rhsp_M;\n resu_M = rk4a(INTRK)*resu_M + dt*rhsu_M;\n resv_M = rk4a(INTRK)*resv_M + dt*rhsv_M;\n \n % update fields\n u = u+rk4b(INTRK)*resu;\n v = v+rk4b(INTRK)*resv;\n p = p+rk4b(INTRK)*resp;\n \n u_M = u_M + rk4b(INTRK)*resu_M;\n v_M = v_M + rk4b(INTRK)*resv_M;\n p_M = p_M + rk4b(INTRK)*resp_M;\n end\n \n % Increment time\n time = time+dt; tstep = tstep+1;\nend\n\np_quadrature = Vq * p;\np_M_quadrature = Vq * p_M;\n\n[d1,d2]=size(p_quadrature);\nerror_accumulation = 0;\nfor j1=1:d2\n for j2=1:d1\n err = p_quadrature(j2,j1)-p_M_quadrature(j2,j1);\n error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1);\n end\nend\n\nerror_l2(i) = sqrt(error_accumulation);\nerror_fro(i) = norm(p-p_M,'fro'); \nend\n\nfunction [rhsp, rhsu, rhsv] = acousticsRHS2D_adaptiveWADG(p,u,v)\n\nGlobals2D;\n\n% Define field differences at faces\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM);\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM);\ndv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM);\n\n% evaluate upwind fluxes\nndotdU = nx.*du + ny.*dv;\n\n% Impose reflective boundary conditions (p+ = -p-)\nndotdU(mapB) = 0;\ndp(mapB) = -2*p(vmapB);\n\ntau = 1;\nfluxp = tau*dp - ndotdU;\nfluxu = (tau*ndotdU - dp).*nx;\nfluxv = (tau*ndotdU - dp).*ny;\n\npr = Dr*p; ps = Ds*p;\ndpdx = rx.*pr + sx.*ps;\ndpdy = ry.*pr + sy.*ps;\ndivU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy);\n\n% compute right hand sides of the PDE's\nrhsp = -divU + LIFT*(Fscale.*fluxp)/2.0;\nrhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0;\nrhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0;\n\nrhsp = Pq*(CqM.*(Vq*rhsp));\nreturn;\nend\n\nfunction [rhsp, rhsu, rhsv] = acousticsRHS2D_fullWADG(p,u,v)\n\nGlobals2D;\n\n% Define field differences at faces\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM);\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM);\ndv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM);\n\n% evaluate upwind fluxes\nndotdU = nx.*du + ny.*dv;\n\n% Impose reflective boundary conditions (p+ = -p-)\nndotdU(mapB) = 0;\ndp(mapB) = -2*p(vmapB);\n\ntau = 1;\nfluxp = tau*dp - ndotdU;\nfluxu = (tau*ndotdU - dp).*nx;\nfluxv = (tau*ndotdU - dp).*ny;\n\npr = Dr*p; ps = Ds*p;\ndpdx = rx.*pr + sx.*ps;\ndpdy = ry.*pr + sy.*ps;\ndivU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy);\n\n% compute right hand sides of the PDE's\nrhsp = -divU + LIFT*(Fscale.*fluxp)/2.0;\nrhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0;\nrhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0;\n\nrhsp = Pq*(Cq.*(Vq*rhsp));\nreturn;\nend\n\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "Wave2D_k_manufactured.m", "ext": ".m", "path": "WADG_Matlab-master/Wave2D_k_manufactured.m", "size": 3325, "source_encoding": "utf_8", "md5": "0034b8526d028e8da590042ba197b35b", "text": "clear\nGlobals2D\n\nk=[1 4 8 16]\nN = 4;\nM = 1\n\nfor i = 1:length(k)\n\nK1D = 32;\nFinalTime = 1.0;\n[Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D);\nStartUp2D;\n\n%% Set up wavespeed function\n%cfun = @(x,y) ones(size(x));\ncfun = @(x,y) 1+ 0.5*sin(pi*x).*sin(pi*y); % smooth velocity\n%cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity\n\n%% Set periodic manufactured solution\npfun = @(x,y,t) sin(k(i)*pi*x).*sin(k(i)*pi*y).*cos(k(i)*pi*t);\nufun = @(x,y,t) -cos(k(i)*pi*x).*sin(k(i)*pi*y).*sin(k(i)*pi*t);\nvfun = @(x,y,t) -sin(k(i)*pi*x).*cos(k(i)*pi*y).*sin(k(i)*pi*t);\nffun = @(x,y,t) k(i)*pi*(-1./(cfun(x,y))+2).*sin(k(i)*pi*x).*sin(k(i)*pi*y).*sin(k(i)*pi*t);\n\n%% generate quadrature points\nNq = 2*N+1;\n[rq sq wq] = Cubature2D(Nq); % integrate u*v*c\nVq = Vandermonde2D(N,rq,sq)/V;\nxq = Vq*x; yq = Vq*y;\n\n%% construct the projection matrix for nodal basis Pq\nPq = V*V'*Vq'*diag(wq);\n\n%% construct matrix Cq\nCq = cfun(xq,yq);\n\n%% construct the projection matrix for cfun to degree M\nVMq = Vandermonde2D(M,rq,sq);\nCqM = VMq*VMq'*diag(wq)*Cq;\n\n%% initial condition\np = pfun(x,y,0);\nu = ufun(x,y,0);\nv = vfun(x,y,0);\n\ntime = 0;\n\n%% Runge-Kutta residual storage\nresu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K);\n\n%% compute time step size\nCN = (N+1)*(N+2)/2; % trace inequality constant\nCNh = max(CN*max(Fscale(:)));\ndt = 2/CNh;\n\n%% outer time step loop\ntstep = 0;\n\n\nwhile (timeFinalTime), dt = FinalTime-time; end\n \n for INTRK = 1:5\n \n timelocal = time + rk4c(INTRK)*dt;\n \n f=ffun(x,y,timelocal);\n \n [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f);\n \n % initiate and increment Runge-Kutta residuals\n resp = rk4a(INTRK)*resp + dt*rhsp;\n resu = rk4a(INTRK)*resu + dt*rhsu;\n resv = rk4a(INTRK)*resv + dt*rhsv;\n \n % update fields\n u = u+rk4b(INTRK)*resu;\n v = v+rk4b(INTRK)*resv;\n p = p+rk4b(INTRK)*resp;\n \n end\n \n % Increment time\n time = time+dt; tstep = tstep+1;\nend\n\np_exact = pfun(x,y,FinalTime);\np_exact_quadrature = pfun(xq,yq,FinalTime);\n\np_quadrature = Vq * p;\n\n[d1,d2]=size(p_quadrature);\nerror_accumulation = 0;\nfor j1=1:d2\n for j2=1:d1\n err = p_quadrature(j2,j1)-p_exact_quadrature(j2,j1);\n error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1);\n end\nend\n\nerror_l2(i) = sqrt(error_accumulation);\nerror_fro(i) = norm(p-p_exact,'fro'); \nend\n\n\n\nfunction [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f)\n\nGlobals2D;\n\n% Define field differences at faces\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM);\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM);\ndv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM);\n\n% evaluate upwind fluxes\nndotdU = nx.*du + ny.*dv;\n\n% Impose reflective boundary conditions (p+ = -p-)\nndotdU(mapB) = 0;\ndp(mapB) = -2*p(vmapB);\n\ntau = 1;\nfluxp = tau*dp - ndotdU;\nfluxu = (tau*ndotdU - dp).*nx;\nfluxv = (tau*ndotdU - dp).*ny;\n\npr = Dr*p; ps = Ds*p;\ndpdx = rx.*pr + sx.*ps;\ndpdy = ry.*pr + sy.*ps;\ndivU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy);\n\n% compute right hand sides of the PDE's\nrhsp = -divU + f + LIFT*(Fscale.*fluxp)/2.0;\nrhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0;\nrhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0;\n\nrhsp = Pq*(CqM.*(Vq*rhsp));\nreturn;\nend\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "Wave2D_mesh_manufactured.m", "ext": ".m", "path": "WADG_Matlab-master/Wave2D_mesh_manufactured.m", "size": 3326, "source_encoding": "utf_8", "md5": "322817f72f150c1acafea4eaefbd319b", "text": "clear\nGlobals2D\n\nkd=[64]\nh=2./kd\nN = 4;\nM = 1;\nk = 16\nfor i = 1:length(kd)\n\nK1D = kd(i);\nFinalTime = 1.5;\n[Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D);\nStartUp2D;\n\n%% Set up wavespeed function\n%cfun = @(x,y) ones(size(x));\ncfun = @(x,y) 1+ 0.5*sin(pi*x).*sin(pi*y); % smooth velocity\n%cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity\n\n%% Set periodic manufactured solution\npfun = @(x,y,t) sin(k*pi*x).*sin(k*pi*y).*cos(k*pi*t);\nufun = @(x,y,t) -cos(k*pi*x).*sin(k*pi*y).*sin(k*pi*t);\nvfun = @(x,y,t) -sin(k*pi*x).*cos(k*pi*y).*sin(k*pi*t);\nffun = @(x,y,t) k*pi*(-1./(cfun(x,y))+2).*sin(k*pi*x).*sin(k*pi*y).*sin(k*pi*t);\n\n%% generate quadrature points\nNq = 2*N+1;\n[rq sq wq] = Cubature2D(Nq); % integrate u*v*c\nVq = Vandermonde2D(N,rq,sq)/V;\nxq = Vq*x; yq = Vq*y;\n\n%% construct the projection matrix for nodal basis Pq\nPq = V*V'*Vq'*diag(wq);\n\n%% construct matrix Cq\nCq = cfun(xq,yq);\n\n%% construct the projection matrix for cfun to degree M\nVMq = Vandermonde2D(M,rq,sq);\nCqM = VMq*VMq'*diag(wq)*Cq;\n\n%% initial condition\np = pfun(x,y,0);\nu = ufun(x,y,0);\nv = vfun(x,y,0);\n\ntime = 0;\n\n%% Runge-Kutta residual storage\nresu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K);\n\n%% compute time step size\nCN = (N+1)*(N+2)/2; % trace inequality constant\nCNh = max(CN*max(Fscale(:)));\ndt = 2/CNh;\n\n%% outer time step loop\ntstep = 0;\n\nwhile (timeFinalTime), dt = FinalTime-time; end\n \n for INTRK = 1:5\n \n timelocal = time + rk4c(INTRK)*dt;\n \n f=ffun(x,y,timelocal);\n \n [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f);\n \n % initiate and increment Runge-Kutta residuals\n resp = rk4a(INTRK)*resp + dt*rhsp;\n resu = rk4a(INTRK)*resu + dt*rhsu;\n resv = rk4a(INTRK)*resv + dt*rhsv;\n \n % update fields\n u = u+rk4b(INTRK)*resu;\n v = v+rk4b(INTRK)*resv;\n p = p+rk4b(INTRK)*resp;\n \n \n \n \n end\n \n % Increment time\n time = time+dt; tstep = tstep+1;\nend\n\np_exact = pfun(x,y,FinalTime);\np_exact_quadrature = pfun(xq,yq,FinalTime);\n\np_quadrature = Vq * p;\n\n[d1,d2]=size(p_quadrature);\nerror_accumulation = 0;\nfor j1=1:d2\n for j2=1:d1\n err = p_quadrature(j2,j1)-p_exact_quadrature(j2,j1);\n error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1);\n end\nend\n\nerror_l2(i) = sqrt(error_accumulation);\nerror_fro(i) = norm(p-p_exact,'fro'); \nend\n\n\n\nfunction [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f)\n\nGlobals2D;\n\n% Define field differences at faces\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM);\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM);\ndv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM);\n\n% evaluate upwind fluxes\nndotdU = nx.*du + ny.*dv;\n\n% Impose reflective boundary conditions (p+ = -p-)\nndotdU(mapB) = 0;\ndp(mapB) = -2*p(vmapB);\n\ntau = 1;\nfluxp = tau*dp - ndotdU;\nfluxu = (tau*ndotdU - dp).*nx;\nfluxv = (tau*ndotdU - dp).*ny;\n\npr = Dr*p; ps = Ds*p;\ndpdx = rx.*pr + sx.*ps;\ndpdy = ry.*pr + sy.*ps;\ndivU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy);\n\n% compute right hand sides of the PDE's\nrhsp = -divU + f + LIFT*(Fscale.*fluxp)/2.0;\nrhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0;\nrhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0;\n\nrhsp = Pq*(CqM.*(Vq*rhsp));\nreturn;\nend\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "bern_tri.m", "ext": ".m", "path": "WADG_Matlab-master/bern_tri.m", "size": 1444, "source_encoding": "utf_8", "md5": "3a04a72548c550e48525a3a60987827c", "text": "% function [V Vr Vs V1 V2 V3 id] = bern_tri(N,r,s)\n% \n% % use equivalence between W&B and equispaced nodes - get ordering\n% [re se] = EquiNodes2D(N); [re se] = xytors(re,se);\n% Ve = bern_tri_b(N,re,se);\n% for i = 1:size(Ve,2)\n% [val iid] = max(Ve(:,i)); \n% id(i) = iid;\n% % id(i) = i;\n% end\n% \n% [V Vr Vs V1 V2 V3] = bern_tri_b(N,r,s);\n% V = V(:,id);\n% Vr = Vr(:,id); Vs = Vs(:,id);\n% V1 = V1(:,id); V2 = V2(:,id); V3 = V3(:,id);\n\nfunction [V Vr Vs VL1 VL2 VL3] = bern_tri(N,r,s)\n\n% barycentric version\nL1 = -(r+s)/2; L2 = (1+r)/2; L3 = (1+s)/2;\ndL1r = -.5; dL2r = .5; dL3r = 0;\ndL1s = -.5; dL2s = 0; dL3s = .5;\n\nsk = 1;\n% for i = 0:N\n% for j = 0:N-i\n% k = N-i-j;\nfor k = 0:N\n for j = 0:N-k\n i = N-j-k;\n C=factorial(N)/(factorial(i)*factorial(j)*factorial(k));\n V(:,sk) = C*(L1.^i).*(L2.^j).*(L3.^k);\n \n dL1 = C*i*(L1.^(i-1)).*(L2.^j).*(L3.^k);\n dL2 = C*j*(L1.^(i)).*(L2.^(j-1)).*(L3.^k);\n dL3 = C*k*(L1.^(i)).*(L2.^j).*(L3.^(k-1));\n if i==0\n dL1 = zeros(size(dL1));\n end\n if j==0\n dL2 = zeros(size(dL2));\n end\n if k == 0\n dL3 = zeros(size(dL3));\n end\n Vr(:,sk) = dL1.*dL1r + dL2.*dL2r + dL3.*dL3r; \n Vs(:,sk) = dL1.*dL1s + dL2.*dL2s + dL3.*dL3s;\n \n VL1(:,sk) = dL1;\n VL2(:,sk) = dL2;\n VL3(:,sk) = dL3;\n sk = sk + 1;\n end\nend\n\nreturn\n\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "Wave2D_modified.m", "ext": ".m", "path": "WADG_Matlab-master/Wave2D_modified.m", "size": 2725, "source_encoding": "utf_8", "md5": "16165584c54009cc2f3f03cf162a8f73", "text": "Globals2D\n\nN = 4;\nK1D = 16;\nc_flag = 0;\nFinalTime = 0.5;\n%cfun = @(x,y) ones(size(x));\ncfun = @(x,y) 1 + sin(pi*x).*sin(pi*y); % smooth velocity\n%cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity\n\n[Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D);\nStartUp2D;\n\n [rp sp] = EquiNodes2D(50); [rp sp] = xytors(rp,sp);\nVp = Vandermonde2D(N,rp,sp)/V;\nxp = Vp*x; yp = Vp*y;\n\nNq = 2*N+1;\n[rq sq wq] = Cubature2D(Nq); % integrate u*v*c\nVq = Vandermonde2D(N,rq,sq)/V; \nxq = Vq*x; yq = Vq*y;\n\n\n\n\n%construct Pq\nPq=V*V'*Vq'*diag(wq);\n\n%Pq is the projection matrix for Nodal Basis\n\n%construct the matrix C\nCq=cfun(xq,yq);\n\n\n\n\n%% initial condition\n\nx0 = 0; y0 = .1;\np = exp(-25*((x-x0).^2 + (y-y0).^2));\nu = zeros(Np, K);\nv=zeros(Np,K);\n%%\n\ntime = 0;\n\n% Runge-Kutta residual storage\nresu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K);\n\n% compute time step size\nCN = (N+1)*(N+2)/2; % trace inequality constant\nCNh = max(CN*max(Fscale(:)));\ndt = 2/CNh;\n\n% outer time step loop\ntstep = 0;\n\nwhile (timeFinalTime), dt = FinalTime-time; end\n \n for INTRK = 1:5\n \n timelocal = time + rk4c(INTRK)*dt;\n \n [rhsp, rhsu, rhsv] = acousticsRHS2D_WADG(p,u,v);\n \n % initiate and increment Runge-Kutta residuals\n %apply invM*M_c^2\n resp = rk4a(INTRK)*resp + dt*rhsp;\n resu = rk4a(INTRK)*resu + dt*rhsu;\n resv = rk4a(INTRK)*resv + dt*rhsv;\n \n % update fields\n u = u+rk4b(INTRK)*resu;\n v = v+rk4b(INTRK)*resv;\n p = p+rk4b(INTRK)*resp;\n \n end;\n \n if 1 && nargin==0 && mod(tstep,10)==0\n clf\n vv = Vp*p;\n plot3(xp,yp,vv,'.');\n axis equal\n axis tight\n colorbar\n title(sprintf('time = %f',time))\n drawnow\n end\n \n % Increment time\n time = time+dt; tstep = tstep+1;\nend\n\nfunction [rhsp, rhsu, rhsv] = acousticsRHS2D_WADG(p,u,v)\n\nGlobals2D;\n\n% Define field differences at faces\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM);\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM);\ndv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM);\n\n% evaluate upwind fluxes\nndotdU = nx.*du + ny.*dv;\n\n% Impose reflective boundary conditions (p+ = -p-)\nndotdU(mapB) = 0;\ndp(mapB) = -2*p(vmapB);\n\ntau = 1;\nfluxp = tau*dp - ndotdU;\nfluxu = (tau*ndotdU - dp).*nx;\nfluxv = (tau*ndotdU - dp).*ny;\n\npr = Dr*p; ps = Ds*p;\ndpdx = rx.*pr + sx.*ps;\ndpdy = ry.*pr + sy.*ps;\ndivU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy);\n\n% compute right hand sides of the PDE's\nrhsp = -divU + LIFT*(Fscale.*fluxp)/2.0;\nrhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0;\nrhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0;\n\nrhsp = Pq*(Cq.*(Vq*rhsp));\nreturn;\nend\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "Wave2D_simple.m", "ext": ".m", "path": "WADG_Matlab-master/Wave2D_simple.m", "size": 2633, "source_encoding": "utf_8", "md5": "977017e5edb69468778850473fbb3602", "text": "function Wave2D\n\n\nGlobals2D\n\nN = 4;\nK1D = 16;\nc_flag = 0;\nFinalTime = 3;\n%cfun = @(x,y) ones(size(x));\n cfun = @(x,y) .5*sin(pi*x).*sin(pi*y); % smooth velocity\n %cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity\n\n[Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D);\nStartUp2D;\n\n% plotting nodes\n[rp sp] = EquiNodes2D(50); [rp sp] = xytors(rp,sp);\nVp = Vandermonde2D(N,rp,sp)/V;\nxp = Vp*x; yp = Vp*y;\n\nNq = 2*N+1;\n[rq sq wq] = Cubature2D(Nq); % integrate u*v*c\nVq = Vandermonde2D(N,rq,sq)/V;\nxq = Vq*x; yq = Vq*y;\n\n%% initial condition\n\nx0 = 0; y0 = .1;\np = exp(-25*((x-x0).^2 + (y-y0).^2));\nu = zeros(Np, K);\nv= zeros(Np,K);\nvv = Vp*p;\ncolor_line3(xp,yp,vv,vv)\n%%\n\ntime = 0;\n\n% Runge-Kutta residual storage\nresu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K);\n\n% compute time step size\nCN = (N+1)*(N+2)/2; % trace inequality constant\nCNh = max(CN*max(Fscale(:)));\ndt = 2/CNh;\n\n% outer time step loop\ntstep = 0;\nfigure\n\n\nwhile (timeFinalTime), dt = FinalTime-time; end\n \n for INTRK = 1:5\n \n timelocal = time + rk4c(INTRK)*dt;\n \n [rhsp, rhsu, rhsv] = acousticsRHS2D(p,u,v,timelocal);\n \n % initiate and increment Runge-Kutta residuals\n resp = rk4a(INTRK)*resp + dt*rhsp;\n resu = rk4a(INTRK)*resu + dt*rhsu;\n resv = rk4a(INTRK)*resv + dt*rhsv;\n \n % update fields\n u = u+rk4b(INTRK)*resu;\n v = v+rk4b(INTRK)*resv;\n p = p+rk4b(INTRK)*resp;\n \n end;\n \n if 1 && nargin==0 && mod(tstep,10)==0\n clf\n vv = Vp*p;\n color_line3(xp,yp,vv,vv,'.');\n axis equal\n axis tight\n colorbar\n title(sprintf('time = %f',time))\n drawnow\n end\n \n % Increment time\n time = time+dt; tstep = tstep+1;\nend\n\n\n\nfunction [rhsp, rhsu, rhsv] = acousticsRHS2D(p,u,v,time)\n\nGlobals2D;\n\n% Define field differences at faces\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM);\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM);\ndv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM);\n\n% evaluate upwind fluxes\nndotdU = nx.*du + ny.*dv;\n\n% Impose reflective boundary conditions (p+ = -p-)\nndotdU(mapB) = 0;\ndp(mapB) = -2*p(vmapB);\n\ntau = 1;\nfluxp = tau*dp - ndotdU;\nfluxu = (tau*ndotdU - dp).*nx;\nfluxv = (tau*ndotdU - dp).*ny;\n\npr = Dr*p; ps = Ds*p;\ndpdx = rx.*pr + sx.*ps;\ndpdy = ry.*pr + sy.*ps;\ndivU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy);\n\n% compute right hand sides of the PDE's\nrhsp = -divU + LIFT*(Fscale.*fluxp)/2.0;\nrhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0;\nrhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0;\n\nreturn;\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "bern_pyr.m", "ext": ".m", "path": "WADG_Matlab-master/bern_pyr.m", "size": 1162, "source_encoding": "utf_8", "md5": "e05be17e730cbb437109d06c7b108ec5", "text": "function [V Vr Vs Vt Va Vb Vc] = bern_pyr(N,r,s,t)\n\na = 2*(r+1)./(1-t)-1;\nb = 2*(s+1)./(1-t)-1;\nc = t;\nids = abs(t-1)<1e-8;\na(ids) = -1;\nb(ids) = -1;\n\ndadr = 2./(1-t); \ndbds = 2./(1-t);\ndadt = (1+a)./(1-t);\ndbdt = (1+b)./(1-t);\n\nsk = 1;\nfor k = 0:N\n for i = 0:N-k \n for j = 0:N-k \n V(:,sk) = bern(N-k,i,a).*bern(N-k,j,b).*bern(N,k,c);\n va = .5*d_bern(N-k,i,a).*bern(N-k,j,b).*bern(N,k,c);\n vb = .5*bern(N-k,i,a).*d_bern(N-k,j,b).*bern(N,k,c);\n vc = .5*bern(N-k,i,a).*bern(N-k,j,b).*d_bern(N,k,c);\n Vr(:,sk) = va.*dadr;\n Vs(:,sk) = vb.*dbds;\n Vt(:,sk) = va.*dadt + vb.*dbdt + vc;\n \n % for testing\n Va(:,sk) = va; Vb(:,sk) = vb; Vc(:,sk) = vc; \n \n sk = sk + 1; \n end\n end\nend\n\nfunction [bi] = bern(N,i,r)\n\nr = (1+r)/2;\nbi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i);\n% bi = (r.^i).*(1-r).^(N-i);\n\nfunction dbi = d_bern(N,i,r)\n\nif (i==0)\n dbi = -N*(1-r).^(N-1);\nelseif (i==N)\n dbi = N*(r.^(N-1));\nelse\n dbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r);\nend"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "bern_basis_tri.m", "ext": ".m", "path": "WADG_Matlab-master/bern_basis_tri.m", "size": 2146, "source_encoding": "utf_8", "md5": "b5c5ae2fee4e7f3bac98387d91b0b6d1", "text": "function [V Vr Vs V1 V2 V3 id] = bern_basis_tri(N,r,s)\n\n\n[V Vr Vs V1 V2 V3] = bern_tri(N,r,s);\n\nreturn\n% \n% % use equivalence between W&B and equispaced nodes - get ordering\n% [re se] = EquiNodes2D(N); [re se] = xytors(re,se);\n% Ve = bern_tri(N,re,se);\n% for i = 1:size(Ve,2)\n% [val iid] = max(Ve(:,i)); \n% id(i) = iid;\n% % id(i) = i;\n% end\n% \n% [V Vr Vs V1 V2 V3] = bern_tri(N,r,s);\n% V = V(:,id);\n% Vr = Vr(:,id);\n% Vs = Vs(:,id);\n% V1 = V1(:,id);\n% V2 = V2(:,id);\n% V3 = V3(:,id);\n\nfunction [V Vr Vs VL1 VL2 VL3] = bern_tri(N,r,s)\n\n% barycentric version\nL1 = -(r+s)/2; L2 = (1+r)/2; L3 = (1+s)/2;\ndL1r = -.5; dL2r = .5; dL3r = 0;\ndL1s = -.5; dL2s = 0; dL3s = .5;\n\nsk = 1;\nfor k = 0:N\n for j = 0:N-k\n i = N-j-k;\n C=factorial(N)/(factorial(i)*factorial(j)*factorial(k));\n V(:,sk) = C*(L1.^i).*(L2.^j).*(L3.^k);\n \n dL1 = C*i*(L1.^(i-1)).*(L2.^j).*(L3.^k);\n dL2 = C*j*(L1.^(i)).*(L2.^(j-1)).*(L3.^k);\n dL3 = C*k*(L1.^(i)).*(L2.^j).*(L3.^(k-1));\n if i==0\n dL1 = zeros(size(dL1));\n end\n if j==0\n dL2 = zeros(size(dL2));\n end\n if k == 0\n dL3 = zeros(size(dL3));\n end\n Vr(:,sk) = dL1.*dL1r + dL2.*dL2r + dL3.*dL3r; \n Vs(:,sk) = dL1.*dL1s + dL2.*dL2s + dL3.*dL3s;\n \n VL1(:,sk) = dL1;\n VL2(:,sk) = dL2;\n VL3(:,sk) = dL3;\n sk = sk + 1;\n end\nend\n\nreturn\n\n\n\n% [a b] = rstoab(r,s);\n% a = .5*(a+1); % convert to unit\n% b = .5*(b+1); % convert to unit\n\n% be careful about derivatives at s = 1\na = .5*(r+1)./(1-.5*(s+1));\nb = .5*(s+1);\na(abs(1-s)<1e-8) = 0;\n\ndadr = 1./(1 - s);\ndads = (r+1)./((1-s).^2);\ndbds = .5;\n\nsk = 1;\nfor i = 0:N\n for j = 0:N-i\n k = N-i-j;\n V(:,sk) = bern(N-k,i,a).*bern(N,k,b);\n Vr(:,sk) = d_bern(N-k,i,a).*bern(N,k,b).*dadr;\n Vs(:,sk) = d_bern(N-k,i,a).*bern(N,k,b).*dads + bern(N-k,i,a).*d_bern(N,k,b)*dbds;\n sk = sk + 1;\n end\nend\n\nfunction bi = bern(N,i,r)\n\nbi = nchoosek(N,i)*(r.^i).*(1-r).^(N-i);\n\nfunction dbi = d_bern(N,i,r)\n\ndbi = nchoosek(N,i)*r.^(i - 1).*(1 - r).^(N - i - 1).*(i - N*r);\n\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "Sample2D.m", "ext": ".m", "path": "WADG_Matlab-master/Sample2D.m", "size": 717, "source_encoding": "utf_8", "md5": "be53a9f67b172f80cb774efda6b67d4b", "text": "\r\nfunction [sampleweights,sampletri] = Sample2D(xout, yout)\r\n \r\n% function [sampleweights,sampletri] = Sample2D(xout, yout)\r\n% purpose: input = coordinates of output data point\r\n% output = number of containing tri and interpolation weights\r\n% [ only works for straight sided triangles ]\r\n\r\nGlobals2D;\r\n\r\n% find containing tri\r\n[sampletri,tribary] = ...\r\n tsearchn([VX', VY'], EToV, [xout,yout]);\r\n\r\n% Matlab barycentric coordinates -> biunit triangle coordinates\r\nsout = 2*tribary(:,3)-1; rout = 2*tribary(:,2)-1;\r\n\r\n% build generalized Vandermonde for the sample point\r\nVout = Vandermonde2D(N, rout, sout);\r\n \r\n% build interpolation matrix for the sample point\r\nsampleweights = Vout*invV;\r\nreturn;\r\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "tet_cubature.m", "ext": ".m", "path": "WADG_Matlab-master/tet_cubature.m", "size": 103616, "source_encoding": "utf_8", "md5": "8f12d404868158cf03a4dc3cae2976bb", "text": "function [r s t w] = tet_cubature(N)\n\n% CubatureData3D_GX.cpp\n% database of precalculated cubature data\n% 2012/05/02\n%---------------------------------------------------------\n%\n% N [1 1 1] [2 2] [3 3] [4\n% cubN 1 2 3 4 5 6 7 8\n% Ncub 1 4 6 11 14 23 31 44\n%---------------------------------------------------------\n%\n% N 4 [5 5] [6 6] [7 7]\n% cubN 9 10 11 12 13 14 15\n% Ncub 57 74 95 122 146 177 214\n%---------------------------------------------------------\n\n\n%----------------------\n% N cubN Ncub\n%----------------------\n% 1 ( 2, 3) [ 4, 6]\n% 2 ( 4, 5) [ 11, 14]\n% 3 ( 6, 7) [ 23, 31]\n% 4 ( 8, 9) [ 44, 57]\n% 5 (10,11) [ 74, 95]\n% 6 (12,13) [122,146]\n% 7 (14,15) [177,214]\n% 8 ( 15) [ 214]\n%----------------------\n\n\n\n% NodeSet 1 1\nTN2012_1 = [ % 1*4\n 0.000000000000000E+00, 0.000000000000000E+00, 0.000000000000000E+00, 0.942809041582063E+00 ];\n\n% NodeSet 2 4\nTN2012_2 = [ % 4*4\n -.267702858591007E+00, 0.593901700619949E-01, -.396942694114215E+00, 0.283333858791636E+00,\n 0.151093184153314E+00, 0.435408773247631E+00, 0.215171925430692E+00, 0.262834019890433E+00,\n -.136769919523739E+00, -.328034111559041E+00, 0.295084651993713E+00, 0.300844647504794E+00,\n 0.806744930905196E+00, -.340097731428529E+00, -.343037895100255E+00, 0.957965153951996E-01 ];\n\n% NodeSet 3 6\nTN2012_3 = [ % 6*4\n -.168503718027600E+00, 0.191091491627171E+00, -.389626731458516E+00, 0.124986334616479E+00,\n 0.278379942753442E-01, -.230493283883966E-01, 0.548135066324183E+00, 0.211580648438021E+00,\n -.351221617734345E+00, 0.183514402633999E+00, 0.514781533034353E-01, 0.120742171826672E+00,\n 0.430853246354904E+00, -.247471582318045E+00, -.168331564100703E+00, 0.237591631621872E+00,\n -.467676374796738E+00, -.423525082726438E+00, -.158697307788931E+00, 0.132581964894968E+00,\n 0.149283125384843E+00, 0.639784768516452E+00, -.108021925305539E+00, 0.115326290184051E+00 ];\n\n% NodeSet 4 11\nTN2012_4 = [ % 11*4\n -.145961228097999E-01, 0.242656457919971E-02, 0.709356578010363E+00, 0.100379025241264E+00,\n -.293724489630999E+00, 0.176439650676461E+00, 0.110886049494113E+00, 0.103929831025446E+00,\n 0.323087833715827E+00, -.193207041095656E+00, 0.169542639670465E+00, 0.146112883409388E+00,\n -.881965417939658E-01, 0.231788427010598E-01, -.201181939132559E+00, 0.182349462340124E+00,\n 0.127020366331471E+00, 0.545141067721522E+00, 0.130950399075932E+00, 0.718068965649525E-01,\n -.441430768809118E+00, -.384822563159018E+00, 0.922542967916253E-01, 0.748841921109801E-01,\n 0.393941858963343E+00, 0.206874467063953E+00, -.311156042619824E+00, 0.654969120044006E-01,\n -.603446971461421E-01, -.457373907492708E+00, -.330221532932238E+00, 0.565055488469881E-01,\n -.891405983460118E-01, 0.726809265959946E+00, -.350793173736374E+00, 0.522257744237005E-01,\n 0.654521303360376E+00, -.397035624387057E+00, -.297042483395114E+00, 0.521122321989204E-01,\n -.730764225967786E+00, -.266942008864898E+00, -.386103757024185E+00, 0.370062834158988E-01 ];\n\n% NodeSet 5 14\nTN2012_5 = [ % 14*4\n 0.166418072157768E-15, 0.109436232414623E-15, 0.770436782529672E+00, 0.692899055434865E-01,\n 0.408992591748701E+00, -.236131982942675E+00, 0.333941052787584E+00, 0.401127730719707E-01,\n 0.633846727543000E-16, 0.472263965885350E+00, 0.333941052787583E+00, 0.401127730719707E-01,\n -.408992591748701E+00, -.236131982942675E+00, 0.333941052787583E+00, 0.401127730719708E-01,\n 0.372390093103578E-16, 0.354800148930181E-16, -.298278869430759E+00, 0.106243195244073E+00,\n -.243543677053202E+00, 0.140610007506098E+00, 0.994262898102530E-01, 0.106243195244073E+00,\n 0.771865760070526E-17, -.281220015012195E+00, 0.994262898102531E-01, 0.106243195244073E+00,\n 0.243543677053203E+00, 0.140610007506098E+00, 0.994262898102530E-01, 0.106243195244073E+00,\n 0.629058998756435E+00, -.363187382268184E+00, -.256812260843224E+00, 0.692899055434864E-01,\n -.629058998756435E+00, -.363187382268184E+00, -.256812260843224E+00, 0.692899055434865E-01,\n -.140776895379933E-15, 0.726374764536368E+00, -.256812260843224E+00, 0.692899055434864E-01,\n 0.408992591748701E+00, 0.236131982942675E+00, -.333941052787584E+00, 0.401127730719707E-01,\n -.104796521146490E-15, -.472263965885350E+00, -.333941052787583E+00, 0.401127730719707E-01,\n -.408992591748701E+00, 0.236131982942675E+00, -.333941052787584E+00, 0.401127730719707E-01 ];\n\n% NodeSet 6 23\nTN2012_6 = [ % 23*4\n 0.491994195152311E-02, -.139223850343092E-01, 0.106622826396772E+01, 0.668997954335606E-02,\n 0.341505806021954E-01, 0.254207383054340E+00, 0.631588696703923E+00, 0.297073565323308E-01,\n -.456119832861723E+00, -.311038544744538E+00, 0.230026765510699E+00, 0.228454763572233E-01,\n 0.214449922976949E+00, -.123490387324972E+00, 0.563235163630283E+00, 0.460940056044558E-01,\n -.154069305999594E+00, -.686521447230217E-01, 0.620626489628262E+00, 0.500002972857723E-01,\n 0.306452540322295E+00, 0.181849550192318E+00, 0.125468587644291E+00, 0.407663998761417E-01,\n -.130588295951477E-01, -.248889116907340E-01, -.335770592628266E+00, 0.632962545391904E-01,\n 0.153524468983807E-01, -.326114310053292E+00, 0.114778898592700E+00, 0.564001074548194E-01,\n -.156778448777534E+00, 0.252245430100092E+00, 0.214059780070552E+00, 0.590334934291369E-01,\n -.397361694050676E+00, -.197715908337850E+00, -.796336180288233E-01, 0.606546975975660E-01,\n 0.976488461664955E-02, 0.650418429113368E+00, 0.586844628157869E-02, 0.410974214177224E-01,\n -.522808798464745E+00, -.663505530412342E-01, 0.193427268845595E-02, 0.212751151391656E-01,\n 0.556560570221033E+00, -.318669005422011E+00, 0.137974025142484E-01, 0.439472843110177E-01,\n 0.842308197902346E-01, 0.213805982286452E-01, 0.319575612691255E-01, 0.106159736633763E+00,\n 0.217416609116024E+00, 0.459950700499800E+00, -.302723230375316E+00, 0.508504156781972E-01,\n 0.321215894522565E+00, -.426005242154505E+00, -.299485560260426E+00, 0.469223144374328E-01,\n -.259364807854540E+00, 0.385198021113758E+00, -.282519709925312E+00, 0.594595362053551E-01,\n 0.563645476720258E+00, -.111160622782170E+00, -.306814049530041E+00, 0.444515894220345E-01,\n -.641094964462573E+00, -.193431833850761E+00, -.366047360516159E+00, 0.240457075184084E-01,\n -.334415109058215E+00, -.449175869972365E+00, -.310242329274613E+00, 0.374428103418277E-01,\n -.189458838689202E-01, 0.901059945993096E+00, -.347395205043690E+00, 0.150146857671485E-01,\n -.821465589619935E+00, -.510986035935518E+00, -.263564524010136E+00, 0.982721516374585E-02,\n 0.859741547561566E+00, -.520808514122574E+00, -.360343258536933E+00, 0.682714132625144E-02 ];\n\n% NodeSet 7 31\nTN2012_7 = [ % 31*4\n -.308252291356292E+00, -.197843287967888E+00, 0.655377140534142E+00, 0.726734289368660E-02,\n 0.323006856476517E+00, -.116660814480029E+00, 0.596321726821282E+00, 0.113172838083258E-01,\n 0.179003094309949E-02, 0.276022304167135E-02, 0.919167034243546E+00, 0.218890177509953E-01,\n -.174985856285022E+00, 0.149255307127258E+00, 0.516292138739824E+00, 0.211296379289743E-01,\n 0.351581822451223E-01, 0.322257000983196E+00, 0.549210359947022E+00, 0.219589530907310E-01,\n -.114891280250506E+00, 0.359815024699799E-01, -.388691765396646E+00, 0.257668903243402E-01,\n 0.108024261958047E+00, -.212321108274526E+00, 0.513821465706857E+00, 0.271493965375484E-01,\n 0.996088601920952E-01, 0.337060034616579E+00, -.273250222640217E+00, 0.405324562077599E-01,\n 0.255258965717304E+00, 0.234593138765271E-01, -.128926642642749E+00, 0.497630316079319E-01,\n 0.301897209396454E+00, -.279744081272853E+00, -.336815502815560E+00, 0.394457458861626E-01,\n -.363799525166287E-01, 0.678415814779263E+00, 0.496515459049994E-01, 0.195275383339862E-01,\n -.197974843267435E+00, -.109926012070685E+00, 0.368810136731088E+00, 0.568528141204943E-01,\n 0.170554760858719E+00, 0.585448114971668E-01, 0.324539845033623E+00, 0.628959292907061E-01,\n 0.538271457535773E+00, -.332620243815606E+00, 0.653099846338948E-01, 0.296146949713317E-01,\n -.582625595155966E+00, -.286639428866960E+00, 0.405007368919429E-01, 0.266935521529227E-01,\n -.663882748425514E-01, 0.339664373274517E+00, 0.433913762115470E-01, 0.629225940565768E-01,\n 0.139486545048336E+00, -.307850231836867E+00, -.855418822812698E-02, 0.605178177170064E-01,\n -.252544821156148E+00, -.968770785232076E-01, -.121223434312817E+00, 0.776291699936313E-01,\n -.336417947935678E+00, -.422280930562356E+00, 0.224493699213366E-01, 0.196789751488124E-01,\n 0.508817409509134E+00, -.460796001465295E-01, -.538915514978018E-01, 0.231576809797211E-01,\n -.399767677129958E+00, 0.169411793400156E+00, -.133176911076194E-01, 0.210705295411276E-01,\n 0.223357920899763E+00, 0.507026392231846E+00, -.399617306009708E-01, 0.209118054635657E-01,\n -.288768983232798E+00, -.432041161224173E+00, -.330437075713885E+00, 0.348234147884134E-01,\n 0.243005680598846E+00, 0.526215548808249E+00, -.363369754803439E+00, 0.157467976153176E-01,\n -.240245918466879E+00, 0.491923965978304E+00, -.318467007553824E+00, 0.318630473755232E-01,\n -.573712249516894E+00, -.745318233435191E-01, -.334800074141430E+00, 0.264563326318226E-01,\n 0.553074058634518E+00, -.335502653046674E-02, -.350744403540142E+00, 0.198864503476964E-01,\n 0.763216087154036E+00, -.434539428837598E+00, -.312047989157562E+00, 0.194127668598410E-01,\n 0.110832352531628E-02, 0.883581509323175E+00, -.315533688400763E+00, 0.181045845852361E-01,\n -.766658972551922E+00, -.454032742499625E+00, -.314870223157801E+00, 0.170243759166119E-01,\n 0.331437926843703E+00, -.541903403372277E+00, -.310441026876215E+00, 0.117984136552630E-01 ];\n\n% NodeSet 8 44\nTN2012_8 = [ % 44*4\n -.161177255167053E-01, 0.799860011950070E-03, 0.114075012048065E+01, 0.164537481630632E-02,\n -.714882723684071E-02, 0.172391459500714E+00, 0.786069607279345E+00, 0.142022580708632E-01,\n 0.458992337208856E+00, -.174471635165123E+00, -.399143091233099E+00, 0.931166933355630E-02,\n -.452099049249418E+00, -.263294162907140E+00, 0.353609296024044E+00, 0.954963853667850E-02,\n 0.110956035643063E+00, -.629572037600564E-01, 0.818940414230147E+00, 0.166052583605351E-01,\n 0.182522429364889E+00, 0.167838281859336E+00, 0.476496271636175E+00, 0.147232729381889E-01,\n -.150748980541997E+00, -.782694187324931E-01, 0.762897429508123E+00, 0.169600880437266E-01,\n -.287732473487860E+00, -.123468697478364E+00, -.388005832381780E+00, 0.155840364711871E-01,\n 0.368074721237849E+00, -.216987676633974E+00, 0.399755369527441E+00, 0.212175082715303E-01,\n 0.478815642489051E+00, -.462943730059424E-01, 0.114465646499509E+00, 0.120673743703809E-01,\n -.347877936740082E+00, -.129563033616473E+00, 0.250917196877864E+00, 0.256962000267611E-01,\n -.354828586873474E-01, -.226810803130748E+00, 0.417461557834331E+00, 0.304461329840053E-01,\n 0.259165044293404E+00, 0.133007144302729E+00, -.274777834511803E+00, 0.265737195097187E-01,\n -.130503737894631E-02, 0.491940911589454E+00, 0.303192932475321E+00, 0.227767050847918E-01,\n -.349399607082860E-01, 0.300199516912219E+00, -.344250352423092E+00, 0.303973451645927E-01,\n -.166046285970730E+00, 0.140773645768751E+00, 0.397053743418083E+00, 0.344597559898010E-01,\n 0.101008552242243E+00, -.225925757531516E+00, -.307089325860143E+00, 0.391902057995841E-01,\n -.358746816360514E+00, -.108319979557346E+00, -.198990439690392E+00, 0.368286761285683E-01,\n -.347306756398568E+00, -.374230473903013E+00, 0.152625895856833E-01, 0.237013576444607E-01,\n -.863574112140118E-01, -.147806248208501E+00, -.154235018984395E-03, 0.498396471485484E-01,\n 0.290116820177849E+00, -.344951237372675E+00, 0.412102600131449E-01, 0.308555705439793E-01,\n 0.104209335515011E+00, 0.288367114168047E-01, 0.324891384827993E+00, 0.526016619480544E-01,\n -.641938745191836E-01, 0.255812557085304E+00, -.695790051538878E-01, 0.503024473506213E-01,\n -.201698697211897E+00, 0.440436807904118E+00, -.334098756487922E-01, 0.255666604695654E-01,\n 0.184617067735640E+00, 0.399856860528596E+00, -.130352743154576E-01, 0.378055160438833E-01,\n 0.378889395816016E+00, -.995658516281559E-01, -.839032251221259E-01, 0.488182976194162E-01,\n -.481871616316580E+00, -.150974738390975E-01, -.450140403133934E-01, 0.214429854534266E-01,\n 0.682171905077817E+00, -.395651861881759E+00, -.745152352274434E-01, 0.138780615762415E-01,\n 0.397864229301514E+00, 0.225661601324835E+00, -.399393902200914E+00, 0.650295778034312E-02,\n -.697588947015913E+00, -.389965102391845E+00, -.125421045820558E+00, 0.160043996273847E-01,\n 0.274296474933631E-02, 0.813499823087962E+00, -.141581579520532E+00, 0.163946974018378E-01,\n 0.164568786005099E-01, -.445103670029463E+00, -.185824429941080E+00, 0.212690542680105E-01,\n -.461834921478590E+00, -.453564747993794E+00, -.324551242480902E+00, 0.221549975797254E-01,\n 0.157509056839709E+00, 0.665014546017143E+00, -.331712100150823E+00, 0.189945011444925E-01,\n 0.539917520321524E+00, -.467462446997303E+00, -.316815950570112E+00, 0.193700460252858E-01,\n -.140390526208972E+00, 0.701265398375963E+00, -.337215023915009E+00, 0.168751540630192E-01,\n 0.445339657003786E-01, -.510724184730913E+00, -.395001367051171E+00, 0.709100855483249E-02,\n -.423436030210435E+00, 0.226332499768761E+00, -.333644400603587E+00, 0.206706155183819E-01,\n -.721417637689403E+00, -.272715517063635E+00, -.351939297000166E+00, 0.129502105610663E-01,\n 0.727811871619034E+00, -.286162780307073E+00, -.322616758291581E+00, 0.145083654707130E-01,\n 0.490189077970134E+00, 0.185630652333263E+00, -.278004232570757E+00, 0.111868259153756E-01,\n -.875888735250778E+00, -.556637467888742E+00, -.372057779910459E+00, 0.240124083764661E-02,\n 0.763237720561976E-02, 0.105605694666911E+01, -.397275100897422E+00, 0.196017972799913E-02,\n 0.931743114716919E+00, -.566424712470591E+00, -.382107361679063E+00, 0.142736140697601E-02 ];\n\n% NodeSet 9 57\nTN2012_9 = [ % 57*4\n 0.210805201710326E+00, -.895577604807597E-01, 0.773588207426104E+00, 0.551558344381980E-02,\n 0.128372935585005E-02, 0.612119775491147E-03, 0.102094083614009E+01, 0.668799331175713E-02,\n -.291873417501847E-01, 0.212275857965953E+00, 0.779935872338808E+00, 0.669939372222656E-02,\n -.435794929768927E+00, -.283935548031834E+00, 0.364437764378333E+00, 0.678802354666028E-02,\n -.179934163787020E+00, -.958255615202926E-01, 0.757204434805819E+00, 0.110898258011410E-01,\n 0.694222218620416E-01, -.139466668070751E+00, 0.705548760498302E+00, 0.118538505140399E-01,\n -.100564299113523E+00, 0.483639752826183E+00, -.407160361174579E+00, 0.742946816321177E-02,\n 0.190485569675336E+00, 0.324884395173882E+00, 0.278433783534254E+00, 0.926343928641625E-02,\n 0.323123885199655E+00, -.309109700213472E+00, 0.322000369135132E+00, 0.922010916817944E-02,\n 0.681998794334014E-01, -.179954101765636E+00, -.395513568317633E+00, 0.134505343605042E-01,\n 0.970813162355614E-01, 0.134669034127363E+00, 0.663220941750769E+00, 0.140436576643744E-01,\n 0.424623978805520E+00, -.197403745136440E+00, 0.367189752118327E+00, 0.109601109221468E-01,\n -.356966425620311E+00, 0.524066509488554E-01, -.374748135646347E+00, 0.125263969973275E-01,\n -.214575206114175E+00, 0.276138738286531E+00, 0.232593226318610E+00, 0.142541215309657E-01,\n -.481867430578161E-02, 0.484004124635174E+00, 0.348784030681802E+00, 0.148184854033573E-01,\n -.431495410462145E+00, -.397275228639652E+00, -.403570454197210E+00, 0.772943163310455E-02,\n -.131245356741703E+00, 0.756907618774431E-01, 0.537490019630355E+00, 0.247774861194694E-01,\n -.408355822291399E+00, -.123985974201377E+00, 0.265431810476576E+00, 0.187513504661882E-01,\n -.124561260584964E+00, -.234479030043771E+00, 0.369888302935578E+00, 0.248671432375052E-01,\n 0.113634878033089E+00, -.330547698703443E-01, 0.436987303689540E+00, 0.307730125976643E-01,\n 0.335166884632847E+00, 0.177062207282753E-01, 0.186039322023310E+00, 0.238461172482832E-01,\n 0.215958933320729E+00, 0.238524676460651E+00, -.347991118600472E+00, 0.239402893423799E-01,\n -.122863949389777E+00, 0.531376367885168E-01, -.273145041975343E+00, 0.332060763385794E-01,\n 0.138027624345606E+00, 0.734485926751206E-02, -.819386487269520E-01, 0.394804564434818E-01,\n 0.390531978382373E+00, -.243428663405389E+00, -.281292431872822E+00, 0.300240411183455E-01,\n -.458086784432454E+00, -.258955617426663E+00, -.254631379075299E+00, 0.265185960537560E-01,\n 0.231022856438977E+00, -.257836991797271E+00, 0.867803014584036E-01, 0.360351853787601E-01,\n 0.355406888461040E+00, 0.145836601896362E+00, -.142843849837899E+00, 0.241848262660195E-01,\n -.650524186104096E-01, -.319406461060356E+00, -.215662211604969E+00, 0.332617040610486E-01,\n -.178650654128820E+00, -.836129565920432E-01, 0.967490323299266E-01, 0.462939269977053E-01,\n 0.126510452153425E-01, 0.278960632394181E+00, 0.158303673718777E+00, 0.426257007495146E-01,\n -.457382782386756E+00, -.362054438107985E+00, -.237157888006631E-01, 0.216935544804701E-01,\n -.554273119987709E-01, 0.458349465064086E+00, -.208364056535059E+00, 0.336738699618573E-01,\n -.638763000006867E-01, -.411051272548540E+00, -.132770313096762E-01, 0.155331473891789E-01,\n -.341374973214618E+00, 0.145358665232317E+00, -.866448830311343E-01, 0.312268484322361E-01,\n 0.596607789097683E+00, -.281733562310855E+00, -.774827243010763E-01, 0.211007367041140E-01,\n 0.691731471051810E+00, -.424495189591718E+00, -.966950194712262E-02, 0.405144808936909E-02,\n 0.107828302200302E-01, 0.774068604209679E+00, -.631674539643141E-01, 0.122447617845554E-01,\n 0.183398357962906E+00, 0.509650173780726E+00, -.104199760560026E+00, 0.201330268431642E-01,\n -.156683210068974E+00, 0.587162777730252E+00, -.755800454786169E-01, 0.122331907698306E-01,\n -.721547519515627E+00, -.406928813430898E+00, -.799919904106300E-01, 0.664376101021386E-02,\n 0.563441810039983E+00, -.874528744803895E-01, -.375106925048635E+00, 0.972176210434993E-02,\n -.603817531772941E+00, -.160501116667620E+00, -.129922703170555E+00, 0.128950212070301E-01,\n 0.442461715547963E+00, -.465894984005083E+00, -.189272831033158E+00, 0.145039223723267E-01,\n 0.537695450854474E+00, -.482291905161232E+00, -.391061249617109E+00, 0.673169400168803E-02,\n 0.580167495141382E+00, -.263048745975854E-01, -.190776527382174E+00, 0.662950441786340E-02,\n 0.141863444388837E+00, 0.709313400805060E+00, -.347713452942033E+00, 0.123374761221794E-01,\n 0.380205280510817E-01, -.498131957310980E+00, -.347454353176202E+00, 0.125147680660765E-01,\n -.676654633827680E+00, -.160810255413913E+00, -.360647958818099E+00, 0.864102814374049E-02,\n -.148377942874081E+00, 0.747657811481758E+00, -.344049968649168E+00, 0.862346954119176E-02,\n 0.758853898498784E+00, -.286386495629028E+00, -.347456341168422E+00, 0.513516282754194E-02,\n -.400933270410922E+00, 0.318490934135072E+00, -.327689243668322E+00, 0.124744034495474E-01,\n 0.429402228177352E+00, 0.334245126683004E+00, -.354238091771872E+00, 0.622361500042201E-02,\n -.491182021838701E+00, -.525990681712148E+00, -.304001912945509E+00, 0.782176608831162E-02,\n -.823043669681940E+00, -.475229875889280E+00, -.344070595704639E+00, 0.756246981707266E-02,\n 0.830738527244245E+00, -.489448455641652E+00, -.329816063460246E+00, 0.635585327043357E-02,\n 0.284775635443480E-02, 0.980029354692865E+00, -.337801211308477E+00, 0.518644179936464E-02 ];\n\n% NodeSet 10 74\nTN2012_10 = [ % 74*4\n 0.413544192610844E+00, -.246750776531309E+00, -.224667871253980E-01, 0.194884222920563E-01,\n 0.692034457414863E-02, 0.481515164653911E+00, -.224667871255619E-01, 0.194884222920962E-01,\n -.420464537184973E+00, -.234764388122768E+00, -.224667871254998E-01, 0.194884222920930E-01,\n 0.121282701905074E+00, -.364557446136076E+00, -.367498543067273E+00, 0.116794850938757E-01,\n 0.255074658540227E+00, 0.287312623956679E+00, -.367498543067270E+00, 0.116794850938789E-01,\n -.376357360444638E+00, 0.772448221789755E-01, -.367498543067392E+00, 0.116794850938540E-01,\n -.479357881541579E-03, 0.110502360149269E+00, 0.916888476308096E+00, 0.624172197526661E-02,\n -.954581721268622E-01, -.556663161775985E-01, 0.916888476307731E+00, 0.624172197527072E-02,\n 0.959375300078558E-01, -.548360439716068E-01, 0.916888476308578E+00, 0.624172197526365E-02,\n 0.312630140117656E+00, 0.515676770951221E+00, -.355333655819841E+00, 0.578805012499284E-02,\n -.602904253843795E+00, 0.129072578554667E-01, -.355333655819819E+00, 0.578805012499533E-02,\n 0.290274113726703E+00, -.528584028806339E+00, -.355333655819835E+00, 0.578805012497432E-02,\n 0.179312496297470E+00, 0.282332460052200E+00, -.198316580827254E+00, 0.239540208326386E-01,\n -.334163330867068E+00, 0.141229469833529E-01, -.198316580827563E+00, 0.239540208326322E-01,\n 0.154850834569687E+00, -.296455407035973E+00, -.198316580827245E+00, 0.239540208326273E-01,\n 0.400666660401149E+00, 0.216199307780049E+00, -.144785840545057E+00, 0.118493333120654E-01,\n -.387567423018714E+00, 0.238887852466967E+00, -.144785840545187E+00, 0.118493333120532E-01,\n -.130992373825936E-01, -.455087160247049E+00, -.144785840545197E+00, 0.118493333120350E-01,\n -.115974989812532E+00, 0.793735571318706E+00, -.354239328110807E+00, 0.658548439060982E-02,\n -.629407673742435E+00, -.497305073040731E+00, -.354239328110752E+00, 0.658548439061438E-02,\n 0.745382663555392E+00, -.296430498277665E+00, -.354239328110759E+00, 0.658548439061556E-02,\n -.146516588784843E+00, 0.620735233485336E+00, -.125151192736591E+00, 0.123965418109180E-01,\n -.464314186829922E+00, -.437254704706162E+00, -.125151192736474E+00, 0.123965418109110E-01,\n 0.610830775614764E+00, -.183480528779117E+00, -.125151192736430E+00, 0.123965418109090E-01,\n 0.152677322698633E+00, 0.615349010913590E+00, -.138717779739843E+00, 0.129228051042385E-01,\n -.609246536994131E+00, -.175452065417948E+00, -.138717779739883E+00, 0.129228051042351E-01,\n 0.456569214295294E+00, -.439896945495579E+00, -.138717779739667E+00, 0.129228051042306E-01,\n -.234983628865204E+00, -.506023035146311E+00, -.354913786574649E+00, 0.861537010564474E-02,\n 0.555720617769565E+00, 0.495097255022037E-01, -.354913786574608E+00, 0.861537010564896E-02,\n -.320736988903808E+00, 0.456513309644504E+00, -.354913786574637E+00, 0.861537010565374E-02,\n 0.261719079216423E+00, 0.120684595399040E+00, 0.865913059621064E-01, 0.252926861510092E-01,\n -.235375465069513E+00, 0.166313073556813E+00, 0.865913059617144E-01, 0.252926861510152E-01,\n -.263436141471209E-01, -.286997668956207E+00, 0.865913059620792E-01, 0.252926861510182E-01,\n -.151870784241490E+00, 0.375380795135610E+00, 0.259768753032010E+00, 0.105992396528304E-01,\n -.249153912559676E+00, -.319214354813566E+00, 0.259768753032135E+00, 0.105992396528186E-01,\n 0.401024696800887E+00, -.561664403219833E-01, 0.259768753032231E+00, 0.105992396528257E-01,\n 0.210831894372952E+00, -.130924570230131E+00, 0.263063208114240E+00, 0.264859218837044E-01,\n 0.796805661212086E-02, 0.248048061569683E+00, 0.263063208114389E+00, 0.264859218837275E-01,\n -.218799950985084E+00, -.117123491339812E+00, 0.263063208114476E+00, 0.264859218837323E-01,\n -.645184534114996E+00, -.294850962306783E+00, -.345383308918403E+00, 0.117883930527143E-01,\n 0.577940690745812E+00, -.411320715519360E+00, -.345383308918355E+00, 0.117883930527001E-01,\n 0.672438433695747E-01, 0.706171677825659E+00, -.345383308918353E+00, 0.117883930527065E-01,\n -.111702700311124E+00, 0.378278113185099E+00, -.232788953429898E+00, 0.257606535268669E-01,\n -.271747105558396E+00, -.285876432733472E+00, -.232788953429742E+00, 0.257606535268701E-01,\n 0.383449805869739E+00, -.924016804521191E-01, -.232788953429680E+00, 0.257606535268793E-01,\n 0.235386463106491E+00, -.326349752361119E+00, 0.241526812057868E+00, 0.111411397385480E-01,\n 0.164933944510181E+00, 0.367025532937718E+00, 0.241526812057621E+00, 0.111411397385863E-01,\n -.400320407616776E+00, -.406757805765914E-01, 0.241526812057666E+00, 0.111411397385560E-01,\n 0.781386647435055E+00, -.452646852034879E+00, -.213306800322009E+00, 0.673992636364470E-02,\n 0.131034908770753E-02, 0.903024112874510E+00, -.213306800322442E+00, 0.673992636363803E-02,\n -.782696996523264E+00, -.450377260839599E+00, -.213306800322782E+00, 0.673992636364011E-02,\n -.144648648594220E+00, 0.855865956909313E-01, 0.605581650673550E+00, 0.157113747630530E-01,\n -.179584179474888E-02, -.168062702151182E+00, 0.605581650673681E+00, 0.157113747630306E-01,\n 0.146444490388834E+00, 0.824761064602773E-01, 0.605581650673770E+00, 0.157113747630343E-01,\n 0.566289741151568E+00, -.329071545508948E+00, 0.141413168417081E+00, 0.959306888489052E-02,\n 0.183944749757621E-02, 0.654957074494562E+00, 0.141413168416557E+00, 0.959306888489720E-02,\n -.568129188649652E+00, -.325885528985560E+00, 0.141413168416239E+00, 0.959306888489236E-02,\n 0.195995882040799E-02, 0.350093442409637E+00, 0.559353834699797E+00, 0.107406866856387E-01,\n -.304169794235504E+00, -.173349347076073E+00, 0.559353834699497E+00, 0.107406866856343E-01,\n 0.302209835414552E+00, -.176744095333465E+00, 0.559353834700328E+00, 0.107406866856401E-01,\n -.713806162729187E-01, 0.396304230394379E+00, -.396100787902427E+00, 0.774239246773105E-02,\n -.307519223012102E+00, -.259969542227603E+00, -.396100787902375E+00, 0.774239246774146E-02,\n 0.378899839285653E+00, -.136334688167220E+00, -.396100787902350E+00, 0.774239246774322E-02,\n -.318784852490390E-01, 0.106707438509449E+01, -.395074109048042E+00, 0.744912589128255E-03,\n -.908174282594812E+00, -.561144770606617E+00, -.395074109048246E+00, 0.744912589134030E-03,\n 0.940052767843358E+00, -.505929614487096E+00, -.395074109047602E+00, 0.744912589138556E-03,\n 0.997667683143875E-01, 0.947218006642626E+00, -.377949220857205E+00, 0.159576637662907E-02,\n -.870198240831572E+00, -.387208447506806E+00, -.377949220857219E+00, 0.159576637662087E-02,\n 0.770431472517722E+00, -.560009559135281E+00, -.377949220857186E+00, 0.159576637661854E-02,\n -.820775777814033E-14, -.146673911156923E-12, -.346454886778686E-01, 0.439146516704393E-01,\n -.347841759723423E-12, 0.241985437638784E-13, 0.120100985698529E+01, 0.360074156134488E-03,\n 0.479095201677494E-12, -.155248834093771E-12, 0.406812386591265E+00, 0.110828201197969E-01,\n 0.137478771276506E-12, -.230632360521964E-12, -.334140778607838E+00, 0.263152783811875E-01,\n 0.142035845739461E-12, -.170617436886576E-12, 0.569947520590082E+00, 0.107640257183785E-01 ];\n\n% NodeSet 11 95\nTN2012_11 = [ % 95*4\n 0.965117777689970E-01, 0.763379519383339E+00, -.186826886312270E+00, 0.600845159732900E-02,\n -.709361945399304E+00, -.298108108379529E+00, -.186826886312305E+00, 0.600845159733409E-02,\n 0.612850167629794E+00, -.465271411003715E+00, -.186826886311271E+00, 0.600845159734557E-02,\n -.452783642439655E-02, 0.535212668450515E+00, 0.419413645671028E+00, 0.137982881729824E-02,\n -.461243849092658E+00, -.271527555592882E+00, 0.419413645671752E+00, 0.137982881730247E-02,\n 0.465771685518937E+00, -.263685112857434E+00, 0.419413645671101E+00, 0.137982881724185E-02,\n 0.243865553143861E-01, -.385976677345993E+00, 0.503008658379878E-01, 0.920652231770260E-02,\n 0.322072330192304E+00, 0.214107715087058E+00, 0.503008658372996E-01, 0.920652231774636E-02,\n -.346458885508177E+00, 0.171868962258854E+00, 0.503008658370734E-01, 0.920652231767883E-02,\n -.126750066458516E+00, 0.693029111438289E+00, -.150595614519410E+00, 0.661716072025893E-02,\n -.536805782837873E+00, -.456283333203682E+00, -.150595614519024E+00, 0.661716072024581E-02,\n 0.663555849297038E+00, -.236745778234389E+00, -.150595614519243E+00, 0.661716072024213E-02,\n -.954797245177502E-01, 0.327297126599053E+00, -.172527578542390E+00, 0.185656100008145E-01,\n -.235707763961444E+00, -.246336430278646E+00, -.172527578542985E+00, 0.185656100007781E-01,\n 0.331187488479253E+00, -.809606963205869E-01, -.172527578541491E+00, 0.185656100009255E-01,\n -.790832808659181E-02, 0.911574214979798E+00, -.170981061542019E+00, 0.298677403005469E-02,\n -.785492263564104E+00, -.462635920514496E+00, -.170981061542179E+00, 0.298677403005462E-02,\n 0.793400591649882E+00, -.448938294464901E+00, -.170981061540804E+00, 0.298677403007424E-02,\n -.149464443207015E+00, 0.450624307688046E+00, 0.767474283940176E-01, 0.110287876790012E-01,\n -.315519876417291E+00, -.354752158623110E+00, 0.767474283947060E-01, 0.110287876790499E-01,\n 0.464984319623066E+00, -.958721490650558E-01, 0.767474283968136E-01, 0.110287876791503E-01,\n 0.116527686078558E+00, 0.399090383783252E+00, -.372013456992333E+00, 0.105992886100834E-01,\n -.403886253801475E+00, -.986292555028626E-01, -.372013456992289E+00, 0.105992886100787E-01,\n 0.287358567722714E+00, -.300461128279899E+00, -.372013456992142E+00, 0.105992886101145E-01,\n -.204775506709099E-02, 0.107474766209103E+00, 0.934296066501945E+00, 0.409142461938696E-02,\n -.920520002693779E-01, -.555107910131548E-01, 0.934296066502188E+00, 0.409142461937905E-02,\n 0.940997553396656E-01, -.519639751977071E-01, 0.934296066495320E+00, 0.409142461947846E-02,\n 0.346835457488581E+00, -.394508692759800E+00, -.361173628980284E-01, 0.117181969107905E-01,\n 0.168236821198931E+00, 0.497622663499452E+00, -.361173628986015E-01, 0.117181969107935E-01,\n -.515072278689013E+00, -.103113970739211E+00, -.361173628990288E-01, 0.117181969107802E-01,\n -.114431972741818E+00, 0.876715287683553E+00, -.353556036747552E+00, 0.250403187559638E-02,\n -.702041724648949E+00, -.537458639241080E+00, -.353556036747620E+00, 0.250403187561624E-02,\n 0.816473697390820E+00, -.339256648442110E+00, -.353556036747688E+00, 0.250403187560628E-02,\n -.304870256759300E+00, 0.362285109955623E+00, -.192611435219708E+00, 0.121611426335016E-01,\n -.161312980254746E+00, -.445167942189768E+00, -.192611435219803E+00, 0.121611426334971E-01,\n 0.466183237014652E+00, 0.828828322332235E-01, -.192611435219709E+00, 0.121611426335199E-01,\n 0.210164030825951E+00, -.499019487215612E+00, -.281852351964106E+00, 0.782992696918182E-02,\n 0.327081537499466E+00, 0.431517133264640E+00, -.281852351964309E+00, 0.782992696917981E-02,\n -.537245568325068E+00, 0.675023539512562E-01, -.281852351964830E+00, 0.782992696920705E-02,\n -.640407059904653E-01, 0.706921078951722E+00, -.388855276146498E+00, 0.484839331593464E-02,\n -.580191259847264E+00, -.408921417739124E+00, -.388855276146452E+00, 0.484839331594336E-02,\n 0.644231965837054E+00, -.297999661211961E+00, -.388855276145405E+00, 0.484839331606112E-02,\n 0.547000964710360E-02, 0.287534224296398E+00, 0.665484806312732E+00, 0.597173171055007E-02,\n -.251746947521409E+00, -.139029944834592E+00, 0.665484806313078E+00, 0.597173171055419E-02,\n 0.246276937877777E+00, -.148504279463874E+00, 0.665484806307889E+00, 0.597173171042218E-02,\n 0.100846198138096E-01, -.205752031778813E+00, 0.179468318187578E-01, 0.260067107585456E-01,\n 0.173144176492929E+00, 0.111609552836825E+00, 0.179468318197516E-01, 0.260067107585507E-01,\n -.183228796308316E+00, 0.941424789424061E-01, 0.179468318186687E-01, 0.260067107585578E-01,\n 0.174898207844580E+00, 0.337221337718768E+00, -.227279445343111E+00, 0.189036526144369E-01,\n -.379491349084951E+00, -.171443777901745E-01, -.227279445343298E+00, 0.189036526143951E-01,\n 0.204593141240706E+00, -.320076959928987E+00, -.227279445342920E+00, 0.189036526144052E-01,\n 0.106539163848767E-01, 0.392485195255571E+00, 0.807848010336490E-01, 0.204109886439253E-01,\n -.345229107893253E+00, -.187016035388081E+00, 0.807848010331957E-01, 0.204109886439160E-01,\n 0.334575191505824E+00, -.205469159866835E+00, 0.807848010360809E-01, 0.204109886439593E-01,\n -.708368682688562E-03, -.242259848811423E+00, 0.340611194255165E+00, 0.163646441659378E-01,\n 0.210157367729121E+00, 0.120516459131557E+00, 0.340611194255109E+00, 0.163646441658739E-01,\n -.209448999046689E+00, 0.121743389680979E+00, 0.340611194253702E+00, 0.163646441659038E-01,\n -.285127304889096E+00, 0.541912173452750E+00, -.354913123600949E+00, 0.572964737547824E-02,\n -.326746056385501E+00, -.517883576072872E+00, -.354913123601104E+00, 0.572964737548000E-02,\n 0.611873361274685E+00, -.240285973797814E-01, -.354913123601249E+00, 0.572964737546058E-02,\n -.232320939692072E-02, 0.251307339208139E+00, 0.421305767658705E+00, 0.164150916714920E-01,\n -.216476935213671E+00, -.127665627959789E+00, 0.421305767658474E+00, 0.164150916715063E-01,\n 0.218800144609601E+00, -.123641711247167E+00, 0.421305767661954E+00, 0.164150916714715E-01,\n -.205157790402930E-01, 0.655109849960249E+00, -.243025087375771E+00, 0.143350299742849E-01,\n -.557083882814730E+00, -.345322110807617E+00, -.243025087375512E+00, 0.143350299742910E-01,\n 0.577599661854348E+00, -.309787739152588E+00, -.243025087373678E+00, 0.143350299742819E-01,\n -.302645519699800E-02, -.166602186418557E+00, 0.693950700576721E+00, 0.678988863033392E-02,\n 0.145794953362658E+00, 0.806801061259830E-01, 0.693950700576845E+00, 0.678988863030666E-02,\n -.142768498166691E+00, 0.859220802934521E-01, 0.693950700575701E+00, 0.678988863030576E-02,\n -.197353854914094E+00, 0.296656144937577E+00, -.354789590718461E+00, 0.146915319740604E-01,\n -.158234830247364E+00, -.319241524359057E+00, -.354789590718600E+00, 0.146915319740350E-01,\n 0.355588685161490E+00, 0.225853794216406E-01, -.354789590718495E+00, 0.146915319740717E-01,\n 0.106885774436226E+00, 0.414728869215933E+00, 0.327363420469225E+00, 0.681230704214779E-02,\n -.412608623641975E+00, -.114798638643009E+00, 0.327363420469154E+00, 0.681230704214552E-02,\n 0.305722849205178E+00, -.299930230573075E+00, 0.327363420469785E+00, 0.681230704208426E-02,\n -.300336408294241E+00, -.288233526509174E+00, 0.379747909798793E+00, 0.482110236270034E-02,\n 0.399785760325697E+00, -.115982196008667E+00, 0.379747909801915E+00, 0.482110236255637E-02,\n -.994493520320316E-01, 0.404215722519396E+00, 0.379747909798407E+00, 0.482110236269031E-02,\n 0.122183524609399E-01, 0.100907701884453E+01, -.362667202068887E+00, 0.263398684352695E-02,\n -.879995508924978E+00, -.493957105798725E+00, -.362667202068938E+00, 0.263398684352256E-02,\n 0.867777156463928E+00, -.515119913045772E+00, -.362667202068643E+00, 0.263398684353644E-02,\n 0.153456883865012E+00, 0.748965017517851E+00, -.365662386060026E+00, 0.572950098933217E-02,\n -.725351173648843E+00, -.241584948946274E+00, -.365662386060004E+00, 0.572950098933272E-02,\n 0.571894289784060E+00, -.507380068571563E+00, -.365662386059841E+00, 0.572950098935171E-02,\n 0.223545621647398E-02, 0.666719280580741E+00, 0.105695336068241E+00, 0.851444680345821E-02,\n -.578513562284073E+00, -.331423678417813E+00, 0.105695336068278E+00, 0.851444680346480E-02,\n 0.576278106065851E+00, -.335295602162006E+00, 0.105695336070785E+00, 0.851444680349955E-02,\n 0.943641659215635E-01, -.515850141384783E+00, -.401512235299027E+00, 0.308329306953878E-02,\n 0.399557244024400E+00, 0.339646835586887E+00, -.401512235299043E+00, 0.308329306953569E-02,\n -.493921409945304E+00, 0.176203305798363E+00, -.401512235299548E+00, 0.308329306949863E-02,\n 0.157895181731732E-11, -.806952626522489E-12, 0.111822360907102E+01, 0.104767813052089E-02,\n -.723450889997721E-12, 0.459685166655004E-12, 0.666410458367556E+00, 0.169670060154491E-01,\n -.119501050305224E-12, 0.115625438680115E-12, -.380999085805230E+00, 0.109719477490228E-01,\n 0.127319386408849E-12, 0.576565413140336E-13, -.225394550268228E+00, 0.280623276941522E-01,\n -.139831304526210E-12, -.122619858793024E-12, 0.260494099975575E+00, 0.254827978128425E-01 ];\n\n% NodeSet 12 122\nTN2012_12 = [ % 122*4\n 0.395854409891267E+00, 0.333851555538772E+00, -.390557745165981E+00, 0.196698372273148E-02,\n -.487051133135165E+00, 0.175894197396554E+00, -.390557745165981E+00, 0.196698372273156E-02,\n 0.911967232438951E-01, -.509745752935337E+00, -.390557745165989E+00, 0.196698372273062E-02,\n -.592643180494659E+00, -.257532889411981E+00, -.419476157759784E-02, 0.593882685696330E-02,\n 0.519351614788115E+00, -.384477604981992E+00, -.419476157760429E-02, 0.593882685696352E-02,\n 0.732915657065390E-01, 0.642010494393973E+00, -.419476157758415E-02, 0.593882685696374E-02,\n -.454414185024514E-01, 0.344585845204826E+00, 0.187402702185600E+00, 0.123879940796820E-01,\n -.275699386480693E+00, -.211646345409540E+00, 0.187402702185615E+00, 0.123879940796815E-01,\n 0.321140804983144E+00, -.132939499795295E+00, 0.187402702185621E+00, 0.123879940796812E-01,\n -.341386063086216E+00, -.408973262387964E+00, -.307110201339023E+00, 0.809284187539252E-02,\n 0.524874266239694E+00, -.911623719366133E-01, -.307110201339028E+00, 0.809284187539236E-02,\n -.183488203153488E+00, 0.500135634324581E+00, -.307110201339028E+00, 0.809284187539222E-02,\n -.131972243113920E+00, -.243782408641952E+00, -.270196159791184E-01, 0.146386931024421E-01,\n 0.277107880436666E+00, 0.759988918990409E-02, -.270196159791151E-01, 0.146386931024407E-01,\n -.145135637322735E+00, 0.236182519452053E+00, -.270196159791055E-01, 0.146386931024392E-01,\n 0.291671915694103E+00, 0.572563599327284E+00, -.365022387456384E+00, 0.265528824562810E-02,\n -.641690580146739E+00, -.336865111020842E-01, -.365022387456384E+00, 0.265528824562798E-02,\n 0.350018664452620E+00, -.538877088225203E+00, -.365022387456383E+00, 0.265528824562834E-02,\n -.407043948553664E-01, 0.579489770656000E+00, -.861239200062299E-01, 0.112080999248455E-01,\n -.481500665193633E+00, -.324995925318421E+00, -.861239200062188E-01, 0.112080999248459E-01,\n 0.522205060049005E+00, -.254493845337578E+00, -.861239200062174E-01, 0.112080999248457E-01,\n -.982085654981925E-01, 0.550459421679584E+00, 0.107079122173015E+00, 0.695607989649797E-02,\n -.427607560177907E+00, -.360280823430456E+00, 0.107079122173020E+00, 0.695607989649740E-02,\n 0.525816125676105E+00, -.190178598249124E+00, 0.107079122173022E+00, 0.695607989649711E-02,\n 0.218408903368161E+00, 0.411598677519539E+00, 0.323037482249117E-01, 0.736054409846543E-02,\n -.465659362580079E+00, -.166516800302459E-01, 0.323037482249063E-01, 0.736054409846635E-02,\n 0.247250459211923E+00, -.394946997489293E+00, 0.323037482249106E-01, 0.736054409846627E-02,\n -.660677749114476E-02, -.143062077792866E+00, 0.328982719937537E+00, 0.183928475395296E-01,\n 0.127198782432377E+00, 0.658094017519560E-01, 0.328982719937527E+00, 0.183928475395297E-01,\n -.120592004941238E+00, 0.772526760409100E-01, 0.328982719937539E+00, 0.183928475395289E-01,\n -.186234667494277E+00, 0.234269739501763E+00, -.200232446998792E+00, 0.159414592319126E-01,\n -.109766211999345E+00, -.278418822866280E+00, -.200232446998804E+00, 0.159414592319108E-01,\n 0.296000879493631E+00, 0.441490833645066E-01, -.200232446998801E+00, 0.159414592319116E-01,\n -.589040275422118E+00, -.401755436436729E+00, -.277182597081116E+00, 0.819183899036344E-02,\n 0.642450551773759E+00, -.309246124149365E+00, -.277182597081118E+00, 0.819183899036412E-02,\n -.534102763516564E-01, 0.711001560586086E+00, -.277182597081118E+00, 0.819183899036391E-02,\n -.119640021030782E-01, 0.908525373598771E+00, -.379414595213076E+00, 0.294790999852269E-02,\n -.780824052467749E+00, -.464623816551583E+00, -.379414595213078E+00, 0.294790999852259E-02,\n 0.792788054570826E+00, -.443901557047195E+00, -.379414595213078E+00, 0.294790999852263E-02,\n 0.623523946168630E-01, 0.473029639538299E+00, 0.288759219788336E+00, 0.727501233383112E-02,\n -.440831881891602E+00, -.182516062044160E+00, 0.288759219788326E+00, 0.727501233383119E-02,\n 0.378479487274750E+00, -.290513577494149E+00, 0.288759219788326E+00, 0.727501233383113E-02,\n 0.223590386309356E+00, -.685745684803208E-01, 0.730795305056316E+00, 0.297359482938225E-02,\n -.524078747971530E-01, 0.227922238826041E+00, 0.730795305056320E+00, 0.297359482938299E-02,\n -.171182511512208E+00, -.159347670345715E+00, 0.730795305056314E+00, 0.297359482938252E-02,\n 0.166647705033182E+00, 0.219014023508552E+00, 0.412491824632861E+00, 0.859915960963346E-02,\n -.272995560660045E+00, 0.348141342868342E-01, 0.412491824632852E+00, 0.859915960963336E-02,\n 0.106347855626874E+00, -.253828157795390E+00, 0.412491824632853E+00, 0.859915960963354E-02,\n -.741504913903760E-01, -.425160033234697E-01, 0.983902012123622E+00, 0.298228147645889E-02,\n 0.738951846406989E-01, -.429582075854323E-01, 0.983902012123617E+00, 0.298228147645893E-02,\n 0.255306749680119E-03, 0.854742109088923E-01, 0.983902012123638E+00, 0.298228147645866E-02,\n 0.195590871722804E+00, -.244732213104454E+00, 0.682975149260760E-01, 0.177091390217947E-01,\n 0.114148877811455E+00, 0.291752770212531E+00, 0.682975149260640E-01, 0.177091390217942E-01,\n -.309739749534244E+00, -.470205571080570E-01, 0.682975149260745E-01, 0.177091390217946E-01,\n -.180268025859154E-01, 0.260028370424514E+00, 0.509026771210850E+00, 0.108911229551476E-01,\n -.216177773199345E+00, -.145625854200665E+00, 0.509026771210867E+00, 0.108911229551474E-01,\n 0.234204575785254E+00, -.114402516223841E+00, 0.509026771210866E+00, 0.108911229551477E-01,\n -.153261381170292E+00, 0.296445376975146E+00, 0.385161785525853E+00, 0.502733325550593E-02,\n -.180098536709772E+00, -.280950938000134E+00, 0.385161785525857E+00, 0.502733325550605E-02,\n 0.333359917880078E+00, -.154944389750067E-01, 0.385161785525851E+00, 0.502733325550543E-02,\n 0.577633666523352E-02, 0.777575919372589E+00, 0.234842077607212E-01, 0.314863068921769E-02,\n -.676288667880321E+00, -.383785505393390E+00, 0.234842077607121E-01, 0.314863068921804E-02,\n 0.670512331215088E+00, -.393790413979201E+00, 0.234842077607110E-01, 0.314863068921800E-02,\n -.830459079091334E-01, -.362439189266012E+00, 0.774728166241968E-01, 0.110344801019880E-01,\n 0.355404499185969E+00, 0.109299728703350E+00, 0.774728166242032E-01, 0.110344801019876E-01,\n -.272358591276836E+00, 0.253139460562663E+00, 0.774728166241957E-01, 0.110344801019877E-01,\n 0.542384531596793E+00, -.214582781999708E-01, -.163033856608466E+00, 0.793705941737894E-02,\n -.252608851755744E+00, 0.480447922082540E+00, -.163033856608472E+00, 0.793705941737921E-02,\n -.289775679841053E+00, -.458989643882559E+00, -.163033856608470E+00, 0.793705941737940E-02,\n 0.557343196731010E+00, 0.934213228803310E-01, -.358456239566711E+00, 0.396471418063503E-02,\n -.359576837235012E+00, 0.435962705555325E+00, -.358456239566711E+00, 0.396471418063520E-02,\n -.197766359495993E+00, -.529384028435640E+00, -.358456239566708E+00, 0.396471418063583E-02,\n 0.473136623876986E+00, -.250358512021129E+00, 0.369862621961321E+00, 0.303733516257231E-02,\n -.197514804745208E-01, 0.534927591748828E+00, 0.369862621961330E+00, 0.303733516257264E-02,\n -.453385143402462E+00, -.284569079727708E+00, 0.369862621961319E+00, 0.303733516257254E-02,\n 0.315321932442742E+00, -.153252510670659E+00, -.366729822887569E+00, 0.105027803145516E-01,\n -.249403987868362E-01, 0.349703059201127E+00, -.366729822887571E+00, 0.105027803145513E-01,\n -.290381533655895E+00, -.196450548530486E+00, -.366729822887572E+00, 0.105027803145511E-01,\n -.183165376400892E-01, 0.108643540500343E+01, -.379008133716638E+00, 0.476818959640627E-03,\n -.931722391483764E+00, -.559080289407412E+00, -.379008133716641E+00, 0.476818959640552E-03,\n 0.950038929123857E+00, -.527355115596027E+00, -.379008133716642E+00, 0.476818959640539E-03,\n -.669997455371388E+00, -.227798897754623E+00, -.219722706081442E+00, 0.784021930375232E-02,\n 0.532278360095291E+00, -.466335367945242E+00, -.219722706081443E+00, 0.784021930375221E-02,\n 0.137719095276097E+00, 0.694134265699857E+00, -.219722706081437E+00, 0.784021930375275E-02,\n 0.278278328278097E+00, 0.210817208106962E+00, -.365464586905286E+00, 0.108042147702591E-01,\n -.321712221914591E+00, 0.135587497558006E+00, -.365464586905286E+00, 0.108042147702593E-01,\n 0.434338936365029E-01, -.346404705664989E+00, -.365464586905287E+00, 0.108042147702594E-01,\n 0.974677087891540E-01, 0.374855937111035E+00, -.201472632623356E+00, 0.206967714188870E-01,\n -.373368618692161E+00, -.103018456695450E+00, -.201472632623353E+00, 0.206967714188874E-01,\n 0.275900909903009E+00, -.271837480415594E+00, -.201472632623350E+00, 0.206967714188872E-01,\n 0.108908146593124E-01, 0.940032615892273E+00, -.246440528575148E+00, 0.346740810672804E-02,\n -.819537533078310E+00, -.460584585783268E+00, -.246440528575155E+00, 0.346740810672790E-02,\n 0.808646718418997E+00, -.479448030109011E+00, -.246440528575156E+00, 0.346740810672803E-02,\n -.125193888603033E+00, 0.326782427510051E-01, 0.737539571985585E+00, 0.754303426952455E-02,\n 0.342967559281075E-01, -.124760209304291E+00, 0.737539571985584E+00, 0.754303426952443E-02,\n 0.908971326749169E-01, 0.920819665532847E-01, 0.737539571985590E+00, 0.754303426952452E-02,\n 0.486885272388682E+00, -.419470048425788E+00, -.368924026122376E+00, 0.739775920991071E-02,\n 0.119829081869080E+00, 0.631390038829989E+00, -.368924026122375E+00, 0.739775920991112E-02,\n -.606714354257758E+00, -.211919990404208E+00, -.368924026122375E+00, 0.739775920991109E-02,\n 0.338254046583528E+00, 0.336279909351889E+00, -.220250860026090E+00, 0.114614821427815E-01,\n -.460353967572830E+00, 0.124796642598277E+00, -.220250860026094E+00, 0.114614821427812E-01,\n 0.122099920989301E+00, -.461076551950167E+00, -.220250860026091E+00, 0.114614821427811E-01,\n -.948021074991389E-01, 0.799664327081630E+00, -.159472036609177E+00, 0.267380541702802E-02,\n -.645128568003312E+00, -.481933196967374E+00, -.159472036609172E+00, 0.267380541702784E-02,\n 0.739930675502450E+00, -.317731130114253E+00, -.159472036609174E+00, 0.267380541702784E-02,\n 0.114011306776160E+00, 0.921756734003682E+00, -.375888607361787E+00, 0.121571084356495E-02,\n -.855270401144653E+00, -.362141679015031E+00, -.375888607361789E+00, 0.121571084356478E-02,\n 0.741259094368485E+00, -.559615054988663E+00, -.375888607361789E+00, 0.121571084356474E-02,\n -.165842180155680E+00, 0.816962945157694E+00, -.354270062100271E+00, 0.197644247637581E-02,\n -.624589574379273E+00, -.552105013612662E+00, -.354270062100270E+00, 0.197644247637581E-02,\n 0.790431754534958E+00, -.264857931545035E+00, -.354270062100270E+00, 0.197644247637583E-02,\n 0.255741305649357E+00, -.185422039944996E+00, 0.689558909191225E+00, 0.209026833265583E-02,\n 0.327095441892273E-01, 0.314189487461839E+00, 0.689558909191237E+00, 0.209026833265534E-02,\n -.288450849838587E+00, -.128767447516842E+00, 0.689558909191228E+00, 0.209026833265520E-02,\n -.161315756957164E+00, 0.622400231722008E+00, -.407391669247035E+00, 0.246529805415523E-02,\n -.458356533514003E+00, -.450903659416629E+00, -.407391669247037E+00, 0.246529805415509E-02,\n 0.619672290471167E+00, -.171496572305384E+00, -.407391669247040E+00, 0.246529805415493E-02,\n 0.215699898765183E-14, -.174736370992125E-14, 0.648211705357551E+00, 0.104708231427821E-01,\n 0.215768577391029E-14, -.784133983875845E-14, 0.119860353953893E+01, 0.188750315664348E-03,\n 0.932976159332810E-14, -.103874241321632E-13, -.404150914547157E+00, 0.466026308255542E-02,\n -.193782609554479E-14, -.643408870516526E-14, -.271058498607272E+00, 0.240578023764951E-01,\n 0.511210059808282E-14, 0.851161159313764E-14, 0.875755507387370E-02, 0.278175500155602E-01 ];\n\n% NodeSet 13 146\nTN2012_13 = [ % 146*4\n -.477738501746661E-01, 0.901553008435599E+00, -.232771532399634E+00, 0.200887673646286E-02,\n -.756880883076013E+00, -.492149872105709E+00, -.232771532399608E+00, 0.200887673646046E-02,\n 0.804654733250740E+00, -.409403136329800E+00, -.232771532399543E+00, 0.200887673646232E-02,\n 0.300590794496799E-01, 0.383606470976431E+00, 0.349676269655079E+00, 0.666306373868558E-02,\n -.347242488646652E+00, -.165771309070485E+00, 0.349676269654910E+00, 0.666306373869141E-02,\n 0.317183409197188E+00, -.217835161906151E+00, 0.349676269654956E+00, 0.666306373867523E-02,\n -.352982441311086E-01, 0.506449235044572E+00, 0.271798856540911E+00, 0.460737122110414E-02,\n -.420948781210288E+00, -.283793793648819E+00, 0.271798856540994E+00, 0.460737122109711E-02,\n 0.456247025341450E+00, -.222655441395830E+00, 0.271798856540755E+00, 0.460737122109625E-02,\n -.715353708088888E+00, -.278605040267896E+00, -.387412868821165E+00, 0.256268951692279E-02,\n 0.598955896538828E+00, -.480211963762482E+00, -.387412868821213E+00, 0.256268951691948E-02,\n 0.116397811550130E+00, 0.758817004030299E+00, -.387412868821203E+00, 0.256268951691991E-02,\n 0.371051945602552E-02, -.539347646199226E+00, -.378314593714867E+00, 0.235005654447042E-02,\n 0.465233503351929E+00, 0.272887227209696E+00, -.378314593714866E+00, 0.235005654446923E-02,\n -.468944022807853E+00, 0.266460418989514E+00, -.378314593714884E+00, 0.235005654447035E-02,\n -.359916057535362E-01, -.203223368274530E+00, -.390805436342884E+00, 0.527052754118289E-02,\n 0.193992402445282E+00, 0.704420392315130E-01, -.390805436342852E+00, 0.527052754118820E-02,\n -.158000796691468E+00, 0.132781329042865E+00, -.390805436342852E+00, 0.527052754118752E-02,\n -.216153735984865E-01, -.323838377680154E+00, 0.221462113265870E+00, 0.714961366974697E-02,\n 0.291259948590594E+00, 0.143199726191490E+00, 0.221462113265889E+00, 0.714961366974774E-02,\n -.269644574992100E+00, 0.180638651488654E+00, 0.221462113265882E+00, 0.714961366974817E-02,\n -.491357307496588E+00, 0.193872320289677E-01, -.533215602674804E-01, 0.448845818235097E-02,\n 0.228888818302316E+00, -.435221526641670E+00, -.533215602674484E-01, 0.448845818234801E-02,\n 0.262468489194418E+00, 0.415834294612734E+00, -.533215602674526E-01, 0.448845818235013E-02,\n -.142628109882219E+00, 0.442438151760315E+00, -.136612672009748E+00, 0.108071845189417E-01,\n -.311848624086726E+00, -.344738642331984E+00, -.136612672009748E+00, 0.108071845189381E-01,\n 0.454476733969026E+00, -.976995094284715E-01, -.136612672009781E+00, 0.108071845189454E-01,\n 0.761875476381042E+00, -.275635240194294E+00, -.340571881592319E+00, 0.293227202050287E-02,\n -.142230618004072E+00, 0.797621137163424E+00, -.340571881592331E+00, 0.293227202050352E-02,\n -.619644858376870E+00, -.521985896969213E+00, -.340571881592377E+00, 0.293227202050308E-02,\n 0.577689788002780E-01, -.167839657889956E+00, 0.248215855875381E+00, 0.145445430335915E-01,\n 0.116468918095072E+00, 0.133949232136841E+00, 0.248215855875382E+00, 0.145445430335873E-01,\n -.174237896895506E+00, 0.338904257531623E-01, 0.248215855875340E+00, 0.145445430335903E-01,\n -.141471914229626E+00, 0.454574639911821E+00, 0.149307855052120E+00, 0.637963291334823E-02,\n -.322937228965002E+00, -.349805591600753E+00, 0.149307855052161E+00, 0.637963291335070E-02,\n 0.464409143194571E+00, -.104769048311047E+00, 0.149307855052182E+00, 0.637963291335052E-02,\n -.139825817032614E+00, 0.669493017476507E+00, -.124686100142567E+00, 0.437334200450381E-02,\n -.509885052274530E+00, -.455839218393426E+00, -.124686100142531E+00, 0.437334200449979E-02,\n 0.649710869307182E+00, -.213653799083052E+00, -.124686100142451E+00, 0.437334200450373E-02,\n 0.361031892137155E+00, -.330220034803623E+00, -.880409067166617E-01, 0.120346556615560E-01,\n 0.105462992909919E+00, 0.477772807568843E+00, -.880409067166118E-01, 0.120346556615633E-01,\n -.466494885047039E+00, -.147552772765385E+00, -.880409067164646E-01, 0.120346556615583E-01,\n 0.245901346521248E-01, 0.814663848466296E+00, -.290390441652983E+00, 0.521154166200869E-02,\n -.717814655642789E+00, -.386036242942058E+00, -.290390441652948E+00, 0.521154166200641E-02,\n 0.693224520990723E+00, -.428627605524495E+00, -.290390441653070E+00, 0.521154166200487E-02,\n -.106559514117573E-01, 0.107045377333378E+01, -.358871681151519E+00, 0.613289703460351E-03,\n -.921712185578031E+00, -.544455211290932E+00, -.358871681151507E+00, 0.613289703461410E-03,\n 0.932368136989749E+00, -.525998562042731E+00, -.358871681151508E+00, 0.613289703462290E-03,\n -.411528552887236E+00, -.705388131299747E-01, 0.174864964482491E+00, 0.861854803007364E-02,\n 0.266852680566911E+00, -.321124774617904E+00, 0.174864964482526E+00, 0.861854803008962E-02,\n 0.144675872320202E+00, 0.391663587747994E+00, 0.174864964482476E+00, 0.861854803008200E-02,\n 0.157119041239772E-02, 0.790237540364792E-01, 0.100562602248012E+01, 0.209967579380148E-02,\n -.692221737042301E-01, -.381511862069326E-01, 0.100562602248007E+01, 0.209967579380181E-02,\n 0.676509832917168E-01, -.408725678295113E-01, 0.100562602248031E+01, 0.209967579379976E-02,\n -.299118986162933E+00, 0.316528443913753E+00, -.608536384527786E-01, 0.782057398216375E-02,\n -.124562180368101E+00, -.417308862728220E+00, -.608536384527546E-01, 0.782057398216339E-02,\n 0.423681166531102E+00, 0.100780418814494E+00, -.608536384527534E-01, 0.782057398216470E-02,\n 0.387169643039315E+00, -.396828227141254E+00, -.290741621266202E+00, 0.878729001495772E-02,\n 0.150078504123429E+00, 0.533712860016693E+00, -.290741621266215E+00, 0.878729001495983E-02,\n -.537248147162582E+00, -.136884632875611E+00, -.290741621266106E+00, 0.878729001496600E-02,\n -.806488630034254E-01, 0.605968663231696E+00, -.292867504968554E+00, 0.892969489447894E-02,\n -.484459824754277E+00, -.372828295763188E+00, -.292867504968491E+00, 0.892969489447761E-02,\n 0.565108687757774E+00, -.233140367468673E+00, -.292867504968617E+00, 0.892969489447887E-02,\n 0.670560385399325E+00, -.853449033898829E-01, -.398619038406075E+00, 0.134935598366959E-02,\n -.261369338280503E+00, 0.623394780222222E+00, -.398619038406084E+00, 0.134935598366930E-02,\n -.409191047118684E+00, -.538049876832367E+00, -.398619038406107E+00, 0.134935598366793E-02,\n -.299491486116021E+00, 0.481774501202084E+00, -.276300502881569E+00, 0.531065986285393E-02,\n -.267483213878585E+00, -.500254485794690E+00, -.276300502881583E+00, 0.531065986285184E-02,\n 0.566974699994646E+00, 0.184799845924988E-01, -.276300502881531E+00, 0.531065986285218E-02,\n 0.451014797342889E-01, -.276848279538879E+00, -.317113237361796E-01, 0.167538404905949E-01,\n 0.217206903207561E+00, 0.177483166967532E+00, -.317113237361369E-01, 0.167538404905937E-01,\n -.262308382941846E+00, 0.993651125712726E-01, -.317113237361872E-01, 0.167538404905924E-01,\n -.249578549272405E+00, 0.384862064401038E+00, -.367007292465087E+00, 0.653851943197237E-02,\n -.208511050088074E+00, -.408572396110129E+00, -.367007292465082E+00, 0.653851943197069E-02,\n 0.458089599360516E+00, 0.237103317090649E-01, -.367007292465064E+00, 0.653851943197134E-02,\n 0.270750482848970E+00, 0.400432634198050E+00, -.391896680938777E+00, 0.390584400794776E-02,\n -.482160075144301E+00, 0.342604791349208E-01, -.391896680938754E+00, 0.390584400795171E-02,\n 0.211409592295448E+00, -.434693113333112E+00, -.391896680938769E+00, 0.390584400794846E-02,\n -.455428038451468E-01, 0.949665213040168E+00, -.394511292898214E+00, 0.126416696275215E-02,\n -.799662797660556E+00, -.514273831609544E+00, -.394511292898228E+00, 0.126416696275155E-02,\n 0.845205601505644E+00, -.435391381430545E+00, -.394511292898271E+00, 0.126416696275047E-02,\n 0.202967443013410E-01, 0.911716011790729E+00, -.168981382745051E+00, 0.196895355148754E-02,\n -.799717599398493E+00, -.438280509716333E+00, -.168981382745087E+00, 0.196895355148876E-02,\n 0.779420855097189E+00, -.473435502074434E+00, -.168981382745058E+00, 0.196895355148764E-02,\n 0.144175623644654E+00, 0.715286661071672E+00, -.198845636085639E+00, 0.425246913479433E-02,\n -.691544231298561E+00, -.232783577853110E+00, -.198845636085654E+00, 0.425246913479412E-02,\n 0.547368607654000E+00, -.482503083218601E+00, -.198845636085661E+00, 0.425246913479049E-02,\n 0.352817051875322E-01, 0.362038483159059E+00, -.358178896668777E+00, 0.950473780765503E-02,\n -.331175376157013E+00, -.150464388598384E+00, -.358178896668761E+00, 0.950473780765618E-02,\n 0.295893670969645E+00, -.211574094560774E+00, -.358178896668728E+00, 0.950473780765759E-02,\n -.782783570176244E-02, -.314187622250228E+00, -.265257062498191E+00, 0.144822041368009E-01,\n 0.276008380274198E+00, 0.150314706550668E+00, -.265257062498142E+00, 0.144822041368032E-01,\n -.268180544572431E+00, 0.163872915699448E+00, -.265257062498143E+00, 0.144822041368031E-01,\n 0.680665560696609E-01, 0.650432218392058E+00, 0.912765565119796E-01, 0.370575350803494E-02,\n -.597324102602245E+00, -.266268742491591E+00, 0.912765565119247E-01, 0.370575350803537E-02,\n 0.529257546532531E+00, -.384163475900498E+00, 0.912765565120003E-01, 0.370575350803248E-02,\n -.968506766523193E-01, -.204999708658188E+00, 0.471202702836115E+00, 0.102317707080299E-01,\n 0.225960293792512E+00, 0.186247079744668E-01, 0.471202702836177E+00, 0.102317707080322E-01,\n -.129109617140210E+00, 0.186375000683749E+00, 0.471202702836125E+00, 0.102317707080311E-01,\n -.100170803050395E-01, 0.655925920233165E+00, -.478910143480145E-01, 0.910628443182790E-02,\n -.563039969770092E+00, -.336638006132562E+00, -.478910143480221E-01, 0.910628443182588E-02,\n 0.573057050075142E+00, -.319287914100737E+00, -.478910143480866E-01, 0.910628443182793E-02,\n 0.346592027383442E-01, 0.185240882398687E+00, 0.556207159853704E+00, 0.100491352093832E-01,\n -.177752911345817E+00, -.626046911530188E-01, 0.556207159853647E+00, 0.100491352093899E-01,\n 0.143093708607631E+00, -.122636191245806E+00, 0.556207159853335E+00, 0.100491352093963E-01,\n 0.728526373455930E-01, 0.969327921121760E+00, -.366690241113186E+00, 0.121714286187474E-02,\n -.875888922961818E+00, -.421571725886872E+00, -.366690241113209E+00, 0.121714286187342E-02,\n 0.803036285616261E+00, -.547756195234916E+00, -.366690241113219E+00, 0.121714286187213E-02,\n 0.134338966391803E+00, -.475379303136392E+00, -.250008196830234E+00, 0.740968779705143E-02,\n 0.344521069753589E+00, 0.354030609181593E+00, -.250008196830256E+00, 0.740968779705232E-02,\n -.478860036145387E+00, 0.121348693954736E+00, -.250008196830276E+00, 0.740968779705109E-02,\n -.134832131321742E-01, -.125546521197851E+00, 0.795391078104131E+00, 0.452696575771365E-02,\n 0.115468083280197E+00, 0.510964555018097E-01, 0.795391078104172E+00, 0.452696575771131E-02,\n -.101984870147968E+00, 0.744500656960183E-01, 0.795391078104141E+00, 0.452696575771781E-02,\n -.517684899030174E-01, 0.304239398243767E+00, 0.124629565419234E+00, 0.186866632090050E-01,\n -.237594802759713E+00, -.196952526493478E+00, 0.124629565419238E+00, 0.186866632089992E-01,\n 0.289363292662701E+00, -.107286871750370E+00, 0.124629565419295E+00, 0.186866632090069E-01,\n 0.172920747285736E-01, 0.496851984411353E+00, 0.443078043912414E+00, 0.208819700591201E-02,\n -.438932477785245E+00, -.233450616206588E+00, 0.443078043912445E+00, 0.208819700590994E-02,\n 0.421640403056608E+00, -.263401368204719E+00, 0.443078043912564E+00, 0.208819700591018E-02,\n -.391479177516457E-02, 0.268959581722058E+00, -.178919068738941E+00, 0.176310626798592E-01,\n -.230968434474979E+00, -.137870099988916E+00, -.178919068738866E+00, 0.176310626798622E-01,\n 0.234883226250137E+00, -.131089481733252E+00, -.178919068738862E+00, 0.176310626798593E-01,\n -.688114413871859E+00, -.954115384882857E-01, -.362175327735890E+00, 0.201431501028147E-02,\n 0.426686023080969E+00, -.548218793879157E+00, -.362175327735869E+00, 0.201431501027980E-02,\n 0.261428390790936E+00, 0.643630332367427E+00, -.362175327735871E+00, 0.201431501028021E-02,\n 0.496097300628823E-02, 0.243946308989103E+00, 0.759020162517206E+00, 0.374440493250076E-02,\n -.213744187247167E+00, -.117676825843630E+00, 0.759020162517164E+00, 0.374440493250154E-02,\n 0.208783214240776E+00, -.126269483145421E+00, 0.759020162517327E+00, 0.374440493250375E-02,\n -.732500606524927E-01, 0.349382220565785E+00, 0.538509761972580E+00, 0.227479774987694E-02,\n -.265948848314349E+00, -.238127523636683E+00, 0.538509761972521E+00, 0.227479774987930E-02,\n 0.339198908966867E+00, -.111254696929119E+00, 0.538509761972401E+00, 0.227479774988148E-02,\n -.467850148968266E-01, 0.651738267999512E+00, -.403488986368024E+00, 0.241377177692592E-02,\n -.541029389257572E+00, -.366386145416827E+00, -.403488986367984E+00, 0.241377177692877E-02,\n 0.587814404154349E+00, -.285352122582576E+00, -.403488986368072E+00, 0.241377177692253E-02,\n -.250040572172371E-01, 0.743479306138410E+00, 0.912948005084153E-01, 0.190144783329074E-02,\n -.631369937695251E+00, -.393393801816990E+00, 0.912948005084432E-01, 0.190144783329102E-02,\n 0.656373994912421E+00, -.350085504321367E+00, 0.912948005085045E-01, 0.190144783329226E-02,\n 0.136419956819384E+00, 0.267208504565108E+00, 0.507647600801933E+00, 0.302173714299617E-02,\n -.299619331470269E+00, -.154611040937976E-01, 0.507647600802004E+00, 0.302173714299884E-02,\n 0.163199374650976E+00, -.251747400471351E+00, 0.507647600801948E+00, 0.302173714299261E-02,\n 0.119874370298418E-12, -.619596764254606E-13, 0.758768636091968E+00, 0.813775298509852E-02,\n -.766297986304656E-13, 0.300237038819369E-13, 0.117406440316567E+01, 0.233872708824947E-03,\n -.482966202439009E-14, -.545779497913239E-13, -.291758813125291E+00, 0.160331113356838E-01,\n -.211105082999440E-13, 0.116449404211565E-12, 0.407285051280602E+00, 0.132371678104456E-01,\n -.127067102529756E-13, 0.312328335528596E-13, -.273797565167698E-02, 0.243467656337569E-01 ];\n\n% NodeSet 14 177\nTN2012_14 = [ % 177*4\n -.575242283584180E+00, -.166133260583219E+00, -.300240841982295E+00, 0.407311106084951E-02,\n 0.431496765869180E+00, -.415107800624731E+00, -.300240841983309E+00, 0.407311106086412E-02,\n 0.143745517713982E+00, 0.581241061205346E+00, -.300240841983382E+00, 0.407311106089195E-02,\n -.330307698415517E+00, -.371209730161657E+00, -.236724353750048E+00, 0.631649202580972E-02,\n 0.486630905659552E+00, -.100449992815378E+00, -.236724353745667E+00, 0.631649202580268E-02,\n -.156323207242951E+00, 0.471659722975369E+00, -.236724353747098E+00, 0.631649202577768E-02,\n -.577016879846576E-02, 0.813563937154318E+00, -.112487413931976E-01, 0.146798867817842E-02,\n -.701681952778111E+00, -.411779081339492E+00, -.112487413914112E-01, 0.146798867823839E-02,\n 0.707452121577043E+00, -.401784855813232E+00, -.112487413918339E-01, 0.146798867814492E-02,\n -.303241671041222E+00, 0.445263691118857E+00, -.209120049193934E+00, 0.347291066290810E-02,\n -.233988832370200E+00, -.485246836167482E+00, -.209120049195121E+00, 0.347291066292713E-02,\n 0.537230503410457E+00, 0.399831450516860E-01, -.209120049194357E+00, 0.347291066293482E-02,\n 0.299584052599151E+00, 0.326484019886960E+00, -.387107016955792E+00, 0.327576451412751E-02,\n -.432535481452004E+00, 0.962053901756467E-01, -.387107016955722E+00, 0.327576451413050E-02,\n 0.132951428853400E+00, -.422689410063099E+00, -.387107016956188E+00, 0.327576451411143E-02,\n 0.231397850894255E+00, -.867100792961791E-01, 0.157675820557768E+00, 0.104553969408172E-01,\n -.406057940119166E-01, 0.243751456904555E+00, 0.157675820555718E+00, 0.104553969408347E-01,\n -.190792056880618E+00, -.157041377608727E+00, 0.157675820555330E+00, 0.104553969407382E-01,\n 0.119845996969304E+00, 0.564161674354201E+00, -.380499446663667E+00, 0.364986777096763E-02,\n -.548501340317717E+00, -.178291159259750E+00, -.380499446663128E+00, 0.364986777100916E-02,\n 0.428655343349320E+00, -.385870515093983E+00, -.380499446663405E+00, 0.364986777098790E-02,\n -.422306701845329E+00, 0.694637725684425E-02, -.256678512678140E+00, 0.806153706545878E-02,\n 0.205137611754242E+00, -.369201520613540E+00, -.256678512679293E+00, 0.806153706540727E-02,\n 0.217169090090457E+00, 0.362255143357407E+00, -.256678512678298E+00, 0.806153706547674E-02,\n -.199555205948733E+00, 0.500456231209974E+00, -.755044562352760E-02, 0.285738806924658E-02,\n -.333630206736558E+00, -.423047993414315E+00, -.755044562555918E-02, 0.285738806927622E-02,\n 0.533185412684041E+00, -.774082377944085E-01, -.755044562511435E-02, 0.285738806927797E-02,\n -.336236777595752E-02, 0.242407987544824E+00, 0.396668527152103E+00, 0.858697993389976E-02,\n -.208250291406449E+00, -.124115889683323E+00, 0.396668527146944E+00, 0.858697993385280E-02,\n 0.211612659183041E+00, -.118292097862163E+00, 0.396668527153668E+00, 0.858697993390625E-02,\n 0.390178919684306E+00, -.224793732281383E+00, 0.543629536874658E+00, 0.947585609194325E-03,\n -.412377074887698E-03, 0.450301722606289E+00, 0.543629536877204E+00, 0.947585609204924E-03,\n -.389766542603637E+00, -.225507990323973E+00, 0.543629536882427E+00, 0.947585609222194E-03,\n 0.544047552181209E-02, 0.651802390266920E+00, 0.210853397269185E+00, 0.194662998140932E-02,\n -.567197665975727E+00, -.321189605120733E+00, 0.210853397275583E+00, 0.194662998140232E-02,\n 0.561757190459366E+00, -.330612785144309E+00, 0.210853397266453E+00, 0.194662998141354E-02,\n 0.510990300967582E-01, 0.988055775141073E+00, -.384622763256674E+00, 0.941442850774455E-03,\n -.881230916676707E+00, -.449774829398800E+00, -.384622763256372E+00, 0.941442850786117E-03,\n 0.830131886579852E+00, -.538280945742860E+00, -.384622763257077E+00, 0.941442850768811E-03,\n -.333403339645188E+00, 0.248487410268569E+00, 0.432019915692715E-01, 0.189817372694094E-02,\n -.484947399918173E-01, -.412979466974262E+00, 0.432019915686436E-01, 0.189817372692919E-02,\n 0.381898079633772E+00, 0.164492056708287E+00, 0.432019915722213E-01, 0.189817372688908E-02,\n 0.296720921714769E+00, -.178610160343121E+00, -.394255226103660E+00, 0.358472221400519E-02,\n 0.632047537306693E-02, 0.346272936211606E+00, -.394255226103611E+00, 0.358472221400298E-02,\n -.303041397090647E+00, -.167662775869139E+00, -.394255226103512E+00, 0.358472221401662E-02,\n 0.394708154053029E+00, 0.115993706074013E+00, -.290082372165631E+00, 0.773951746082833E-02,\n -.297807573165452E+00, 0.283830435453547E+00, -.290082372165407E+00, 0.773951746077951E-02,\n -.969005808834108E-01, -.399824141528047E+00, -.290082372165008E+00, 0.773951746070415E-02,\n 0.460227742541093E+00, 0.332041729449580E-01, -.400195470090810E+00, 0.192176084759634E-02,\n -.258869528551988E+00, 0.381966830094237E+00, -.400195470090222E+00, 0.192176084765180E-02,\n -.201358213989841E+00, -.415171003039598E+00, -.400195470089365E+00, 0.192176084769918E-02,\n 0.432020401344211E+00, -.498688417766836E+00, -.251459996699954E+00, 0.359141808167828E-02,\n 0.215866637686716E+00, 0.623484851400748E+00, -.251459996700175E+00, 0.359141808170410E-02,\n -.647887039030433E+00, -.124796433632328E+00, -.251459996700565E+00, 0.359141808169343E-02,\n 0.324350258804347E-02, 0.939598309554684E+00, -.205299346524922E+00, 0.163835774237929E-02,\n -.815337756722135E+00, -.466990199139287E+00, -.205299346526383E+00, 0.163835774238299E-02,\n 0.812094254131555E+00, -.472608110414891E+00, -.205299346522325E+00, 0.163835774239529E-02,\n -.292963974805897E+00, 0.123680175760901E+00, 0.294659474040601E+00, 0.372396860339681E-02,\n 0.393718132485005E-01, -.315554332455396E+00, 0.294659474041647E+00, 0.372396860343135E-02,\n 0.253592161555488E+00, 0.191874156694664E+00, 0.294659474042561E+00, 0.372396860340175E-02,\n -.291171236420790E+00, -.345588148418140E+00, -.579522686235738E-01, 0.986772173845936E-02,\n 0.444873733985901E+00, -.793676133807912E-01, -.579522686212165E-01, 0.986772173839348E-02,\n -.153702497567287E+00, 0.424955761799258E+00, -.579522686218909E-01, 0.986772173843421E-02,\n 0.377057762840246E+00, 0.309639391945564E+00, -.221215714449003E+00, 0.511418213201809E-02,\n -.456684460855543E+00, 0.171721905344289E+00, -.221215714449280E+00, 0.511418213203137E-02,\n 0.796266980160928E-01, -.481361297286375E+00, -.221215714448616E+00, 0.511418213204769E-02,\n -.734356843870207E-03, 0.698468651280787E-01, 0.103191504161762E+01, 0.148408055902508E-02,\n -.601219811521234E-01, -.355594042455063E-01, 0.103191504162137E+01, 0.148408055898773E-02,\n 0.608563379984996E-01, -.342874608822615E-01, 0.103191504161585E+01, 0.148408055903742E-02,\n -.786061244475154E+00, -.362810988466514E+00, -.284366470168081E+00, 0.289589802390020E-02,\n 0.707234155023705E+00, -.499343512413032E+00, -.284366470169136E+00, 0.289589802389795E-02,\n 0.788270894528871E-01, 0.862154500880184E+00, -.284366470168453E+00, 0.289589802389629E-02,\n -.179807943025799E+00, 0.763907312527733E+00, -.391663270955190E+00, 0.142400302631111E-02,\n -.571659167272307E+00, -.537671902726336E+00, -.391663270955074E+00, 0.142400302631816E-02,\n 0.751467110298568E+00, -.226235409801304E+00, -.391663270955000E+00, 0.142400302631990E-02,\n 0.234912174928423E-01, 0.330303232304993E+00, -.585340450356535E-01, 0.141866307556572E-01,\n -.297796598875667E+00, -.144807625037826E+00, -.585340450333672E-01, 0.141866307556615E-01,\n 0.274305381381167E+00, -.185495607266993E+00, -.585340450347141E-01, 0.141866307557038E-01,\n -.350818590031590E+00, -.208653955178107E+00, 0.434903259331463E+00, 0.539971419326250E-02,\n 0.356108920801636E+00, -.199490833498607E+00, 0.434903259331847E+00, 0.539971419319880E-02,\n -.529033076836162E-02, 0.408144788676786E+00, 0.434903259332148E+00, 0.539971419323761E-02,\n -.479999707057395E+00, -.102130793619860E+00, -.716646932020444E-01, 0.946900966745673E-02,\n 0.328447715310549E+00, -.364626543310714E+00, -.716646932031980E-01, 0.946900966753316E-02,\n 0.151551991745061E+00, 0.466757336930631E+00, -.716646932016664E-01, 0.946900966753050E-02,\n 0.550374936239566E+00, -.174924988222624E+00, -.365102007850781E+00, 0.514867007981190E-02,\n -.123697984561225E+00, 0.564101170503260E+00, -.365102007850920E+00, 0.514867007976846E-02,\n -.426676951679799E+00, -.389176182278205E+00, -.365102007851096E+00, 0.514867007970910E-02,\n -.116091399601824E+00, -.736998279723331E-01, 0.666674160835910E+00, 0.692917641087077E-02,\n 0.121871623076646E+00, -.636881872281037E-01, 0.666674160842752E+00, 0.692917641083534E-02,\n -.578022347846076E-02, 0.137388015200055E+00, 0.666674160841551E+00, 0.692917641083512E-02,\n -.179596619245613E+00, 0.689296401321286E+00, -.285060798024655E+00, 0.384786348087887E-02,\n -.507149884659416E+00, -.500183435361117E+00, -.285060798024677E+00, 0.384786348087703E-02,\n 0.686746503903723E+00, -.189112965959864E+00, -.285060798023968E+00, 0.384786348091793E-02,\n -.473131159616946E-02, 0.798252844734476E+00, -.376713904904150E+00, 0.341675933601673E-02,\n -.688941586384925E+00, -.403223858402992E+00, -.376713904904145E+00, 0.341675933602221E-02,\n 0.693672897981391E+00, -.395028986330868E+00, -.376713904904146E+00, 0.341675933602166E-02,\n 0.183801975582644E+00, 0.750015934305411E+00, -.384732311329371E+00, 0.185506742588904E-02,\n -.741433840143401E+00, -.215830787033148E+00, -.384732311329466E+00, 0.185506742588527E-02,\n 0.557631864560502E+00, -.534185147273039E+00, -.384732311329474E+00, 0.185506742588539E-02,\n -.315748277890409E+00, 0.168599598023018E+00, -.143071179101490E-01, 0.108203755560910E-01,\n 0.118626039881620E-01, -.357745828865578E+00, -.143071179097027E-01, 0.108203755561398E-01,\n 0.303885673901511E+00, 0.189146230843338E+00, -.143071179104198E-01, 0.108203755560971E-01,\n -.376015684493240E+00, -.754120415611064E-01, 0.222689343484614E+00, 0.906808701359823E-02,\n 0.253316585990410E+00, -.287933114212501E+00, 0.222689343484401E+00, 0.906808701356199E-02,\n 0.122699098503781E+00, 0.363345155772191E+00, 0.222689343484860E+00, 0.906808701357411E-02,\n 0.313284788743724E-01, -.199122996930348E+00, 0.186136871843591E+00, 0.138609762453174E-01,\n 0.156781334383015E+00, 0.126692757030961E+00, 0.186136871841625E+00, 0.138609762453567E-01,\n -.188109813255554E+00, 0.724302398995938E-01, 0.186136871843113E+00, 0.138609762453960E-01,\n -.594039828858582E+00, -.438423888774048E+00, -.107279562274995E+00, 0.456878927721502E-02,\n 0.676706139733047E+00, -.295241638264149E+00, -.107279562274549E+00, 0.456878927727467E-02,\n -.826663108750434E-01, 0.733665527037704E+00, -.107279562274855E+00, 0.456878927726143E-02,\n 0.579906374949189E+00, -.424363651310160E+00, -.648551694854795E-01, 0.464900158014659E-02,\n 0.775565150022491E-01, 0.714395478178690E+00, -.648551694856163E-01, 0.464900158010975E-02,\n -.657462889952257E+00, -.290031826867551E+00, -.648551694856968E-01, 0.464900158010665E-02,\n 0.195928853192363E+00, -.216361578531986E+00, 0.572562269345945E+00, 0.326622940781702E-02,\n 0.894101968154995E-01, 0.277860153464154E+00, 0.572562269347270E+00, 0.326622940780099E-02,\n -.285339050008115E+00, -.614985749335604E-01, 0.572562269346011E+00, 0.326622940781070E-02,\n 0.293847693490531E+00, -.171985278472679E+00, -.279108711226420E+00, 0.124729622108709E-01,\n 0.201977348840127E-02, 0.340472206642557E+00, -.279108711226616E+00, 0.124729622108673E-01,\n -.295867466979937E+00, -.168486928169786E+00, -.279108711225454E+00, 0.124729622109326E-01,\n 0.365502052532130E+00, 0.437394577048286E+00, -.371415437111150E+00, 0.267294138131050E-02,\n -.561545841467734E+00, 0.978367741037638E-01, -.371415437111249E+00, 0.267294138129828E-02,\n 0.196043788935523E+00, -.535231351152352E+00, -.371415437111085E+00, 0.267294138131039E-02,\n -.570659524572094E-01, 0.923818279609940E+00, -.316173841712837E+00, 0.247104884668795E-02,\n -.771517122393903E+00, -.511329704323859E+00, -.316173841712279E+00, 0.247104884666643E-02,\n 0.828583074852206E+00, -.412488575286835E+00, -.316173841713480E+00, 0.247104884669676E-02,\n 0.101152805721060E+00, 0.630551067591309E-01, 0.837327710042496E+00, 0.296404318850117E-02,\n -.105183727153304E+00, 0.560733460392890E-01, 0.837327710042566E+00, 0.296404318841329E-02,\n 0.403092143123203E-02, -.119128452798902E+00, 0.837327710042031E+00, 0.296404318845359E-02,\n -.212419725843974E+00, -.293637332571483E+00, 0.249887391854507E+00, 0.860843027377963E-02,\n 0.360507252427238E+00, -.371422125585314E-01, 0.249887391855293E+00, 0.860843027375037E-02,\n -.148087526584551E+00, 0.330779545130526E+00, 0.249887391855666E+00, 0.860843027377383E-02,\n -.165178219962910E+00, 0.862687098105019E-01, 0.510890414043656E+00, 0.876808189201044E-02,\n 0.787821573356979E-02, -.186182889544598E+00, 0.510890414043511E+00, 0.876808189200772E-02,\n 0.157300004228448E+00, 0.999141797342290E-01, 0.510890414043504E+00, 0.876808189201718E-02,\n -.361792752561076E+00, 0.440883726379541E+00, -.370614775674016E+00, 0.290438401248579E-02,\n -.200920130878983E+00, -.533763577812893E+00, -.370614775674052E+00, 0.290438401246964E-02,\n 0.562712883440469E+00, 0.928798514331573E-01, -.370614775674048E+00, 0.290438401247830E-02,\n -.501582060028134E+00, -.189017523532352E+00, 0.243300456027558E+00, 0.214700460048371E-02,\n 0.414485007154890E+00, -.339874044299363E+00, 0.243300456030077E+00, 0.214700460050576E-02,\n 0.870970528739568E-01, 0.528891567831824E+00, 0.243300456029155E+00, 0.214700460053189E-02,\n 0.943406837211783E+00, -.549830207760000E+00, -.353870254501487E+00, 0.288727982779534E-03,\n 0.446350908212159E-02, 0.109192939101015E+01, -.353870254502128E+00, 0.288727982772595E-03,\n -.947870346296031E+00, -.542099183250677E+00, -.353870254502452E+00, 0.288727982759760E-03,\n 0.200575172082975E+00, 0.108858729355023E+00, -.358265174400078E+00, 0.890647160456436E-02,\n -.194562011087352E+00, 0.119273829713901E+00, -.358265174399951E+00, 0.890647160456416E-02,\n -.601316099752385E-02, -.228132559069674E+00, -.358265174400086E+00, 0.890647160457989E-02,\n -.125565833845857E-01, 0.546993463921740E+00, 0.875506297144548E-01, 0.949936126258408E-02,\n -.467431943769019E+00, -.284371052157281E+00, 0.875506297145599E-01, 0.949936126256084E-02,\n 0.479988527151917E+00, -.262622411764873E+00, 0.875506297137920E-01, 0.949936126260162E-02,\n -.171690873716897E-01, -.216015130934396E+00, -.139730799812637E+00, 0.168769172486876E-01,\n 0.195659134676586E+00, 0.931386996440844E-01, -.139730799812326E+00, 0.168769172486957E-01,\n -.178490047305620E+00, 0.122876431289901E+00, -.139730799812474E+00, 0.168769172486963E-01,\n -.546275791578987E-03, 0.667828701294578E+00, -.218376112477418E+00, 0.948331095626193E-02,\n -.578083482801784E+00, -.334387439360658E+00, -.218376112477213E+00, 0.948331095626163E-02,\n 0.578629758593253E+00, -.333441261934690E+00, -.218376112477671E+00, 0.948331095627096E-02,\n -.183387701321059E+00, -.219539988831699E+00, 0.576350781636215E+00, 0.291801565831253E-02,\n 0.281821058134979E+00, -.490484136690603E-01, 0.576350781636874E+00, 0.291801565829244E-02,\n -.984333568143726E-01, 0.268588402501900E+00, 0.576350781636510E+00, 0.291801565827458E-02,\n 0.191661789507546E+00, -.109745450674066E+00, 0.806220842543315E+00, 0.270440540659129E-02,\n -.788546520336479E-03, 0.220856703983877E+00, 0.806220842545406E+00, 0.270440540658569E-02,\n -.190873242983517E+00, -.111111253309189E+00, 0.806220842548502E+00, 0.270440540661825E-02,\n -.481389123117500E-01, 0.102301268899185E+01, -.404965878434928E+00, 0.364445038290711E-03,\n -.861885520903912E+00, -.553195865468262E+00, -.404965878433795E+00, 0.364445038304032E-03,\n 0.910024433217974E+00, -.469816823523960E+00, -.404965878436118E+00, 0.364445038271510E-03,\n -.442446287170860E+00, -.348710568478134E+00, 0.222570681379663E+00, 0.212760250081768E-02,\n 0.523215354454083E+00, -.208814440260071E+00, 0.222570681379047E+00, 0.212760250089270E-02,\n -.807690672840585E-01, 0.557525008738729E+00, 0.222570681380127E+00, 0.212760250085897E-02,\n 0.233016466910397E+00, 0.458660430488394E+00, -.409672523946633E-02, 0.245758502593965E-02,\n -.513719817967670E+00, -.275320353974866E-01, -.409672524092190E-02, 0.245758502598051E-02,\n 0.280703351056490E+00, -.431128395087878E+00, -.409672523825050E-02, 0.245758502598958E-02,\n 0.396708065400329E-12, 0.142484953050341E-12, -.259244781008597E+00, 0.140379841702619E-01,\n 0.172242545847118E-11, 0.416320752022618E-12, 0.119114912174165E+01, 0.125045207771754E-03,\n 0.350241037314071E-12, 0.256440763467915E-12, 0.412065312751145E+00, 0.152916747668899E-01,\n -.294794246186653E-11, -.948925382567767E-12, 0.843526260134419E+00, 0.448751025261868E-02,\n -.103209102664440E-11, 0.572570760190481E-12, -.400363967338670E+00, 0.271147435356790E-02,\n -.435939356582035E-12, -.430785817780272E-12, 0.332100254506089E-01, 0.179783863072324E-01 ];\n\n% NodeSet 15 214\nTN2012_15 = [ % 214*4\n 0.258152119478843E+00, 0.304175382366057E+00, 0.114941536929827E+00, 0.249094171140855E-02,\n -.392499668074282E+00, 0.714786023264670E-01, 0.114941536929798E+00, 0.249094171140690E-02,\n 0.134347548595462E+00, -.375653984692530E+00, 0.114941536929772E+00, 0.249094171140722E-02,\n 0.174793662760004E+00, 0.343502512582010E+00, -.142514196488796E+00, 0.652868546942704E-02,\n -.384878733539857E+00, -.203755039203169E-01, -.142514196488753E+00, 0.652868546942395E-02,\n 0.210085070779848E+00, -.323127008661698E+00, -.142514196488787E+00, 0.652868546942618E-02,\n -.268615838548664E+00, -.209746805323262E+00, -.389739165020216E+00, 0.299603045409476E-02,\n 0.315953981046930E+00, -.127754737380383E+00, -.389739165020212E+00, 0.299603045409517E-02,\n -.473381424982375E-01, 0.337501542703614E+00, -.389739165020218E+00, 0.299603045409458E-02,\n 0.535680841576558E-02, 0.968947530543105E-01, 0.742528316718603E+00, 0.431794709527661E-02,\n -.865917218463591E-01, -.438082443558939E-01, 0.742528316718619E+00, 0.431794709527601E-02,\n 0.812349134305405E-01, -.530865086984093E-01, 0.742528316718614E+00, 0.431794709527687E-02,\n -.814463113484512E+00, -.507805620316222E+00, -.285611224208266E+00, 0.115071789816229E-02,\n 0.847004124120622E+00, -.451442936564845E+00, -.285611224208270E+00, 0.115071789816230E-02,\n -.325410106361014E-01, 0.959248556881068E+00, -.285611224208257E+00, 0.115071789816246E-02,\n 0.224935844193548E+00, 0.715768558382950E+00, -.389186754644429E+00, 0.812146724356807E-03,\n -.732341676886575E+00, -.163084123898153E+00, -.389186754644439E+00, 0.812146724356529E-03,\n 0.507405832693028E+00, -.552684434484796E+00, -.389186754644434E+00, 0.812146724356482E-03,\n -.547357038434130E+00, -.243235419738212E+00, 0.184732558232411E+00, 0.181330436451233E-02,\n 0.484326571810546E+00, -.352407390355058E+00, 0.184732558232403E+00, 0.181330436451273E-02,\n 0.630304666235898E-01, 0.595642810093306E+00, 0.184732558232408E+00, 0.181330436451180E-02,\n -.237879144231129E-01, 0.246550698911715E+00, 0.580270468252207E+00, 0.414087152453678E-02,\n -.201625211366817E+00, -.143876287649317E+00, 0.580270468252226E+00, 0.414087152453607E-02,\n 0.225413125789895E+00, -.102674411262402E+00, 0.580270468252234E+00, 0.414087152453595E-02,\n -.739187181924076E-01, -.547727077011690E+00, -.391441391104918E+00, 0.100666812186601E-02,\n 0.511304922128929E+00, 0.209848050736021E+00, -.391441391104914E+00, 0.100666812186624E-02,\n -.437386203936511E+00, 0.337879026275675E+00, -.391441391104921E+00, 0.100666812186573E-02,\n -.296800453069907E+00, 0.321721626441848E-01, 0.406150067393071E+00, 0.281295627235464E-02,\n 0.120538316390380E+00, -.273122813535342E+00, 0.406150067393110E+00, 0.281295627235580E-02,\n 0.176262136679499E+00, 0.240950650891170E+00, 0.406150067393085E+00, 0.281295627235510E-02,\n -.424109825534735E-02, 0.416431076208372E+00, 0.580863239140085E+00, 0.964358972918426E-03,\n -.358519341794062E+00, -.211888436933256E+00, 0.580863239140087E+00, 0.964358972918691E-03,\n 0.362760440049413E+00, -.204542639275101E+00, 0.580863239140103E+00, 0.964358972918272E-03,\n 0.420238636403193E-02, -.208941903277785E-01, 0.112230077847980E+01, 0.288213892537120E-03,\n 0.159937064333278E-01, 0.140864685116470E-01, 0.112230077847979E+01, 0.288213892537525E-03,\n -.201960927973878E-01, 0.680772181611991E-02, 0.112230077847980E+01, 0.288213892536919E-03,\n -.538855127386786E-01, 0.841520524077910E+00, -.170238260141001E+00, 0.202238868092459E-02,\n -.701835395288124E+00, -.467426484966598E+00, -.170238260140992E+00, 0.202238868092480E-02,\n 0.755720908026795E+00, -.374094039111304E+00, -.170238260140987E+00, 0.202238868092491E-02,\n 0.364602780629829E-01, 0.711452204819021E+00, -.292851721446071E-01, 0.342986352626608E-02,\n -.634365821983225E+00, -.324150575377920E+00, -.292851721446072E-01, 0.342986352626522E-02,\n 0.597905543920261E+00, -.387301629441103E+00, -.292851721446004E-01, 0.342986352626463E-02,\n 0.125850346682288E-01, -.283649922521734E+00, -.237863927191367E-01, 0.956695562971094E-02,\n 0.239355521351163E+00, 0.152723920991028E+00, -.237863927191305E-01, 0.956695562971296E-02,\n -.251940556019402E+00, 0.130926001530681E+00, -.237863927191544E-01, 0.956695562971111E-02,\n 0.385162531779287E-02, -.179377244818765E+00, -.387600248278067E+00, 0.433604548796903E-02,\n 0.153419438215009E+00, 0.930242277804360E-01, -.387600248278066E+00, 0.433604548796935E-02,\n -.157271063532833E+00, 0.863530170383109E-01, -.387600248278063E+00, 0.433604548796941E-02,\n -.348530140993749E-02, -.185028244536387E+00, -.157327640046718E+00, 0.103356064299359E-01,\n 0.161981810891139E+00, 0.894957627073358E-01, -.157327640046750E+00, 0.103356064299294E-01,\n -.158496509481226E+00, 0.955324818290217E-01, -.157327640046750E+00, 0.103356064299327E-01,\n 0.530463511464713E-01, -.440073176598083E+00, -.984667765940366E-01, 0.423558626963751E-02,\n 0.354591374884810E+00, 0.265976075969954E+00, -.984667765940141E-01, 0.423558626963793E-02,\n -.407637726031304E+00, 0.174097100628107E+00, -.984667765940299E-01, 0.423558626963730E-02,\n 0.665392854648627E-01, 0.239078964888139E+00, 0.419574950888795E+00, 0.681046506781639E-02,\n -.240318099836065E+00, -.619147708818347E-01, 0.419574950888812E+00, 0.681046506781542E-02,\n 0.173778814371207E+00, -.177164194006293E+00, 0.419574950888816E+00, 0.681046506781649E-02,\n -.166734893106253E+00, 0.409621014869640E+00, 0.169870647828065E+00, 0.397039820954813E-02,\n -.271374758247967E+00, -.349207160562124E+00, 0.169870647828042E+00, 0.397039820954811E-02,\n 0.438109651354205E+00, -.604138543075271E-01, 0.169870647828062E+00, 0.397039820954754E-02,\n 0.949353282231965E-01, -.569687711930257E-01, 0.100104563339689E+01, 0.808994059895755E-03,\n 0.186873896394871E-02, 0.110700791554415E+00, 0.100104563339690E+01, 0.808994059895714E-03,\n -.968040671871328E-01, -.537320203613814E-01, 0.100104563339690E+01, 0.808994059895808E-03,\n -.510598172246801E-01, -.345927815689831E+00, 0.127825298661453E+00, 0.552735908612229E-02,\n 0.325112184875413E+00, 0.128744809015723E+00, 0.127825298661432E+00, 0.552735908612158E-02,\n -.274052367650716E+00, 0.217183006674084E+00, 0.127825298661416E+00, 0.552735908612256E-02,\n -.208024528677348E-01, 0.184883929787422E+00, 0.669985129294430E-01, 0.115934884219135E-01,\n -.149712953513427E+00, -.110457417538084E+00, 0.669985129295205E-01, 0.115934884219225E-01,\n 0.170515406381284E+00, -.744265122493089E-01, 0.669985129294305E-01, 0.115934884219135E-01,\n 0.292178123870944E+00, -.328160490412648E+00, 0.188860305200578E+00, 0.475283519793602E-02,\n 0.138106259280221E+00, 0.417113922908688E+00, 0.188860305200536E+00, 0.475283519793658E-02,\n -.430284383151197E+00, -.889534324959835E-01, 0.188860305200515E+00, 0.475283519793719E-02,\n -.878090582800034E-01, -.257954966189383E+00, 0.416231911745254E+00, 0.442753455264511E-02,\n 0.267300082892351E+00, 0.529326079418328E-01, 0.416231911745271E+00, 0.442753455264529E-02,\n -.179491024612372E+00, 0.205022358247536E+00, 0.416231911745261E+00, 0.442753455264571E-02,\n -.194458745679973E-01, 0.337200394761511E+00, -.142937741910735E+00, 0.108023951109223E-01,\n -.282301170745611E+00, -.185440818755414E+00, -.142937741910703E+00, 0.108023951109241E-01,\n 0.301747045313629E+00, -.151759576006076E+00, -.142937741910730E+00, 0.108023951109209E-01,\n -.731343132041161E-01, 0.646898497210061E+00, 0.752675747660435E-01, 0.285875163245338E-02,\n -.523663375651827E+00, -.386785421728115E+00, 0.752675747660487E-01, 0.285875163245380E-02,\n 0.596797688855938E+00, -.260113075481936E+00, 0.752675747660478E-01, 0.285875163245399E-02,\n -.376250705244884E+00, -.114322556557385E+00, 0.550225974563751E-01, 0.869361992936774E-02,\n 0.287131590826730E+00, -.268681390655231E+00, 0.550225974563902E-01, 0.869361992936585E-02,\n 0.891191144181605E-01, 0.383003947212582E+00, 0.550225974563760E-01, 0.869361992936762E-02,\n -.379789627183864E-01, 0.558964475667290E+00, -.378364573029073E+00, 0.383799020167440E-02,\n -.465087954381758E+00, -.312372984357168E+00, -.378364573029073E+00, 0.383799020167453E-02,\n 0.503066917100135E+00, -.246591491310175E+00, -.378364573029073E+00, 0.383799020167383E-02,\n 0.275055549348987E-02, 0.838751807936127E+00, -.355785818698930E-01, 0.139738389542722E-02,\n -.727755650889547E+00, -.416993853036175E+00, -.355785818698781E-01, 0.139738389542723E-02,\n 0.725005095396073E+00, -.421757954899949E+00, -.355785818698916E-01, 0.139738389542685E-02,\n 0.612300613856560E+00, -.215796645511508E+00, -.118009477093553E+00, 0.489300425975968E-02,\n -.119264929863829E+00, 0.638166209108364E+00, -.118009477093543E+00, 0.489300425975965E-02,\n -.493035683992722E+00, -.422369563596831E+00, -.118009477093543E+00, 0.489300425975971E-02,\n -.264572722008943E+00, 0.352599331047574E+00, -.163748002755720E+00, 0.739653306113128E-02,\n -.173073617040117E+00, -.405426363931915E+00, -.163748002755722E+00, 0.739653306113081E-02,\n 0.437646339049050E+00, 0.528270328843696E-01, -.163748002755714E+00, 0.739653306113117E-02,\n -.663096245113129E-01, 0.241883469905418E+00, 0.297745486047570E+00, 0.102352430507446E-01,\n -.176322417437979E+00, -.178367554294907E+00, 0.297745486047582E+00, 0.102352430507444E-01,\n 0.242632041949263E+00, -.635159156104787E-01, 0.297745486047567E+00, 0.102352430507450E-01,\n -.420038409319059E-02, 0.628132240414236E+00, 0.259671260459846E+00, 0.169108162235348E-02,\n -.541878285088164E+00, -.317703759537470E+00, 0.259671260459853E+00, 0.169108162235353E-02,\n 0.546078669181359E+00, -.310428480876762E+00, 0.259671260459848E+00, 0.169108162235344E-02,\n 0.539466322852269E-01, -.205235432096071E+00, 0.227150892695586E+00, 0.106870368988479E-01,\n 0.150765781809271E+00, 0.149336870055697E+00, 0.227150892695555E+00, 0.106870368988450E-01,\n -.204712414094495E+00, 0.558985620404097E-01, 0.227150892695570E+00, 0.106870368988473E-01,\n 0.101817142699943E+00, 0.564065898953328E+00, -.277992617897413E+00, 0.672536035459299E-02,\n -.539403969252066E+00, -.193856717357776E+00, -.277992617897385E+00, 0.672536035459384E-02,\n 0.437586826552127E+00, -.370209181595563E+00, -.277992617897412E+00, 0.672536035459328E-02,\n 0.124551330130348E+00, 0.673513833840005E+00, -.382343277722446E+00, 0.285456723044317E-02,\n -.645555754970877E+00, -.228892300951980E+00, -.382343277722440E+00, 0.285456723044365E-02,\n 0.521004424840520E+00, -.444621532888043E+00, -.382343277722447E+00, 0.285456723044297E-02,\n -.985592955579921E-01, 0.919835388841061E+00, -.377538632244491E+00, 0.106650111993310E-02,\n -.747321166257303E+00, -.545272548152855E+00, -.377538632244493E+00, 0.106650111993292E-02,\n 0.845880461815294E+00, -.374562840688214E+00, -.377538632244494E+00, 0.106650111993302E-02,\n -.175538802028308E+00, 0.715516618290424E+00, -.282968862701148E+00, 0.278412463006544E-02,\n -.531886167255290E+00, -.509779371051619E+00, -.282968862701149E+00, 0.278412463006510E-02,\n 0.707424969283603E+00, -.205737247238819E+00, -.282968862701154E+00, 0.278412463006522E-02,\n -.626762915722012E-02, -.729636607140934E-01, 0.926665990273565E+00, 0.255134087803697E-02,\n 0.663221983101268E-01, 0.310539042853938E-01, 0.926665990273561E+00, 0.255134087803699E-02,\n -.600545691528989E-01, 0.419097564287068E-01, 0.926665990273564E+00, 0.255134087803706E-02,\n -.202338110826756E+00, -.956595869654207E-02, 0.704240870816491E+00, 0.237978659265236E-02,\n 0.109453418656134E+00, -.170446964781441E+00, 0.704240870816488E+00, 0.237978659265308E-02,\n 0.928846921706177E-01, 0.180012923477980E+00, 0.704240870816478E+00, 0.237978659265341E-02,\n -.647349974357924E-01, 0.410863325711682E+00, 0.411688404749235E+00, 0.367154580391546E-02,\n -.323450578831780E+00, -.261493815149158E+00, 0.411688404749230E+00, 0.367154580391558E-02,\n 0.388185576267567E+00, -.149369510562525E+00, 0.411688404749235E+00, 0.367154580391620E-02,\n -.123302554542721E+00, 0.401932094350526E+00, 0.119096478781894E-01, 0.943568869218895E-02,\n -.286432127032441E+00, -.307749191760741E+00, 0.119096478782083E-01, 0.943568869219145E-02,\n 0.409734681575188E+00, -.941829025897397E-01, 0.119096478781972E-01, 0.943568869218898E-02,\n 0.198964891452639E+00, 0.504535085060002E+00, -.982488629629035E-01, 0.567510405577512E-02,\n -.536422646488850E+00, -.799588920708283E-01, -.982488629629094E-01, 0.567510405577412E-02,\n 0.337457755036191E+00, -.424576192989211E+00, -.982488629629237E-01, 0.567510405577405E-02,\n 0.217899163019504E-01, 0.613986541715491E+00, -.121007693279375E+00, 0.757232155064711E-02,\n -.542622900858349E+00, -.288122649793941E+00, -.121007693279352E+00, 0.757232155064673E-02,\n 0.520832984556400E+00, -.325863891921567E+00, -.121007693279350E+00, 0.757232155064802E-02,\n -.201452305982941E+00, 0.241132309402656E+00, -.297032331707505E+00, 0.926123494364474E-02,\n -.108100552624428E+00, -.295028969333504E+00, -.297032331707505E+00, 0.926123494364532E-02,\n 0.309552858607363E+00, 0.538966599308800E-01, -.297032331707501E+00, 0.926123494364516E-02,\n -.116956783563120E-01, -.138782984589614E+00, 0.582806521460454E+00, 0.628310692395311E-02,\n 0.126037429445771E+00, 0.592627377237619E-01, 0.582806521460435E+00, 0.628310692395284E-02,\n -.114341751089492E+00, 0.795202468658380E-01, 0.582806521460469E+00, 0.628310692395237E-02,\n 0.682968101095060E-01, 0.295112105963141E+00, -.301787657090746E+00, 0.950431568825956E-02,\n -.289722985783184E+00, -.884092804293167E-01, -.301787657090743E+00, 0.950431568825956E-02,\n 0.221426175673652E+00, -.206702825533833E+00, -.301787657090740E+00, 0.950431568826002E-02,\n -.429817500306839E+00, 0.445269831351928E-02, -.386224427799053E+00, 0.402949656022401E-02,\n 0.211052600298496E+00, -.374459223413599E+00, -.386224427799051E+00, 0.402949656022447E-02,\n 0.218764900008327E+00, 0.370006525100060E+00, -.386224427799052E+00, 0.402949656022438E-02,\n 0.657830714907697E+00, -.170942391383753E+00, -.380434630448314E+00, 0.272052467007333E-02,\n -.180874903931861E+00, 0.655169306191617E+00, -.380434630448313E+00, 0.272052467007334E-02,\n -.476955810975839E+00, -.484226914807891E+00, -.380434630448313E+00, 0.272052467007346E-02,\n -.370463073663661E+00, -.156950196432308E+00, 0.461451866783806E+00, 0.337227207067558E-02,\n 0.321154394071181E+00, -.242355334740639E+00, 0.461451866783823E+00, 0.337227207067548E-02,\n 0.493086795924882E-01, 0.399305531172947E+00, 0.461451866783816E+00, 0.337227207067610E-02,\n -.119300551780856E+00, 0.530641871747840E+00, -.266456779653053E+00, 0.791030849914603E-02,\n -.399899065354920E+00, -.368638244401638E+00, -.266456779653046E+00, 0.791030849914697E-02,\n 0.519199617135777E+00, -.162003627346192E+00, -.266456779653057E+00, 0.791030849914647E-02,\n -.150452055510191E+00, -.428194345553231E+00, -.383444021066624E+00, 0.398525303397504E-02,\n 0.446053208761040E+00, 0.838018706532008E-01, -.383444021066623E+00, 0.398525303397513E-02,\n -.295601153250867E+00, 0.344392474900012E+00, -.383444021066624E+00, 0.398525303397507E-02,\n 0.197583005475362E+00, 0.660682468125869E+00, -.280966074583490E+00, 0.356670706908016E-02,\n -.670959303969691E+00, -.159229331965177E+00, -.280966074583505E+00, 0.356670706907958E-02,\n 0.473376298494327E+00, -.501453136160682E+00, -.280966074583498E+00, 0.356670706907986E-02,\n -.746313738874201E-02, 0.490647384618176E+00, 0.184322542332287E+00, 0.717150418477603E-02,\n -.421181530685369E+00, -.251786958879662E+00, 0.184322542332289E+00, 0.717150418477588E-02,\n 0.428644668074081E+00, -.238860425738493E+00, 0.184322542332287E+00, 0.717150418477665E-02,\n 0.204947320088601E-02, 0.232828740261373E+00, 0.794993174564848E+00, 0.189617098059473E-02,\n -.202660340397914E+00, -.114639474274342E+00, 0.794993174564868E+00, 0.189617098059435E-02,\n 0.200610867197031E+00, -.118189265987027E+00, 0.794993174564855E+00, 0.189617098059462E-02,\n 0.715208601019793E-01, 0.842335952518595E+00, -.229601950404950E+00, 0.287078796909986E-02,\n -.765244763453047E+00, -.359229094510459E+00, -.229601950404950E+00, 0.287078796910012E-02,\n 0.693723903351066E+00, -.483106858008123E+00, -.229601950404941E+00, 0.287078796909986E-02,\n 0.216683910538321E+00, -.524509738082016E+00, -.376887329718436E+00, 0.235922503173230E-02,\n 0.345896802442191E+00, 0.449908640158552E+00, -.376887329718438E+00, 0.235922503173207E-02,\n -.562580712980498E+00, 0.746010979234869E-01, -.376887329718435E+00, 0.235922503173239E-02,\n 0.127985393998401E+00, -.429747975001943E+00, -.277974239042955E+00, 0.761112189683938E-02,\n 0.308179966577416E+00, 0.325712590016963E+00, -.277974239042960E+00, 0.761112189683879E-02,\n -.436165360575796E+00, 0.104035384984987E+00, -.277974239042955E+00, 0.761112189683944E-02,\n -.157781237450556E-01, 0.800916121480509E+00, -.308819906524061E+00, 0.464793323114600E-02,\n -.685724645630099E+00, -.414122316727537E+00, -.308819906524060E+00, 0.464793323114599E-02,\n 0.701502769375151E+00, -.386793804752983E+00, -.308819906524051E+00, 0.464793323114606E-02,\n -.710599623094926E-03, 0.106591769485371E+01, -.381979997324513E+00, 0.627729148172063E-03,\n -.922756502275117E+00, -.533574244752375E+00, -.381979997324512E+00, 0.627729148172069E-03,\n 0.923467101898213E+00, -.532343450101338E+00, -.381979997324515E+00, 0.627729148171996E-03,\n -.188295544778347E-01, 0.858949317087156E+00, -.401536179522233E+00, 0.106299368117930E-02,\n -.734457151921867E+00, -.445781531063333E+00, -.401536179522234E+00, 0.106299368117924E-02,\n 0.753286706399686E+00, -.413167786023834E+00, -.401536179522228E+00, 0.106299368117947E-02,\n -.337521729934930E+00, 0.430628148626658E+00, -.304570712968866E+00, 0.406209681264780E-02,\n -.204174051327885E+00, -.507616466766249E+00, -.304570712968861E+00, 0.406209681264790E-02,\n 0.541695781262815E+00, 0.769883181395793E-01, -.304570712968855E+00, 0.406209681264795E-02,\n 0.499679503802184E+00, -.443492590565618E+00, -.390575549112483E-01, 0.134809639348428E-02,\n 0.134236097918917E+00, 0.654481439325934E+00, -.390575549112718E-01, 0.134809639348326E-02,\n -.633915601721120E+00, -.210988848760292E+00, -.390575549112678E-01, 0.134809639348292E-02,\n 0.759640879950688E+00, -.534956023308264E+00, -.372610878453242E+00, 0.150236562849430E-02,\n 0.834650661171134E-01, 0.925346311444593E+00, -.372610878453244E+00, 0.150236562849425E-02,\n -.843105946067801E+00, -.390390288136326E+00, -.372610878453243E+00, 0.150236562849425E-02,\n -.882002742703712E+00, -.490456722855413E+00, -.257599002612332E+00, 0.509335150374114E-03,\n 0.865749352801516E+00, -.518608419961260E+00, -.257599002612346E+00, 0.509335150374126E-03,\n 0.162533899022075E-01, 0.100906514281669E+01, -.257599002612343E+00, 0.509335150373880E-03,\n 0.706774233459675E+00, -.891533208596826E-01, -.395467447120577E+00, 0.457728775377536E-03,\n -.276178076033606E+00, 0.656661101346199E+00, -.395467447120577E+00, 0.457728775377498E-03,\n -.430596157426042E+00, -.567507780486533E+00, -.395467447120585E+00, 0.457728775377089E-03,\n -.918645944644083E-01, 0.190304232329775E+00, 0.715850885984145E+00, 0.168397478196152E-02,\n -.118876002413072E+00, -.174709188679419E+00, 0.715850885984146E+00, 0.168397478196167E-02,\n 0.210740596877476E+00, -.155950436503571E-01, 0.715850885984132E+00, 0.168397478196237E-02,\n 0.540513301252501E+00, -.943860862874218E-02, -.914318710054978E-01, 0.213070712463987E-02,\n -.262082575777379E+00, 0.472817554282433E+00, -.914318710054964E-01, 0.213070712463992E-02,\n -.278430725475103E+00, -.463378945653674E+00, -.914318710054968E-01, 0.213070712464070E-02,\n 0.145805941349524E+00, -.526334554268467E+00, -.263961054397257E+00, 0.146222435997457E-02,\n 0.382916124211298E+00, 0.389438926365626E+00, -.263961054397247E+00, 0.146222435997416E-02,\n -.528722065560796E+00, 0.136895627902853E+00, -.263961054397253E+00, 0.146222435997499E-02,\n -.182315800139201E-13, -.173834348867150E-14, -.300394380298934E+00, 0.106049995563824E-01,\n -.169910697181091E-13, -.249020633102366E-15, 0.427541621225973E+00, 0.136188175091050E-01,\n 0.156992255283360E-12, 0.102872783354632E-12, 0.145464511562067E+00, 0.887275759574957E-02,\n 0.535998565692471E-13, 0.781044393753285E-13, -.107279857079785E+00, 0.855159201414087E-02 ];\n\nmaptorst = true;\nswitch N\n case 1\n rstw = TN2012_1;\n case 2\n rstw = TN2012_2;\n case 3\n rstw = TN2012_3;\n case 4\n rstw = TN2012_4;\n case 5\n rstw = TN2012_5;\n case 6\n rstw = TN2012_6;\n case 7\n rstw = TN2012_7;\n case 8\n rstw = TN2012_8;\n case 9\n rstw = TN2012_9;\n case 10\n rstw = TN2012_10;\n case 11\n rstw = TN2012_11;\n case 12\n rstw = TN2012_12;\n case 13\n rstw = TN2012_13;\n case 14\n rstw = TN2012_14;\n case 15\n rstw = TN2012_15;\n otherwise\n% error('Quadrature degree too high.')\n [r s t w] = tet_cubature_TP(ceil(N/2));\n rstw = [r(:) s(:) t(:) w(:)]; \n maptorst = false;\nend\n\nr = rstw(:,1); s = rstw(:,2); t = rstw(:,3); \nif maptorst\n [r s t] = xyztorst(r,s,t);\nend\nw = rstw(:,4); w = (4/3)*w/sum(w);\n\n% integrates order (2*N+1)\nfunction [r s t w] = tet_cubature_TP(N)\n\n[ra wa] = JacobiGQ(0,0,N);\n[rb wb] = JacobiGQ(1,0,N);\n[rc wc] = JacobiGQ(2,0,N);\n\n[a b c] = meshgrid(ra, rb, rc);\n[wa wb wc] = meshgrid(wa,wb,wc);\n\na = a(:); b = b(:); c = c(:);\nwa = wa(:); wb = wb(:); wc = wc(:);\nw = wa.*wb.*wc;\nw = (4/3)*w/sum(w);\n\n[r s t] = tet_abctorst(a,b,c);\n"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "ElasticityAcoustic2D_unified.m", "ext": ".m", "path": "WADG_Matlab-master/ElasticityAcoustic2D_unified.m", "size": 12686, "source_encoding": "utf_8", "md5": "a6984b83845491ed80d1ac4cd5a5ea33", "text": "% function ElasticAcoustic2D_unified\n\nclear all, clear\n% clear -global *\n\nGlobals2D\nglobal tau1 tau2\nglobal ue3 ue4 ue5 ua3\nglobal fa1 fa2 fe1 fe2\n\nK1D = 16;\nN = 4;\nc_flag = 0;\nFinalTime = 2.0;\ntau1 = 1;\ntau2 = 1;\n\n[Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D);\n\nStartUp2D;\n\n\n\n[rp sp] = EquiNodes2D(15); [rp sp] = xytors(rp,sp);\nVp = Vandermonde2D(N,rp,sp)/V;\nxp = Vp*x; yp = Vp*y;\n\nNq = 2*N;\n[rq sq wq] = Cubature2D(Nq); % integrate u*v*c\nVq = Vandermonde2D(N,rq,sq)/V;\nPq = V*V'*Vq'*diag(wq); % J's cancel out\nMref = inv(V*V');\nxq = Vq*x; yq = Vq*y;\nJq = Vq*J;\n\n% partition mesh: y > 0 = acoustic\nglobal Ka Ke\n% Ke = 1:K; Ka = []; \n% Ka = 1:K; Ke = [];\nKa = find(mean(y) > 0); Ke = find(mean(y) < 0);\n\n%% find dividing boundary\n\nglobal mapAM vmapAM mapAP vmapAP\nglobal mapEM vmapEM mapEP vmapEP\nmapAM = []; mapAP = [];\nvmapAM = []; vmapAP = [];\nmapEM = []; mapEP = [];\nvmapEM = []; vmapEP = [];\n\nif ~isempty(Ke) && ~isempty(Ka)\n \n mapAM = zeros(Nfp,K1D); mapAP = zeros(Nfp,K1D);\n vmapAM = zeros(Nfp,K1D); vmapAP = zeros(Nfp,K1D);\n mapEM = zeros(Nfp,K1D); mapEP = zeros(Nfp,K1D);\n vmapEM = zeros(Nfp,K1D); vmapEP = zeros(Nfp,K1D);\n \n yM = reshape(y(vmapM),Nfp*Nfaces,K);\n ska = 1; ske = 1;\n for e = 1:K\n yf = reshape(yM(:,e),Nfp,Nfaces);\n for f = 1:Nfaces\n if norm(yf(:,f))<1e-8\n ids = (1:Nfp) + (f-1)*Nfp + (e-1)*Nfp*Nfaces;\n if ismember(e,Ka) % if in acoustic region\n mapAM(:,ska) = mapM(ids);\n mapAP(:,ska) = mapP(ids);\n vmapAM(:,ska) = vmapM(ids);\n vmapAP(:,ska) = vmapP(ids);\n ska = ska + 1;\n elseif ismember(e,Ke) % if in elastic region\n mapEM(:,ske) = mapM(ids);\n mapEP(:,ske) = mapP(ids);\n vmapEM(:,ske) = vmapM(ids);\n vmapEP(:,ske) = vmapP(ids);\n ske = ske + 1;\n else\n keyboard\n end \n end\n end\n end\n \n% keyboard\nend\n\n\n\n%%\nglobal Nfld mu lambda Vq Pq c2\nNfld = 5; %(u1,u2,sxx,syy,sxy)\n\nmu = ones(size(xq));\nlambda = ones(size(xq));\nc2 = ones(size(xq));\n\n% k = 1;\n% mu = 1 + .5*cos(k*pi*xq).*cos(k*pi*yq);\n% c2 = 1 + .5*cos(k*pi*xq).*cos(k*pi*yq);\n\n% mu = V\\(Pq*mu); \n% c2 = V\\(Pq*c2);\n% mu = repmat(mu(1,:),length(wq),1)/sqrt(2);\n% c2 = repmat(c2(1,:),length(wq),1)/sqrt(2);\n\n% vv = Vp*Pq*c2; color_line3(xp,yp,vv,vv,'.');return\n% keyboard\n\n%% implement exact Scholte wave\nScholte;\n%keyboard\n%% params setup\n\nx0 = 0; \ny0 = .1;\npp = exp(-100^2*((x-x0).^2 + (y-y0).^2));\n\nf0 = 10;\nt0 = 1/f0;\n\n% point source\n%global fsrc\n%fsrc = @(t) (t < t0).*(1-2*(pi*f0*(t-t0))^2)*exp(-(pi*f0*(t-t0)^2)).* (Pq * exp(-100^2*((xq-x0).^2 + (yq-y0).^2)));\n%fsrc = @(t) 0;\n\ny0 = -.25;\n%p = exp(-25^2*((x-x0).^2 + (y-y0).^2));\nu = zeros(Np, K);\n\n%% set initial value using exact solution of scholte wave\nU{1}(:,Ka) = u1a(x(:,Ka),y(:,Ka),0);\nU{1}(:,Ke) = u1e(x(:,Ke),y(:,Ke),0);\n\nU{2}(:,Ka) = u2a(x(:,Ka),y(:,Ka),0);\nU{2}(:,Ke) = u2e(x(:,Ke),y(:,Ke),0);\n\nU{3}(:,Ka) = s1ax(x(:,Ka),y(:,Ka),0);\nU{3}(:,Ke) = s1ex(x(:,Ke),y(:,Ke),0);\n\nU{4}(:,Ka) = s2ay(x(:,Ka),y(:,Ka),0);\nU{4}(:,Ke) = s2ey(x(:,Ke),y(:,Ke),0);\n\nU{5}(:,Ka) = zeros(Np,length(Ka));\nU{5}(:,Ke) = s12exy(x(:,Ke),y(:,Ke),0);\n\n\n% U{1} = u;\n% U{2} = u;\n% U{3} = u;\n% U{4} = u;\n% U{5} = u;\n\n%% test numerical stability\nif Nfld*Np*K < 2500\n \n u = zeros(Nfld*Np*K,1);\n rhs = zeros(Nfld*Np*K,1);\n A = zeros(Nfld*Np*K);\n ids = 1:Np*K;\n for i = 1:Nfld*Np*K\n u(i) = 1;\n for fld = 1:Nfld\n U{fld} = reshape(u(ids + (fld-1)*Np*K),Np,K);\n end\n \n% ue1 = s1ex(x,y,0);\n% ue2 = s2ey(x,y,0);\n% ue3 = s12exy(x,y,0);\n% ua1 = s1ax(x,y,0);\n \n rE = ElasRHS2D(U,0);\n rA = AcousRHS2D(U,0); \n \n u(i) = 0;\n for fld = 1:Nfld \n rU = zeros(Np,K);\n rU(:,Ke) = rE{fld}(:,Ke);\n if fld <= 3\n rU(:,Ka) = rA{fld}(:,Ka);\n end\n rhs(ids + (fld-1)*Np*K) = rU;\n end\n \n A(:,i) = rhs(:);\n if (mod(i,100)==0)\n disp(sprintf('on col %d out of %d\\n',i,Np*K*Nfld))\n end\n end\n lam = eig(A);\n \n plot(lam,'.','markersize',24)\n hold on\n title(sprintf('Largest real part = %g\\n',max(real(lam))))\n axis equal\n % drawnow\n max(abs(lam))\n \n keyboard\nend\n%%\n\n\ntime = 0;\n\n% Runge-Kutta residual storage\nfor fld = 1:Nfld\n \n res{fld} = zeros(Np,K);\n %rhs{fld} = zeros(Np,K);\n \nend\n\n% compute time step size\nCN = (N+1)*(N+2)/3; % guessing...\ndt = 2/(max(2*mu(:)+lambda(:))*CN*max(Fscale(:)));\nNsteps = ceil(FinalTime/dt);\ndt = FinalTime/Nsteps;\n\n% outer time step loop\ntstep = 0;\n\nM = inv(V*V');\nwqJ = diag(wq)*(Vq*J);\n\n% figure\n% colormap(gray)\n% colormap(hot)\n\n\nfor tstep = 1:Nsteps\n \n time = tstep*dt;\n \n for INTRK = 1:5\n \n timeloc = time + rk4c(INTRK)*dt;\n \n \n \n ue3 = s1ex(x,y,timeloc);\n ue4 = s2ey(x,y,timeloc);\n ue5 = s12exy(x,y,timeloc);\n ua3 = s1ax(x,y,timeloc);\n \n %fa1 = f1a(x,y,timeloc);\n %fa2 = f2a(x,y,timeloc);\n \n %fe1 = f1e(x,y,timeloc);\n %fe2 = f2e(x,y,timeloc);\n \n rhsE = ElasRHS2D(U,timeloc);\n rhsA = AcousRHS2D(U,timeloc); \n \n % initiate and increment Runge-Kutta residuals\n for fld = 1:Nfld\n rhs = zeros(Np,K); \n if fld <= 3\n rhs(:,Ka) = rhsA{fld}(:,Ka); \n end \n rhs(:,Ke) = rhsE{fld}(:,Ke);\n res{fld} = rk4a(INTRK)*res{fld} + dt*rhs;\n U{fld} = U{fld} + rk4b(INTRK)*res{fld};\n end\n \n end\n \n if 1 && (mod(tstep,10)==0 || tstep==Nsteps)\n clf\n \n pe = (U{3} + U{4})/2; % average trace(S)\n % pe = U{3}; % average trace(S)\n %pa = (U{3} + U{4})/2;\n pa = U{3}; % average trace(S)\n p(:,Ke) = pe(:,Ke);\n p(:,Ka) = pa(:,Ka);\n vv = Vp*p;\n color_line3(xp,yp,vv,vv,'.');\n axis tight\n title(sprintf('time = %f',time));\n colorbar;\n \n drawnow \n \n p_exact(:,Ka) = s1ax(xq(:,Ka),yq(:,Ka),time);\n p_exact(:,Ke) = 0.5*s1ex(xq(:,Ke),yq(:,Ke),time)+0.5*s2ey(xq(:,Ke),yq(:,Ke),time);\n\n p_quadrature = Vq * p;\n\n [d1,d2]=size(p_quadrature);\n error_accumulation = 0;\n\nfor j1=1:d2\n for j2=1:d1\n err = p_quadrature(j2,j1)-p_exact(j2,j1);\n error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1);\n end\nend\n\nerror_l2 = sqrt(error_accumulation)\n\n \n \n \n \n \n end\n \n if mod(tstep,100)==0\n disp(sprintf('On timestep %d out of %d\\n',tstep,round(FinalTime/dt)))\n end\nend\n\n% keyboard\nset(gca,'fontsize',14)\ntitle('')\naxis tight\n\n\np_exact(:,Ka) = s1ax(xq(:,Ka),yq(:,Ka),FinalTime);\np_exact(:,Ke) = 0.5*s1ex(xq(:,Ke),yq(:,Ke),FinalTime)+0.5*s2ey(xq(:,Ke),yq(:,Ke),FinalTime);\n\np_quadrature = Vq * p;\n\n[d1,d2]=size(p_quadrature);\nerror_accumulation = 0;\nfor j1=1:d2\n for j2=1:d1\n err = p_quadrature(j2,j1)-p_exact(j2,j1);\n error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1);\n end\nend\n\nerror_l2 = sqrt(error_accumulation)\n\n\nfunction [rhs] = ElasRHS2D(U,time)\n\n% function [rhsu, rhsv, rhsp] = acousticsRHS2D(u,v,p)\n% Purpose : Evaluate RHS flux in 2D acoustics TM form\n\nGlobals2D;\n\nglobal Nfld mu lambda Vq Pq tau1 tau2 useWADG\nglobal C11 C12 C13 C22 C23 C33\nglobal ue3 ue4 ue5 ua3\nglobal fa1 fa2 fe1 fe2\n% Define field differences at faces\nfor fld = 1:Nfld\n u = U{fld};\n \n % compute jumps\n dU{fld} = zeros(Nfp*Nfaces,K);\n dU{fld}(:) = u(vmapP)-u(vmapM);\n \n ur = Dr*u;\n us = Ds*u;\n Ux{fld} = rx.*ur + sx.*us;\n Uy{fld} = ry.*ur + sy.*us;\nend\n\ndivSx = Ux{3} + Uy{5}; % d(Sxx)dx + d(Sxy)dy\ndivSy = Ux{5} + Uy{4}; % d(Sxy)dx + d(Syy)dy\ndu1dx = Ux{1}; % du1dx\ndu2dy = Uy{2}; % du2dy\ndu12dxy = Ux{2} + Uy{1}; % du2dx + du1dy\n\n% velocity fluxes An^T*sigma\nnSx = nx.*dU{3} + ny.*dU{5};\nnSy = nx.*dU{5} + ny.*dU{4};\n\n% stress fluxes An*u\nnUx = dU{1}.*nx;\nnUy = dU{2}.*ny;\nnUxy = dU{2}.*nx + dU{1}.*ny;\n\nopt=1;\nif opt==1 % traction BCs \n \n % set traction equal to exact traction \n nSx(mapB) = -2*(nx(mapB).*U{3}(vmapB) + ny(mapB).*U{5}(vmapB)) + 2*(nx(mapB).*ue3(vmapB) + ny(mapB).*ue5(vmapB));\n nSy(mapB) = -2*(nx(mapB).*U{5}(vmapB) + ny(mapB).*U{4}(vmapB)) + 2*(nx(mapB).*ue5(vmapB) + ny(mapB).*ue4(vmapB)); \n \n %nSx(mapB) = -2*(nx(mapB).*ue1(vmapB) + ny(mapB).*ue3(vmapB));\n %nSy(mapB) = -2*(nx(mapB).*ue3(vmapB) + ny(mapB).*ue2(vmapB)); \n \n %nSx(mapB) = -2*(nx(mapB).*U{3}(vmapB) + ny(mapB).*U{5}(vmapB)); \n %nSy(mapB) = -2*(nx(mapB).*U{5}(vmapB) + ny(mapB).*U{4}(vmapB)); \n \nelseif opt==2 % basic ABCs\n nSx(mapB) = -(nx(mapB).*U{3}(vmapB) + ny(mapB).*U{5}(vmapB));\n nSy(mapB) = -(nx(mapB).*U{5}(vmapB) + ny(mapB).*U{4}(vmapB));\n dU{1}(mapB) = -U{1}(vmapB);\n dU{2}(mapB) = -U{2}(vmapB);\nelseif opt==3 % zero velocity\n dU{1}(mapB) = -2*U{1}(vmapB);\n dU{2}(mapB) = -2*U{2}(vmapB); \nend\n\n% coupling\nglobal mapEM vmapEM mapEP vmapEP \nnxf = nx(mapEM); nyf = ny(mapEM); \nu = U{1}(vmapEP); \nv = U{2}(vmapEP);\np = U{3}(vmapEP);\n\nSnx = U{3}(vmapEM).*nxf + U{5}(vmapEM).*nyf;\nSny = U{5}(vmapEM).*nxf + U{4}(vmapEM).*nyf;\nUn = u.*nxf + v.*nyf;\ndU1 = (Un.*nxf-U{1}(vmapEM));\ndU2 = (Un.*nyf-U{2}(vmapEM));\n\nUnM = (u-U{1}(vmapEM)).*nxf + (v-U{2}(vmapEM)).*nyf;\ndU1M = UnM.*nxf;\ndU2M = UnM.*nyf;\n\nnSx(mapEM) = (1*p.*nxf - Snx);\nnSy(mapEM) = (1*p.*nyf - Sny);\nnUx(mapEM) = dU1.*nxf;\nnUy(mapEM) = dU2.*nyf;\nnUxy(mapEM) = dU1.*nyf + dU2.*nxf;\n\n% evaluate central fluxes\nfc{1} = nSx;\nfc{2} = nSy;\nfc{3} = nUx;\nfc{4} = nUy;\nfc{5} = nUxy;\n\n% penalization terms - reapply An\nfp{1} = nx.*fc{3} + ny.*fc{5};\nfp{2} = nx.*fc{5} + ny.*fc{4};\n\nfp{1}(mapEM) = dU1M;\nfp{2}(mapEM) = dU2M;\n\nfp{3} = fc{1}.*nx;\nfp{4} = fc{2}.*ny;\nfp{5} = fc{2}.*nx + fc{1}.*ny;\n\nflux = cell(5,1);\nfor fld = 1:2\n flux{fld} = zeros(Nfp*Nfaces,K);\n flux{fld}(:) = fc{fld}(:) + tau1.*fp{fld}(:);\nend\nfor fld = 3:5\n flux{fld} = zeros(Nfp*Nfaces,K);\n flux{fld}(:) = fc{fld}(:) + tau2.*fp{fld}(:);\nend\n% compute right hand sides of the PDE's\nrr{1} = divSx + LIFT*(Fscale.*flux{1})/2.0;\nrr{2} = divSy + LIFT*(Fscale.*flux{2})/2.0;\nrr{3} = du1dx + LIFT*(Fscale.*flux{3})/2.0;\nrr{4} = du2dy + LIFT*(Fscale.*flux{4})/2.0;\nrr{5} = du12dxy + LIFT*(Fscale.*flux{5})/2.0;\n\nif 0\n rhs{1} = rr{1};\n rhs{2} = rr{2};\n rhs{3} = (2*mu+lambda).*rr{3} + lambda.*rr{4};\n rhs{4} = lambda.*rr{3} + (2*mu+lambda).*rr{4};\n rhs{5} = (mu) .* rr{5};\nelse\n global Pq Vq\n rhs{1} = rr{1};\n rhs{2} = rr{2};\n rhs{3} = Pq*((2*mu+lambda).*(Vq*rr{3}) + lambda.*(Vq*rr{4}));\n rhs{4} = Pq*(lambda.*(Vq*rr{3}) + (2*mu+lambda).*(Vq*rr{4}));\n rhs{5} = Pq*(mu .* (Vq*rr{5}));\nend\n\n% global Ka\n% for fld = 1:5\n% rhs{fld}(:,Ka) = 0;\n% end\n\nend\n\n\nfunction [rhs] = AcousRHS2D(U,time)\n\n% function [rhsu, rhsv, rhsp] = acousticsRHS2D(u,v,p)\n% Purpose : Evaluate RHS flux in 2D acoustics TM form\n\nGlobals2D;\nglobal ua3\nglobal fa1 fa2 fe1 fe2\nu = U{1};\nv = U{2};\np = U{3}; % should be same as U{4}\n\n% Define field differences at faces\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM);\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM);\ndv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM);\n\n% evaluate upwind fluxes\nndotdU = nx.*du + ny.*dv;\n\n% Impose reflective boundary conditions (p+ = -p-)\n%ndotdU(mapB) = 0; % will not affect, naturally zero\n%dp(mapB) = -2*p(vmapB);\ndp(mapB) = -2*p(vmapB) + 2*ua3(vmapB);\n\n% elastic-acoustic coupling\nglobal mapAM vmapAM mapAP vmapAP \nnxf = nx(mapAM); nyf = ny(mapAM); \nv1 = U{1}(vmapAP); v2 = U{2}(vmapAP);\nsxx = U{3}(vmapAP); syy = U{4}(vmapAP); sxy = U{5}(vmapAP);\n\nSnx = sxx.*nxf + sxy.*nyf;\nSny = sxy.*nxf + syy.*nyf;\nnSn = Snx.*nxf + Sny.*nyf;\ndU1 = (v1-u(vmapAM));\ndU2 = (v2-v(vmapAM));\nndotdU(mapAM) = dU1.*nxf + dU2.*nyf;\ndp(mapAM) = nSn-1*p(vmapAM);\n\n\nglobal tau1 tau2;\nfluxp = tau2*dp + ndotdU;\nfluxu = (tau1*ndotdU + dp).*nx;\nfluxv = (tau1*ndotdU + dp).*ny;\n\npr = Dr*p; ps = Ds*p;\ndpdx = rx.*pr + sx.*ps;\ndpdy = ry.*pr + sy.*ps;\ndivU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy);\n\n% compute right hand sides of the PDE's\nrhs{1} = dpdx + LIFT*(Fscale.*fluxu)/2.0;\nrhs{2} = dpdy + LIFT*(Fscale.*fluxv)/2.0;\nrhs{3} = divU + LIFT*(Fscale.*fluxp)/2.0;\n\nif 0\n\nglobal c2 Pq Vq\n\n%global fsrc \n%rhs{3} = rhs{3} + fsrc(time);\n\nrhs{3} = Pq*(c2.*(Vq*rhs{3}));\n\nend\n\nend"} +{"plateform": "github", "repo_name": "KGuo26/WADG_Matlab-master", "name": "Wave2D_M_manufactured.m", "ext": ".m", "path": "WADG_Matlab-master/Wave2D_M_manufactured.m", "size": 3244, "source_encoding": "utf_8", "md5": "7f7a6ac983321b0bffeaf09bbd71fa7f", "text": "clear\nGlobals2D\n\nN = 8;\nk=1\n\nfor M = 0:N\n\nK1D = 32;\nFinalTime = 1.0;\n[Nv, VX, VY, K, EToV] = unif_tri_mesh(K1D);\nStartUp2D;\n\n%% Set up wavespeed function\n%cfun = @(x,y) ones(size(x));\ncfun = @(x,y) 1+ 0.5*sin(k*pi*x).*sin(k*pi*y); % smooth velocity\n%cfun = @(x,y) (1 + .5*sin(2*pi*x).*sin(2*pi*y) + (y > 0)); % piecewise smooth velocity\n\n%% Set periodic manufactured solution\npfun = @(x,y,t) sin(pi*x).*sin(pi*y).*cos(pi*t);\nufun = @(x,y,t) -cos(pi*x).*sin(pi*y).*sin(pi*t);\nvfun = @(x,y,t) -sin(pi*x).*cos(pi*y).*sin(pi*t);\nffun = @(x,y,t) pi*(-1./(cfun(x,y))+2).*sin(pi*x).*sin(pi*y).*sin(pi*t);\n\n%% generate quadrature points\nNq = 2*N+1;\n[rq sq wq] = Cubature2D(Nq); % integrate u*v*c\nVq = Vandermonde2D(N,rq,sq)/V;\nxq = Vq*x; yq = Vq*y;\n\n%% construct the projection matrix for nodal basis Pq\nPq = V*V'*Vq'*diag(wq);\n\n%% construct matrix Cq\nCq = cfun(xq,yq);\n\n%% construct the projection matrix for cfun to degree M\nVMq = Vandermonde2D(M,rq,sq);\nCqM = VMq*VMq'*diag(wq)*Cq;\n\n%% initial condition\np = pfun(x,y,0);\nu = ufun(x,y,0);\nv = vfun(x,y,0);\n\ntime = 0;\n\n%% Runge-Kutta residual storage\nresu = zeros(Np,K); resv = zeros(Np,K); resp = zeros(Np,K);\n\n%% compute time step size\nCN = (N+1)*(N+2)/2; % trace inequality constant\nCNh = max(CN*max(Fscale(:)));\ndt = 2/CNh;\n\n%% outer time step loop\ntstep = 0;\n\nwhile (timeFinalTime), dt = FinalTime-time; end\n \n for INTRK = 1:5\n \n timelocal = time + rk4c(INTRK)*dt;\n \n f=ffun(x,y,timelocal);\n \n [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f);\n \n % initiate and increment Runge-Kutta residuals\n resp = rk4a(INTRK)*resp + dt*rhsp;\n resu = rk4a(INTRK)*resu + dt*rhsu;\n resv = rk4a(INTRK)*resv + dt*rhsv;\n \n % update fields\n u = u+rk4b(INTRK)*resu;\n v = v+rk4b(INTRK)*resv;\n p = p+rk4b(INTRK)*resp;\n \n end\n \n % Increment time\n time = time+dt; tstep = tstep+1;\nend\n\np_exact = pfun(x,y,FinalTime);\np_exact_quadrature = pfun(xq,yq,FinalTime);\n\np_quadrature = Vq * p;\n\n[d1,d2]=size(p_quadrature);\nerror_accumulation = 0;\nfor j1=1:d2\n for j2=1:d1\n err = p_quadrature(j2,j1)-p_exact_quadrature(j2,j1);\n error_accumulation = error_accumulation + err*err*wq(j2)*J(1,j1);\n end\nend\n\nerror_l2(M+1) = sqrt(error_accumulation);\nerror_fro(M+1) = norm(p-p_exact,'fro'); \n\nend\n\n\nfunction [rhsp, rhsu, rhsv] = acousticsRHS2D_compare(p,u,v,f)\n\nGlobals2D;\n\n% Define field differences at faces\ndp = zeros(Nfp*Nfaces,K); dp(:) = p(vmapP)-p(vmapM);\ndu = zeros(Nfp*Nfaces,K); du(:) = u(vmapP)-u(vmapM);\ndv = zeros(Nfp*Nfaces,K); dv(:) = v(vmapP)-v(vmapM);\n\n% evaluate upwind fluxes\nndotdU = nx.*du + ny.*dv;\n\n% Impose reflective boundary conditions (p+ = -p-)\nndotdU(mapB) = 0;\ndp(mapB) = -2*p(vmapB);\n\ntau = 1;\nfluxp = tau*dp - ndotdU;\nfluxu = (tau*ndotdU - dp).*nx;\nfluxv = (tau*ndotdU - dp).*ny;\n\npr = Dr*p; ps = Ds*p;\ndpdx = rx.*pr + sx.*ps;\ndpdy = ry.*pr + sy.*ps;\ndivU = Dr*(u.*rx + v.*ry) + Ds*(u.*sx + v.*sy);\n\n% compute right hand sides of the PDE's\nrhsp = -divU + f + LIFT*(Fscale.*fluxp)/2.0;\nrhsu = -dpdx + LIFT*(Fscale.*fluxu)/2.0;\nrhsv = -dpdy + LIFT*(Fscale.*fluxv)/2.0;\n\nrhsp = Pq*(CqM.*(Vq*rhsp));\nreturn;\nend\n"} +{"plateform": "github", "repo_name": "caghangir/MATLAB-Grid-Search-for-Neural-Networks-master", "name": "gridSearchNN.m", "ext": ".m", "path": "MATLAB-Grid-Search-for-Neural-Networks-master/gridSearchNN.m", "size": 2393, "source_encoding": "utf_8", "md5": "40eb11e58ad1cf4dfde388d97884b636", "text": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Grid Search for Matlab %\n% %\n% Copyright (C) 2017 Cagatay Demirel. All rights reserved. %\n% demirelc16@itu.edu.tr %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% **** Example (How to use function) *******\n%\n% hidlaysize1 = [15 30 70];\n% hidlaysize2 = [10 20 50];\n% trainopt = {'traingd' 'traingda' 'traingdm' 'traingdx'}; \n% maxepoch = [10 20 40 90];\n% transferfunc = {'logsig' 'tansig'};\n% bestparameters = gridSearchNN(x_train',y_train',hidlaysize1,...\n% hidlaysize2,trainopt,maxepoch,transferfunc);\n\n\nfunction out = gridSearchNN(trainX,trainY,param1,param2,param3,param4,...\n param5,varargin)\n\nif(nargin > 4)\n[p,q,r,s,t] = ndgrid(param1,param2,1:length(param3),param4,1:length(param5));\npairs = [p(:) q(:) r(:) s(:) t(:)];\n% scoreboard = cell(size(pairs,1),4);\nelse\n[p,q] = meshgrid(param1,param2);\npairs = [p(:) q(:)];\n% scoreboard = cell(size(pairs,1),3);\nend\n\nvalscores = zeros(size(pairs,1),1);\n\nfor i=1:size(pairs,1)\n setdemorandstream(672880951)\n net = patternnet([pairs(i,1) pairs(i,2)]);\n net.trainFcn = param3{pairs(i,3)};\n net.trainParam.epochs\t= pairs(i,4);\n net.layers{2}.transferFcn = param5{pairs(i,5)};\n net.divideParam.trainRatio = 0.9;\n net.divideParam.valRatio = 0.1;\n net.divideParam.testRatio = 0; \n \n vals = crossval(@(XTRAIN, YTRAIN, XTEST, YTEST)NNtrain(XTRAIN, YTRAIN, XTEST, YTEST, net),...\n trainX, trainY);\n valscores(i) = mean(vals); \n\n% net = train(net,trainX,trainY);\n% y_pred = net(valX); \n% [~,indicesReal] = max(valY, [], 1); %336x1 matrix\n% [~, indicesPredicted] = max(y_pred,[],1);\n% valscores(i) = mean(double(indicesPredicted == indicesReal)); \n\nend\n\n [~,ind] = max(valscores);\n out = {pairs(ind,1) pairs(ind,2) param3{pairs(ind,3)} ...\n pairs(ind,4) param5{pairs(ind,5)}};\n\n\nend\n\nfunction testval = NNtrain(XTRAIN, YTRAIN, XTEST, YTEST, net)\n\n net = train(net, XTRAIN', YTRAIN');\n y_pred = net(XTEST');\n [~,indicesReal] = max(YTEST',[],1);\n [~,indicesPredicted] = max(y_pred,[],1);\n testval = mean(double(indicesPredicted == indicesReal)); \nend\n"} +{"plateform": "github", "repo_name": "mrmushfiq/qalma-master", "name": "qalma.m", "ext": ".m", "path": "qalma-master/qalma.m", "size": 5230, "source_encoding": "utf_8", "md5": "0e9226a0f71ab8eb22b7073be7ef050e", "text": "function varargout = qalma(varargin)\n% QALMA MATLAB code for qalma.fig\n% QALMA, by itself, creates a new QALMA or raises the existing\n% singleton*.\n%\n% H = QALMA returns the handle to a new QALMA or the handle to\n% the existing singleton*.\n%\n% QALMA('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in QALMA.M with the given input arguments.\n%\n% QALMA('Property','Value',...) creates a new QALMA or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before qalma_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to qalma_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help qalma\n\n% Last Modified by GUIDE v2.5 08-Jun-2017 23:41:29\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @qalma_OpeningFcn, ...\n 'gui_OutputFcn', @qalma_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before qalma is made visible.\nfunction qalma_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to qalma (see VARARGIN)\n\n% Choose default command line output for qalma\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes qalma wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n%set(handles.date_txt, 'String', date);\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = qalma_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in ss_button.\nfunction ss_button_Callback(hObject, eventdata, handles)\n% hObject handle to ss_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(qalma);\nrun('star_shot');\n\n\n% --- Executes on button press in pf_button.\nfunction pf_button_Callback(hObject, eventdata, handles)\n% hObject handle to pf_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(qalma);\n%run('./picket_panda8/picket_panda.m');\nrun('picket_panda');\n\n% --- Executes on button press in wl_button.\nfunction wl_button_Callback(hObject, eventdata, handles)\n% hObject handle to wl_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(qalma);\nrun('wl');\n\n\n% --- Executes on button press in lr_button.\nfunction lr_button_Callback(hObject, eventdata, handles)\n% hObject handle to lr_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(qalma);\nrun('ci');\n\n\n% --- Executes on button press in lf_button.\nfunction lf_button_Callback(hObject, eventdata, handles)\n% hObject handle to lf_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(qalma);\nrun('dynalog');\n\n\n% --- Executes on button press in rotate_button.\nfunction rotate_button_Callback(hObject, eventdata, handles)\n% hObject handle to rotate_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in crop_button.\nfunction crop_button_Callback(hObject, eventdata, handles)\n% hObject handle to crop_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in invert_button.\nfunction invert_button_Callback(hObject, eventdata, handles)\n% hObject handle to invert_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n"} +{"plateform": "github", "repo_name": "mrmushfiq/qalma-master", "name": "star_shot.m", "ext": ".m", "path": "qalma-master/star_shot/star_shot.m", "size": 26383, "source_encoding": "utf_8", "md5": "2b44cdb1fdf5db0023e49a8971a36020", "text": "% M. Mushfiqur Rahman\n% Florida Atlantic University\n% August, 2017\n\nfunction varargout = star_shot(varargin)\n% STAR_SHOT MATLAB code for star_shot.fig\n% STAR_SHOT, by itself, creates a new STAR_SHOT or raises the existing\n% singleton*.\n%\n% H = STAR_SHOT returns the handle to a new STAR_SHOT or the handle to\n% the existing singleton*.\n%\n% STAR_SHOT('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in STAR_SHOT.M with the given input arguments.\n%\n% STAR_SHOT('Property','Value',...) creates a new STAR_SHOT or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before star_shot_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to star_shot_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help star_shot\n\n% Last Modified by GUIDE v2.5 25-Aug-2017 22:35:28\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @star_shot_OpeningFcn, ...\n 'gui_OutputFcn', @star_shot_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before star_shot is made visible.\nfunction star_shot_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to star_shot (see VARARGIN)\n\n% Choose default command line output for star_shot\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes star_shot wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\nset(handles.axes1, 'box','off','XTickLabel',[],'xtick',[],'YTickLabel',[],'ytick',[]);\n%set(handles.num_arms_pop, 'String',{4:24});\nset(handles.axes2, 'visible', 'off');\nset(handles.axes3, 'visible', 'off');\nset(handles.radius_name, 'visible', 'off');\nset(handles.radius_txt, 'visible', 'off');\nset(handles.comment_txt, 'visible', 'on');\nset(handles.report_button, 'visible', 'on');\nset(handles.mm_txt, 'visible', 'off');\n\nset(handles.uitable1, 'visible', 'off');\nset(handles.uitable1, 'Data', []);\nset(handles.uitable1, 'ColumnName', {'Image','Gantry','Couch', 'Collimator', 'Radius(mm)','Comment'});\n\nset(handles.wiener_check, 'Value', 1);\nset(handles.w1_pop, 'String',{1:10}, 'Value', 8);\nset(handles.w2_pop, 'String',{1:10}, 'Value', 8);\nset(handles.avg_txt, 'String', '2');\nset(handles.crop_check, 'Value', 1);\nset(handles.resolution_txt, 'String', '0.39');\nset(handles.mag_factor_txt, 'String', '1'); \n\nset(handles.analyze_button, 'Enable', 'off');\nset(handles.report_button, 'Enable', 'off');\nset(handles.add_button, 'Enable', 'off');\nwarning('off','all')\n\n\nglobal analyzer;\nanalyzer = 0; \n\nglobal c1;\nglobal c2;\nglobal c3; \nc1 = get(handles.gantry_check, 'Value');\nc2 = get(handles.couch_check, 'Value');\nc3 = get(handles.collimator_check, 'Value');\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = star_shot_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in browse_button.\nfunction browse_button_Callback(hObject, eventdata, handles)\n% hObject handle to browse_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal img;\nglobal file_name;\n\n[f p] = uigetfile(... \n {'*.jpg; *.JPG; *.jpeg; *.JPEG; *.img; *.IMG; *.tif;*.png; *.TIF; *.tiff, *.TIFF','Supported Files (*.jpg,*.img,*.tiff,*.png)'; ...\n '*.jpg','jpg Files (*.jpg)';...\n '*.JPG','JPG Files (*.JPG)';...\n '*.jpeg','jpeg Files (*.jpeg)';...\n '*.JPEG','JPEG Files (*.JPEG)';...\n '*.img','img Files (*.img)';...\n '*.IMG','IMG Files (*.IMG)';...\n '*.tif','tif Files (*.tif)';...\n '*.TIF','TIF Files (*.TIF)';...\n '*.tiff','tiff Files (*.tiff)';...\n '*.TIFF','TIFF Files (*.TIFF)'},... \n 'MultiSelect', 'off');\n\ntry \n img_d = imread([p f]);\n img=im2double(img_d);\n img=uint8(255*mat2gray(img));\n imshow(img,'Parent',handles.axes1);\n img = img_d;\n file_name = f; \n set(handles.analyze_button, 'Enable', 'on');\n set(handles.report_button, 'Enable', 'on');\n set(handles.add_button, 'Enable', 'on');\n\ncatch\n h = msgbox('Please upload an image');\nend\n\n% --- Executes on button press in analyze_button.\nfunction analyze_button_Callback(hObject, eventdata, handles)\n% hObject handle to analyze_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.analyze_button, 'Enable', 'off');\nglobal img;\nglobal file_name; \nglobal analyzer;\n\n\nanalyzer = analyzer + 1; \n%starF(handles,img);\n\n[radii,pass] = starF(handles,img);\n\nif pass == 1\n\n set(handles.browse_button, 'Visible', 'off'); \n setpixelposition(handles.uitable1,[65, 10, 490, 127]);\n set(handles.uitable1, 'visible', 'on');\n\n global c1;\n global c2;\n global c3;\n\n\n c1 = get(handles.gantry_check, 'Value');\n c2 = get(handles.couch_check, 'Value');\n c3 = get(handles.collimator_check, 'Value');\n\n D = get(handles.uitable1, 'Data');\n\n [r,c] = size(D);\n D{r+1,1} = file_name; \n\n if c1==1\n D{r+1,2} = ' X ';\n elseif c2 == 1\n D{r+1,3} = ' X ';\n elseif c3 == 1\n D{r+1,4} = ' X '; \n else\n h = msgbox({'Check at least one of the three components'});\n pause(2)\n delete(h);\n end \n\n D{r+1,5} = get(handles.radius_txt, 'String');\n% if pass == 1\n% D{r+1,5} = get(handles.radius_txt, 'String'); \n% else\n% D{r+1,5} = '-';\n% end\n\n D{r+1,6} = get(handles.comment_txt, 'String');\n\n set(handles.uitable1, 'Data', D);\n set(handles.row_pop, 'String', {1:r+1});\nend\n\n% --- Executes on selection change in num_arms_pop.\nfunction num_arms_pop_Callback(hObject, eventdata, handles)\n% hObject handle to num_arms_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns num_arms_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from num_arms_pop\n\n\n% --- Executes during object creation, after setting all properties.\nfunction num_arms_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to num_arms_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction radius_txt_Callback(hObject, eventdata, handles)\n% hObject handle to radius_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of radius_txt as text\n% str2double(get(hObject,'String')) returns contents of radius_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction radius_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to radius_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction comment_txt_Callback(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of comment_txt as text\n% str2double(get(hObject,'String')) returns contents of comment_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction comment_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in report_button.\nfunction report_button_Callback(hObject, eventdata, handles)\n% hObject handle to report_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ntc = get(handles.comment_txt, 'String'); \ntc = strcat('Comment:', tc);\nresult = get(handles.radius_txt, 'String');\nresult = strcat('Radius: ',result); \nD = get(handles.uitable1, 'Data');\n\n\nf2=figure\nt = uitable(f2,'Data',D,'Position',[20 60 500 300]);\nt.ColumnName = {'Image','Gantry','Couch', 'Collimator', 'Radius(mm)','Comment'}\n\nsaveas(f2,'Star_Report.pdf');\n\n\n% --- Executes on button press in add_button.\nfunction add_button_Callback(hObject, eventdata, handles)\n% hObject handle to add_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal img;\nglobal file_name;\n%set(handles.axes2, 'visible', 'off');\nset(handles.axes2, 'Units', 'pixels', 'Position', [300, 300, 10, 10]);\n\n[f p] = uigetfile(... \n {'*.jpg; *.JPG; *.jpeg; *.JPEG; *.img; *.IMG; *.tif;*.png; *.TIF; *.tiff, *.TIFF','Supported Files (*.jpg,*.img,*.tiff,*.png)'; ...\n '*.jpg','jpg Files (*.jpg)';...\n '*.JPG','JPG Files (*.JPG)';...\n '*.jpeg','jpeg Files (*.jpeg)';...\n '*.JPEG','JPEG Files (*.JPEG)';...\n '*.img','img Files (*.img)';...\n '*.IMG','IMG Files (*.IMG)';...\n '*.tif','tif Files (*.tif)';...\n '*.TIF','TIF Files (*.TIF)';...\n '*.tiff','tiff Files (*.tiff)';...\n '*.TIFF','TIFF Files (*.TIFF)'},... \n 'MultiSelect', 'off');\n\ntry\n img_d = imread([p f]);\n img=im2double(img_d);\n img=uint8(255*mat2gray(img));\n set(handles.axes1, 'Units', 'pixels', 'Position', [37, 99, 544, 397]);\n imshow(img,'Parent',handles.axes1);\n\n setpixelposition(handles.uitable1,[65, 10, 490, 70]);\n\n img = img_d;\n file_name = f; \n set(handles.analyze_button, 'Enable', 'on');\n\ncatch\n h = msgbox('Please upload an image');\nend\n\n%imshow(img,'Parent',handles.axes1);\n\n% --- Executes on button press in gantry_check.\nfunction gantry_check_Callback(hObject, eventdata, handles)\n% hObject handle to gantry_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of gantry_check\nset(handles.couch_check,'Value',0); \nset(handles.collimator_check,'Value',0); \n\n\n% --- Executes on button press in couch_check.\nfunction couch_check_Callback(hObject, eventdata, handles)\n% hObject handle to couch_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of couch_check\nset(handles.gantry_check,'Value',0); \nset(handles.collimator_check,'Value',0); \n\n% --- Executes on button press in collimator_check.\nfunction collimator_check_Callback(hObject, eventdata, handles)\n% hObject handle to collimator_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of collimator_check\nset(handles.couch_check,'Value',0); \nset(handles.gantry_check,'Value',0); \n\n\n% --- Executes on button press in delete_row_button.\nfunction delete_row_button_Callback(hObject, eventdata, handles)\n% hObject handle to delete_row_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on selection change in row_pop.\nfunction row_pop_Callback(hObject, eventdata, handles)\n% hObject handle to row_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns row_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from row_pop\n\n\n% --- Executes during object creation, after setting all properties.\nfunction row_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to row_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in manual_check.\nfunction manual_check_Callback(hObject, eventdata, handles)\n% hObject handle to manual_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of manual_check\n\n\n\nfunction rotate_txt_Callback(hObject, eventdata, handles)\n% hObject handle to rotate_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of rotate_txt as text\n% str2double(get(hObject,'String')) returns contents of rotate_txt as a double\n% global img;\n% angle = str2num(get(handles.rotate_txt,'String'));\n% \n% if get(handles.manual_check, 'Value') == 1\n% img = imrotate(img, angle);\n% imshow(img,'Parent',handles.axes2);\n% else\n% h = msgbox({'Please Activate Manual mode'});\n% pause(1)\n% delete(h);\n% end\n\n% --- Executes during object creation, after setting all properties.\nfunction rotate_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to rotate_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in center_check.\nfunction center_check_Callback(hObject, eventdata, handles)\n% hObject handle to center_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of center_check\n\n\n% --- Executes on button press in invert_check.\nfunction invert_check_Callback(hObject, eventdata, handles)\n% hObject handle to invert_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of invert_check\nglobal img;\nv1 = get(handles.manual_check, 'Value');\nv2 = get(handles.invert_check, 'Value');\nif v1 == 1 & v2 == 1\n img = imcomplement(img);\n imshow(img,'Parent',handles.axes1);\nend\nset(handles.invert_check, 'Value',0);\n\n% --- Executes on button press in analyze_button.\nfunction pushbutton8_Callback(hObject, eventdata, handles)\n% hObject handle to analyze_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n\nfunction avg_txt_Callback(hObject, eventdata, handles)\n% hObject handle to avg_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of avg_txt as text\n% str2double(get(hObject,'String')) returns contents of avg_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction avg_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to avg_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in w1_pop.\nfunction w1_pop_Callback(hObject, eventdata, handles)\n% hObject handle to w1_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns w1_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from w1_pop\n\n\n% --- Executes during object creation, after setting all properties.\nfunction w1_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to w1_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in w2_pop.\nfunction w2_pop_Callback(hObject, eventdata, handles)\n% hObject handle to w2_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns w2_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from w2_pop\n\n\n% --- Executes during object creation, after setting all properties.\nfunction w2_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to w2_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in delete_button.\nfunction delete_button_Callback(hObject, eventdata, handles)\n% hObject handle to delete_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nD = get(handles.uitable1, 'Data');\n\n[r,c] = size(D);\nrow = get(handles.row_pop, 'Value');\n\nif r>0\n D(row,:) = [];\nend\n\nset(handles.uitable1, 'Data', D);\n\nfunction edit9_Callback(hObject, eventdata, handles)\n% hObject handle to edit9 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of edit9 as text\n% str2double(get(hObject,'String')) returns contents of edit9 as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit9_CreateFcn(hObject, eventdata, handles)\n% hObject handle to edit9 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\n% --- Executes on button press in report_button.\nfunction pushbutton12_Callback(hObject, eventdata, handles)\n% hObject handle to report_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in wiener_check.\nfunction wiener_check_Callback(hObject, eventdata, handles)\n% hObject handle to wiener_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of wiener_check\n\n\n\nfunction edit10_Callback(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of comment_txt as text\n% str2double(get(hObject,'String')) returns contents of comment_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit10_CreateFcn(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction mag_factor_txt_Callback(hObject, eventdata, handles)\n% hObject handle to mag_factor_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of mag_factor_txt as text\n% str2double(get(hObject,'String')) returns contents of mag_factor_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction mag_factor_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to mag_factor_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction resolution_txt_Callback(hObject, eventdata, handles)\n% hObject handle to resolution_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of resolution_txt as text\n% str2double(get(hObject,'String')) returns contents of resolution_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction resolution_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to resolution_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in crop_check.\nfunction crop_check_Callback(hObject, eventdata, handles)\n% hObject handle to crop_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of crop_check\n\n\n% --- Executes on button press in home_button.\nfunction home_button_Callback(hObject, eventdata, handles)\n% hObject handle to home_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(star_shot);\nrun('qalma');\n\n\n% --- Executes when user attempts to close figure1.\nfunction figure1_CloseRequestFcn(hObject, eventdata, handles)\n% hObject handle to figure1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: delete(hObject) closes the figure\ndelete(hObject);\n\nif exist('starshot.png', 'file')==2\n delete('starshot.png');\nend\n\nif exist('starshot_zoomed.png', 'file')==2\n delete('starshot_zoomed.png');\nend\nclearvars;"} +{"plateform": "github", "repo_name": "mrmushfiq/qalma-master", "name": "picket_panda.m", "ext": ".m", "path": "qalma-master/picket_fence/picket_panda.m", "size": 26770, "source_encoding": "utf_8", "md5": "d8e6b4b5b54d088f497dc1f0bef488f7", "text": "% M. Mushfiqur Rahman\n% Florida Atlantic University\n% August, 2017\n\nfunction varargout = picket_panda(varargin)\n% PICKET_PANDA MATLAB code for picket_panda.fig\n% PICKET_PANDA, by itself, creates a new PICKET_PANDA or raises the existing\n% singleton*.\n%\n% H = PICKET_PANDA returns the handle to a new PICKET_PANDA or the handle to\n% the existing singleton*.\n%\n% PICKET_PANDA('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in PICKET_PANDA.M with the given input arguments.\n%\n% PICKET_PANDA('Property','Value',...) creates a new PICKET_PANDA or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before picket_panda_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to picket_panda_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help picket_panda\n\n% Last Modified by GUIDE v2.5 23-Aug-2017 18:14:46\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @picket_panda_OpeningFcn, ...\n 'gui_OutputFcn', @picket_panda_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before picket_panda is made visible.\nfunction picket_panda_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to picket_panda (see VARARGIN)\n\n% Choose default command line output for picket_panda\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n% UIWAIT makes picket_panda wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\nglobal count; \ncount = 0; % go button click counter\nglobal mag_count; %mag button click counter\nmag_count = 0; \n\nset(handles.axes2, 'visible', 'off', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]);\n\nset(handles.axes1, 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]);\nset(handles.data_transfer_min, 'Data',[]);\n\nset(handles.smoothing_param,'string','3');\nset(handles.picket_num_pop, 'String',{1:10});\nset(handles.level_txt, 'String', '26');\n\nset(handles.width_left_txt, 'String', '37');\nset(handles.width_right_txt, 'String', '37');\nset(handles.w1_pop, 'String', {1:10});\nset(handles.w2_pop, 'String', {1:10});\n% set(handles.w1_pop, 'Value', 3);\n% set(handles.w2_pop, 'Value', 2);\nset(handles.w1_pop, 'Value', 5);\nset(handles.w2_pop, 'Value', 5);\n\nset(handles.rotate_pop, 'String', [0,90,180,270,360]);\nset(handles.rotate_check, 'Value', 1);\nset(handles.rotate_pop, 'Value', 1);\nset(handles.profile_check, 'Value', 0);\nset(handles.wiener_check, 'Value',1);\nset(handles.mag_txt, 'String', '1.5');\nset(handles.res_txt, 'String', '0.781');\n\nset(handles.go_button, 'Enable', 'off');\nset(handles.recalculate_button, 'Enable', 'off');\nset(handles.plus_button, 'Enable', 'off');\nset(handles.minus_button, 'Enable', 'off');\nset(handles.column_mlc, 'Enable', 'off');\nset(handles.select_line, 'Enable', 'off');\nset(handles.report_button, 'Enable', 'off');\nset(handles.rotate_pop, 'Enable', 'off');\nset(handles.magnify_button, 'Enable', 'off');\nset(handles.clear, 'Enable', 'off');\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = picket_panda_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in pushbutton1.\nfunction pushbutton1_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n%......\n%dicomF(handles);\n\nglobal img;\n[f p] = uigetfile({'*.dcm','DICOM Files'});\n\ntry\n img_d = dicomread([p f]);\n img=im2double(img_d);\n img=uint8(255*mat2gray(img));\n %img = imrotate(img, 90);\n\n imshow(img,'Parent',handles.axes1);\n h = msgbox({'Please select the number of pickets and select the pickets'});\n pause(2)\n delete(h);\n set(handles.go_button, 'Enable', 'on');\n set(handles.rotate_pop, 'Enable', 'on');\n set(handles.magnify_button, 'Enable', 'on');\n set(handles.clear, 'Enable', 'on');\ncatch\n h = msgbox('Please upload an image');\nend\n\n\n\n% --- Executes when entered data in editable cell(s) in data_transfer_min.\nfunction data_transfer_min_CellEditCallback(hObject, eventdata, handles)\n% hObject handle to data_transfer_min (see GCBO)\n% eventdata structure with the following fields (see MATLAB.UI.CONTROL.TABLE)\n%\tIndices: row and column indices of the cell(s) edited\n%\tPreviousData: previous data for the cell(s) edited\n%\tEditData: string(s) entered by the user\n%\tNewData: EditData or its converted form set on the Data property. Empty if Data was not changed\n%\tError: error string when failed to convert EditData to appropriate value for Data\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on selection change in select_line.\nfunction select_line_Callback(hObject, eventdata, handles)\n% hObject handle to select_line (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns select_line contents as cell array\n% contents{get(hObject,'Value')} returns selected item from select_line\nset(handles.plus_button, 'Enable', 'on');\nset(handles.minus_button, 'Enable', 'on');\n\n% --- Executes during object creation, after setting all properties.\nfunction select_line_CreateFcn(hObject, eventdata, handles)\n% hObject handle to select_line (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in plus_button.\nfunction plus_button_Callback(hObject, eventdata, handles)\n% hObject handle to plus_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nglobal img;\nmoveF(handles,img,-1); %sign = -1 , one pixel movement\n%magnifier('aacircle', 20, 'current_positions.png');\nset(handles.recalculate_button, 'Enable', 'on');\n\n\n% --- Executes on button press in minus_button.\nfunction minus_button_Callback(hObject, eventdata, handles)\n% hObject handle to minus_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal img;\nmoveF(handles,img,+1);\nset(handles.recalculate_button, 'Enable', 'on');\n%sign = +1 , one pixel movement\n%magnifier('aacircle', 20, 'current_positions.png');\n\n\n% --- Executes on button press in clear.\nfunction clear_Callback(hObject, eventdata, handles)\n% hObject handle to clear (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal img;\nimshow(img);\nh = msgbox({'Please select the number of pickets (or keep as it is) and select the pickets'});\npause(2)\ndelete(h);\nset(handles.go_button, 'Enable', 'on');\nset(handles.data_transfer_min, 'Data',[]);\nset(handles.column_mlc, 'Enable', 'off');\nset(handles.select_line, 'Enable', 'off');\n\n\n\n% --- Executes on selection change in column_mlc.\nfunction column_mlc_Callback(hObject, eventdata, handles)\n% hObject handle to column_mlc (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% Hints: contents = cellstr(get(hObject,'String')) returns column_mlc contents as cell array\n% contents{get(hObject,'Value')} returns selected item from column_mlc\nset(handles.select_line, 'Enable', 'on');\n\nglobal img;\n\nmin_data = get(handles.data_transfer_min, 'Data');\n[r,c]= size(min_data);\n\ncolumn = get(handles.column_mlc, 'Value');\nmin = min_data(:,column); %just getting the column required\n\nmy_line = get(handles.select_line,'Value');\nxy = get(handles.xy_data,'Data');\nx=xy(:,1);\n\nlevel = str2num(get(handles.level_txt, 'String'));\n\n%for i=my_line:length(min)-1\n% min(i) = min(i) + 1;\n%end\n\n\nfor i=1:length(min)-1\n leafpos(i) = (min(i) + min(i+1))/2; \nend\n\nimshow(img);\n\nmin_s = min;\nhold on\np = column;\ncol = num2str(p);\ntext([round(x(p))+level],[0],col, 'Color','black')\n\nfor j=1:length(leafpos)\n% line([round(x(1))-30 round(x(1))-20],[leafpos(j) leafpos(j)],'Color','r')\n name = num2str(j);\n \n text([round(x(p))],[leafpos(j)],name, 'Color','yellow')\n \n line([round(x(p))+level],[leafpos(j)],'Color','r','Marker','*', 'MarkerSize',3)\nend\n\nhold off\n\nhold on\n\nfor j=1:length(min_s)\n line([round(x(p))+level-4 round(x(p))+level+11],[min_s(j) min_s(j)],'Color','g')\nend\n\n\nhold off\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction column_mlc_CreateFcn(hObject, eventdata, handles)\n% hObject handle to column_mlc (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in magnify_button.\nfunction magnify_button_Callback(hObject, eventdata, handles)\n% hObject handle to magnify_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n%im= getimage(handles.axes1);\n%magnifier('aacircle', 20, 'current_positions.png');\nglobal mag_count;\nmag_count = mag_count + 1;\n\nwhile mag_count > 0\n if mod(mag_count,2) == 0 \n set(handles.axes2, 'visible', 'off');\n set(get(handles.axes2,'children'),'visible','off');\n %delete(handles.axes2);\n axes(handles.axes1);\n %ginput(0);\n break;\n else\n %[x,y] = ginput; \n\n [x,y] = ginput(1); \n set(handles.axes2, 'visible', 'on');\n frame = getframe(handles.axes1);\n im = frame2im(frame);\n [r,c] = size(im);\n %magnifier('aacircle', 20, im);\n\n imshow(im,'Parent',handles.axes2);\n\n axes(handles.axes2);\n zoom(3);\n axis([double(x+10) double(x + 110) double(y-40) double(y)]);\n set(handles.axes2, 'Units', 'pixels', 'Position', [x-3, r-y, 200, 140],...\n 'box','off','XTickLabel',[],'xtick',[],'YTickLabel',[],'ytick',[]);\n \n\n end\nend\n %mag_counter =0;\n% --- Executes on button press in recalculate_button.\nfunction recalculate_button_Callback(hObject, eventdata, handles)\n% hObject handle to recalculate_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.recalculate_button, 'Enable', 'off');\nset(handles.plus_button, 'Enable', 'off');\nset(handles.minus_button, 'Enable', 'off');\nset(handles.select_line, 'Enable', 'on');\n\nglobal img;\nrecalcF(handles,img);\n\n\n% --- Executes on button press in report_button.\nfunction report_button_Callback(hObject, eventdata, handles)\n% hObject handle to report_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nf2 = figure\nf2.Position = [100, 100, 740, 900];\n[snap,map1] = imread('current_positions.png');\n[gaps,map2] = imread('edge_gaps.png');\ntitle('Report');\nsubplot(8,10,1:30), imshow(snap,[]); axis equal;\nsubplot(8,10,31:80),imshow(gaps,[]); axis equal;\nsaveas(f2,'Picket_Report.pdf');\n \n\n\n\nfunction smoothing_param_Callback(hObject, eventdata, handles)\n% hObject handle to smoothing_param (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of smoothing_param as text\n% str2double(get(hObject,'String')) returns contents of smoothing_param as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction smoothing_param_CreateFcn(hObject, eventdata, handles)\n% hObject handle to smoothing_param (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in picket_num_pop.\nfunction picket_num_pop_Callback(hObject, eventdata, handles)\n% hObject handle to picket_num_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns picket_num_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from picket_num_pop\nv=get(handles.picket_num_pop, 'Value');\nset(handles.column_mlc, 'String', {1:v});\n\n% --- Executes during object creation, after setting all properties.\nfunction picket_num_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to picket_num_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in go_button.\nfunction go_button_Callback(hObject, eventdata, handles)\n% hObject handle to go_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.go_button, 'Enable', 'off');\nset(handles.column_mlc, 'Enable', 'on');\nset(handles.report_button, 'Enable', 'on');\n\nglobal img;\ndicomF2(handles,img);\n\nmin_data = get(handles.data_transfer_min, 'Data');\n\n[r,c]= size(min_data);\npickets = get(handles.picket_num_pop,'Value');\nset(handles.column_mlc, 'String',{1:pickets});\nset(handles.select_line, 'String',{1:r});\n\nglobal count;\ncount = count +1;\n\nfunction width_right_txt_Callback(hObject, eventdata, handles)\n% hObject handle to width_right_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of width_right_txt as text\n% str2double(get(hObject,'String')) returns contents of width_right_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction width_right_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to width_right_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction width_left_txt_Callback(hObject, eventdata, handles)\n% hObject handle to width_left_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of width_left_txt as text\n% str2double(get(hObject,'String')) returns contents of width_left_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction width_left_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to width_left_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in w2_pop.\nfunction w2_pop_Callback(hObject, eventdata, handles)\n% hObject handle to w2_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns w2_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from w2_pop\n\n\n% --- Executes during object creation, after setting all properties.\nfunction w2_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to w2_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in w1_pop.\nfunction w1_pop_Callback(hObject, eventdata, handles)\n% hObject handle to w1_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns w1_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from w1_pop\n\n\n% --- Executes during object creation, after setting all properties.\nfunction w1_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to w1_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in rotate_check.\nfunction rotate_check_Callback(hObject, eventdata, handles)\n% hObject handle to rotate_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of rotate_check\n\n\n% --- Executes on selection change in rotate_pop.\nfunction rotate_pop_Callback(hObject, eventdata, handles)\n% hObject handle to rotate_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns rotate_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from rotate_pop\n\nglobal img;\n\nv = get(handles.rotate_check, 'Value');\nif v ==1\n g = get(handles.rotate_pop, 'Value');\n if g == 2\n img = imrotate(img, 90);\n elseif g == 3\n img = imrotate(img, 180);\n elseif g == 4\n img = imrotate(img, 270);\n elseif g == 5\n img = imrotate(img, 360);\n end\nend\nimshow(img,'Parent',handles.axes1);\n\n% --- Executes during object creation, after setting all properties.\nfunction rotate_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to rotate_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in profile_check.\nfunction profile_check_Callback(hObject, eventdata, handles)\n% hObject handle to profile_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of profile_check\nglobal count;\nif count > 0 & get(handles.profile_check,'Value')== 1\n openfig('f_x.fig');\nend\n\n\n% --- Executes on button press in wiener_check.\nfunction wiener_check_Callback(hObject, eventdata, handles)\n% hObject handle to wiener_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of wiener_check\n\n\n% --- Executes on button press in home_button.\nfunction home_button_Callback(hObject, eventdata, handles)\n% hObject handle to home_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(picket_panda);\n%run('../qalma.m');\nrun('qalma')\n\n\n\nfunction mag_txt_Callback(hObject, eventdata, handles)\n% hObject handle to mag_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of mag_txt as text\n% str2double(get(hObject,'String')) returns contents of mag_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction mag_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to mag_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction res_txt_Callback(hObject, eventdata, handles)\n% hObject handle to res_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of res_txt as text\n% str2double(get(hObject,'String')) returns contents of res_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction res_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to res_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction level_txt_Callback(hObject, eventdata, handles)\n% hObject handle to level_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of level_txt as text\n% str2double(get(hObject,'String')) returns contents of level_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction level_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to level_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in profile_v_check.\nfunction profile_v_check_Callback(hObject, eventdata, handles)\n% hObject handle to profile_v_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of profile_v_check\nglobal count; \nif count > 0 & get(handles.profile_v_check,'Value')== 1\n if exist('f_y.fig', 'file')==2\n openfig('f_y.fig');\n end\nend\n\n\n% --- Executes when user attempts to close figure1.\nfunction figure1_CloseRequestFcn(hObject, eventdata, handles)\n% hObject handle to figure1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: delete(hObject) closes the figure\ndelete(hObject);\n\nif exist('f_x.fig', 'file')==2\n delete('f_x.fig');\nend\n\nif exist('f_y.fig', 'file')==2\n delete('f_y.fig');\nend\n\nif exist('f_x_s.fig', 'file')==2\n delete('f_x_s.fig');\nend\n\nif exist('f_x.fig', 'file')==2\n delete('f_x.fig');\nend\n\nif exist('edge_gaps.png', 'file')==2\n delete('edge_gaps.png');\nend\n\nif exist('current_positions.png', 'file')==2\n delete('current_positions.png');\nend\n\nclearvars; "} +{"plateform": "github", "repo_name": "mrmushfiq/qalma-master", "name": "dynalog.m", "ext": ".m", "path": "qalma-master/dynalog/dynalog.m", "size": 7639, "source_encoding": "utf_8", "md5": "5c135192ef465a4baa5b642159850bd1", "text": "% M. Mushfiqur Rahman\n% Florida Atlantic University\n% August, 2017\n\n\nfunction varargout = dynalog(varargin)\n% DYNALOG MATLAB code for dynalog.fig\n% DYNALOG, by itself, creates a new DYNALOG or raises the existing\n% singleton*.\n%\n% H = DYNALOG returns the handle to a new DYNALOG or the handle to\n% the existing singleton*.\n%\n% DYNALOG('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in DYNALOG.M with the given input arguments.\n%\n% DYNALOG('Property','Value',...) creates a new DYNALOG or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before dynalog_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to dynalog_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help dynalog\n\n% Last Modified by GUIDE v2.5 25-Aug-2017 22:37:45\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @dynalog_OpeningFcn, ...\n 'gui_OutputFcn', @dynalog_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before dynalog is made visible.\nfunction dynalog_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to dynalog (see VARARGIN)\n\n% Choose default command line output for dynalog\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes dynalog wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\nset(handles.axes1,'visible','off');\nset(handles.report_button,'visible','off');\nset(handles.comment_txt,'visible','off');\nset(handles.mag_panel, 'visible', 'off');\n\nset(handles.axes2,'visible','off');\nset(handles.axes3,'visible','off');\nset(handles.axes4,'visible','off');\nset(handles.mag_txt, 'String', '1');\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = dynalog_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in a_button.\nfunction a_button_Callback(hObject, eventdata, handles)\n% hObject handle to a_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal f_a;\nglobal p_a;\n[f_a p_a] = uigetfile(... \n {'*.dlg'},... \n 'MultiSelect', 'off');\nset(handles.file_a_txt, 'String', f_a);\n\n% --- Executes on button press in b_button.\nfunction b_button_Callback(hObject, eventdata, handles)\n% hObject handle to b_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal f_b;\nglobal p_b; \n[f_b p_b] = uigetfile(... \n {'*.dlg'},... \n 'MultiSelect', 'off');\nset(handles.file_b_txt, 'String', f_b);\n\n\n% --- Executes on button press in dynalyze_button.\nfunction dynalyze_button_Callback(hObject, eventdata, handles)\n% hObject handle to dynalyze_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal f_a;\nglobal p_a;\nglobal f_b;\nglobal p_b;\ndynalogF(handles, f_a, f_b, p_a, p_b);\n\n\n% --- Executes on button press in report_button.\nfunction report_button_Callback(hObject, eventdata, handles)\n% hObject handle to report_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\ntc = get(handles.comment_txt, 'String'); \ntc = strcat('Comment: ', tc);\n\nf2 = figure('Position', [100, 100, 724, 700]);\n[picket,map1] = imread('picket_dyn.png');\ntitle('Dynalog Report');\n\nh1=subplot(4,4,1:12); \nimshow(picket,[]);\naxis equal;\nh2=subplot(4,4,[14,15]);\ntext(0.3,1,tc); axis off;\n\nsaveas(f2,'Dynalog_Report.pdf');\n\n\n\nfunction comment_txt_Callback(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of comment_txt as text\n% str2double(get(hObject,'String')) returns contents of comment_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction comment_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in home_button.\nfunction home_button_Callback(hObject, eventdata, handles)\n% hObject handle to home_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(dynalog);\nrun('qalma');\n\n\n\nfunction mag_txt_Callback(hObject, eventdata, handles)\n% hObject handle to mag_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of mag_txt as text\n% str2double(get(hObject,'String')) returns contents of mag_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction mag_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to mag_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes when user attempts to close figure1.\nfunction figure1_CloseRequestFcn(hObject, eventdata, handles)\n% hObject handle to figure1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: delete(hObject) closes the figure\ndelete(hObject);\nif exist('picket_dyn.png', 'file')==2\n delete('picket_dyn.png');\nend\nclearvars;"} +{"plateform": "github", "repo_name": "mrmushfiq/qalma-master", "name": "wl.m", "ext": ".m", "path": "qalma-master/winston_lutz/wl.m", "size": 21479, "source_encoding": "utf_8", "md5": "5c9533af6cf6ffa9e93af23d9a8cf14a", "text": "% M. Mushfiqur Rahman\n% Florida Atlantic University\n% August, 2017\n\nfunction varargout = wl(varargin)\n% WL MATLAB code for wl.fig\n% WL, by itself, creates a new WL or raises the existing\n% singleton*.\n%\n% H = WL returns the handle to a new WL or the handle to\n% the existing singleton*.\n%\n% WL('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in WL.M with the given input arguments.\n%\n% WL('Property','Value',...) creates a new WL or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before wl_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to wl_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help wl\n\n% Last Modified by GUIDE v2.5 25-Aug-2017 22:33:26\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @wl_OpeningFcn, ...\n 'gui_OutputFcn', @wl_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before wl is made visible.\nfunction wl_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to wl (see VARARGIN)\n\n% Choose default command line output for wl\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes wl wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\nglobal mag_count;\nmag_count = 0; \n\nset(handles.radiation_slider, 'Min',0,'Max',100,'Value', 14);\nset(handles.ball_slider,'Min',0,'Max',100,'Value', 13);\nset(handles.ball_txt, 'String', 13);\nset(handles.radiation_txt, 'String', 14);\n\nset(handles.axes1, 'Visible', 'off');\nset(handles.axes2, 'Visible', 'off');\nset(handles.axes3, 'Visible', 'off');\n\n\nset(handles.radiation_slider, 'Visible', 'off');\nset(handles.radiation_txt, 'Visible', 'off');\nset(handles.ball_slider, 'Visible', 'off');\nset(handles.ball_txt, 'Visible', 'off');\nset(handles.text7, 'Visible', 'off');\n\nset(handles.original_label, 'Visible', 'off');\nset(handles.filter1_label, 'Visible', 'off');\nset(handles.filter2_label, 'Visible', 'off');\nset(handles.analyze_button, 'Visible', 'on');\n\nset(handles.distance_label, 'Visible', 'off');\nset(handles.distance_txt, 'Visible', 'off');\n\nset(handles.report_button, 'Visible', 'on');\n\nset(handles.uitable1, 'visible', 'off');\nset(handles.uitable1, 'Data', []);\nset(handles.uitable1, 'ColumnName', {'Image', 'Distance(mm)', 'Comment'});\n\nset(handles.mag_txt, 'String', '1');\nset(handles.res_txt, 'String', '0.34');\n\nset(handles.zoom_pop, 'String', {1:10}, 'Value', 6);\nset(handles.analyze_button, 'Enable', 'off');\nset(handles.report_button, 'Enable', 'off');\nset(handles.zoom_pop, 'Enable', 'off');\n\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = wl_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on slider movement.\nfunction ball_slider_Callback(hObject, eventdata, handles)\n% hObject handle to ball_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\nglobal img;\nglobal img_url; \n\nv = get(handles.ball_slider, 'Value');\nset(handles.ball_txt, 'String', num2str(v));\nwlF_loading(handles,img_url); \n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction ball_slider_CreateFcn(hObject, eventdata, handles)\n% hObject handle to ball_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n\nfunction ball_txt_Callback(hObject, eventdata, handles)\n% hObject handle to ball_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of ball_txt as text\n% str2double(get(hObject,'String')) returns contents of ball_txt as a double\nglobal img;\nglobal img_url; \n\ns= get(handles.ball_txt, 'String');\nset(handles.ball_slider, 'Value', str2num(s));\nwlF_loading(handles,img_url); \n\n\n% --- Executes during object creation, after setting all properties.\nfunction ball_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to ball_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on slider movement.\nfunction radiation_slider_Callback(hObject, eventdata, handles)\n% hObject handle to radiation_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\nglobal img;\nglobal img_url; \nv = get(handles.radiation_slider, 'Value');\nset(handles.radiation_txt, 'String', num2str(v));\nwlF_loading(handles,img_url); \n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction radiation_slider_CreateFcn(hObject, eventdata, handles)\n% hObject handle to radiation_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n\nfunction radiation_txt_Callback(hObject, eventdata, handles)\n% hObject handle to radiation_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of radiation_txt as text\n% str2double(get(hObject,'String')) returns contents of radiation_txt as a double\nglobal img;\nglobal img_url; \n\ns = get(handles.radiation_txt, 'String');\nset(handles.radiation_slider, 'Value', str2num(s));\nwlF_loading(handles,img_url); \n\n\n% --- Executes during object creation, after setting all properties.\nfunction radiation_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to radiation_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in load_button.\nfunction load_button_Callback(hObject, eventdata, handles)\n% hObject handle to load_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal img; \nglobal file_name; \nglobal img_url; \n[f p] = uigetfile(... \n {'*.dcm','Supported Files (*.dcm)'; ...\n },... \n 'MultiSelect', 'off');\n\ntry\n %img_d = imread([p f]);\n img_d = dicomread([p f]);\n img=im2double(img_d);\n img=uint8(255*mat2gray(img));\n\n file_name = f;\n\n set(handles.axes1, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]);\n set(handles.axes2, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]);\n set(handles.axes3, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]);\n\n set(handles.radiation_slider, 'Visible', 'on');\n set(handles.radiation_txt, 'Visible', 'on');\n set(handles.ball_slider, 'Visible', 'on');\n set(handles.ball_txt, 'Visible', 'on');\n\n set(handles.original_label, 'Visible', 'on');\n set(handles.filter1_label, 'Visible', 'on');\n set(handles.filter2_label, 'Visible', 'on');\n set(handles.analyze_button, 'Visible', 'on');\n\n set(handles.distance_label, 'Visible', 'on');\n set(handles.distance_txt, 'Visible', 'on');\n\n imshow(img,'Parent',handles.axes1);\n img_url = strcat(p,f);\n wlF_loading(handles,img_url); \n set(handles.analyze_button, 'Enable', 'on');\n set(handles.zoom_pop, 'Enable', 'on');\n\ncatch\n h = msgbox('Please upload an image');\nend\n\n\n% --- Executes on button press in analyze_button.\nfunction analyze_button_Callback(hObject, eventdata, handles)\n% hObject handle to analyze_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal img;\nglobal file_name;\nglobal img_url; \nset(handles.report_button, 'Visible', 'on');\nwlF(handles,img_url); \nset(handles.uitable1, 'visible', 'on');\nset(handles.load_button, 'Visible', 'off'); \nset(handles.text7, 'Visible', 'on');\nset(handles.report_button, 'Enable', 'on');\n\n\nD = get(handles.uitable1, 'Data');\n\n[r,c] = size(D);\nD{r+1,1} = file_name; \nD{r+1,2} = get(handles.distance_txt, 'String'); \nD{r+1,3} = get(handles.comment_txt, 'String');\n\nset(handles.uitable1, 'Data', D);\nset(handles.row_pop, 'String', {1:r+1});\n\n% --- Executes on button press in instructions_button.\nfunction instructions_button_Callback(hObject, eventdata, handles)\n% hObject handle to instructions_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in report_button.\nfunction report_button_Callback(hObject, eventdata, handles)\n% hObject handle to report_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\nframe = getframe(handles.axes1);\nimf = frame2im(frame);\n%imwrite(imf, 'wl_result.png');\ntc = get(handles.comment_txt, 'String'); \ntc = strcat('Comment : ', tc);\ndist = get(handles.distance_txt, 'String');\ndist = strcat('Distance between the centers : ', dist);\ntexts = {dist,' ', tc};\n\nD = get(handles.uitable1, 'Data');\n\n\nf1=figure\nt = uitable(f1,'Data',D,'Position',[20 60 400 300]);\nt.ColumnName = {'Image','Distance(mm)','Comment'};\n\n\nsaveas(f1, 'wl_report.pdf')\n\n\nfunction comment_txt_Callback(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of comment_txt as text\n% str2double(get(hObject,'String')) returns contents of comment_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction comment_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in add_image.\nfunction add_image_Callback(hObject, eventdata, handles)\n% hObject handle to add_image (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal img; \nglobal file_name;\nglobal img_url; \n\n[f p] = uigetfile(... \n {'*.dcm','Supported Files (*.dcm)'; ...\n },... \n 'MultiSelect', 'off');\n\n\n% [f p] = uigetfile(... \n% {'*.jpg; *.JPG; *.jpeg; *.JPEG; *.img; *.IMG; *.tif;*.png; .dcm;*.TIF; *.tiff, *.TIFF','Supported Files (*.dcm,*.jpg,*.img,*.tiff,*.png)'; ...\n% '*.jpg','jpg Files (*.jpg)';...\n% '*.JPG','JPG Files (*.JPG)';...\n% '*.jpeg','jpeg Files (*.jpeg)';...\n% '*.JPEG','JPEG Files (*.JPEG)';...\n% '*.img','img Files (*.img)';...\n% '*.IMG','IMG Files (*.IMG)';...\n% '*.tif','tif Files (*.tif)';...\n% '*.TIF','TIF Files (*.TIF)';...\n% '*.tiff','tiff Files (*.tiff)';...\n% '*.TIFF','TIFF Files (*.TIFF)'},... \n% 'MultiSelect', 'off');\n\ntry\n %img_d = imread([p f]);\n img_d = dicomread([p f]);\n img=im2double(img_d);\n img=uint8(255*mat2gray(img));\n file_name = f; \n\n set(handles.axes1, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]);\n set(handles.axes2, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]);\n set(handles.axes3, 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]);\n\n set(handles.radiation_slider, 'Visible', 'on');\n set(handles.radiation_txt, 'Visible', 'on');\n set(handles.ball_slider, 'Visible', 'on');\n set(handles.ball_txt, 'Visible', 'on');\n\n set(handles.original_label, 'Visible', 'on');\n set(handles.filter1_label, 'Visible', 'on');\n set(handles.filter2_label, 'Visible', 'on');\n set(handles.analyze_button, 'Visible', 'on');\n\n set(handles.distance_label, 'Visible', 'on');\n set(handles.distance_txt, 'Visible', 'on');\n\n imshow(img,'Parent',handles.axes1);\n img_url = strcat(p,f);\n wlF_loading(handles,img_url); \n set(handles.analyze_button, 'Enable', 'on');\n set(handles.zoom_pop, 'Enable', 'on');\n\n\ncatch\n h = msgbox('Please upload an image');\nend\n\n\n\nfunction res_txt_Callback(hObject, eventdata, handles)\n% hObject handle to res_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of res_txt as text\n% str2double(get(hObject,'String')) returns contents of res_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction res_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to res_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction mag_txt_Callback(hObject, eventdata, handles)\n% hObject handle to mag_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of mag_txt as text\n% str2double(get(hObject,'String')) returns contents of mag_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction mag_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to mag_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction edit8_Callback(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of comment_txt as text\n% str2double(get(hObject,'String')) returns contents of comment_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction edit8_CreateFcn(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in home_button.\nfunction home_button_Callback(hObject, eventdata, handles)\n% hObject handle to home_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(wl);\nrun('qalma');\n\n\n% --- Executes on selection change in zoom_pop.\nfunction zoom_pop_Callback(hObject, eventdata, handles)\n% hObject handle to zoom_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns zoom_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from zoom_pop\nglobal img;\nglobal img_url; \n\nwlF_loading(handles,img_url); \n\n\n% --- Executes during object creation, after setting all properties.\nfunction zoom_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to zoom_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in pushbutton15.\nfunction pushbutton15_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton15 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n% --- Executes on button press in delete_button.\nfunction delete_button_Callback(hObject, eventdata, handles)\n% hObject handle to delete_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nD = get(handles.uitable1, 'Data');\n\n[r,c] = size(D);\nrow = get(handles.row_pop, 'Value');\n\nif r>0\n D(row,:) = [];\nend\n\nset(handles.uitable1, 'Data', D);\n\n\n% --- Executes on selection change in row_pop.\nfunction row_pop_Callback(hObject, eventdata, handles)\n% hObject handle to row_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns row_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from row_pop\n\n\n% --- Executes during object creation, after setting all properties.\nfunction row_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to row_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes when user attempts to close figure1.\nfunction figure1_CloseRequestFcn(hObject, eventdata, handles)\n% hObject handle to figure1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: delete(hObject) closes the figure\ndelete(hObject);\nclearvars;"} +{"plateform": "github", "repo_name": "mrmushfiq/qalma-master", "name": "ci.m", "ext": ".m", "path": "qalma-master/ci/ci.m", "size": 25849, "source_encoding": "utf_8", "md5": "bda1d740da1c89b97e876fc2f9ffe66e", "text": "% M. Mushfiqur Rahman\n% Florida Atlantic University\n% August, 2017\n\nfunction varargout = ci(varargin)\n% CI MATLAB code for ci.fig\n% CI, by itself, creates a new CI or raises the existing\n% singleton*.\n%\n% H = CI returns the handle to a new CI or the handle to\n% the existing singleton*.\n%\n% CI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in CI.M with the given input arguments.\n%\n% CI('Property','Value',...) creates a new CI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before ci_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to ci_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help ci\n\n% Last Modified by GUIDE v2.5 31-Aug-2017 18:50:29\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @ci_OpeningFcn, ...\n 'gui_OutputFcn', @ci_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before ci is made visible.\nfunction ci_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to ci (see VARARGIN)\n\n% Choose default command line output for ci\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes ci wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\nset(handles.bbs_txt, 'Visible', 'off');\n\nsetpixelposition(handles.radius1_pop,[3, 10, 70, 40]);\nsetpixelposition(handles.radius2_pop,[87, 10, 70, 40]);\n\nsetpixelposition(handles.w_1_pop,[79, 5, 70, 40]);\nsetpixelposition(handles.w_2_pop,[153, 5, 70, 40]);\n\nset(handles.axes1,... \n 'Visible', 'on', 'box','off','XTickLabel',[],'XTick',[],'YTickLabel',[],'YTick',[]);\n \nset(handles.wiener_check,'Value', 1);\nset(handles.dark_check,'Value', 1); \nset(handles.w_1_pop, 'string', {1:10}, 'Value', 5);\nset(handles.w_2_pop, 'string', {1:10}, 'Value', 5);\n\nset(handles.radius1_pop, 'string', {1:20}, 'Value', 1, 'Visible' , 'on');\nset(handles.radius2_pop, 'string', {1:20}, 'Value', 3, 'Visible' , 'on');\n\nset(handles.sensitivity_slider, 'SliderStep', [0.01, 0.1], 'Value', 0.94);\nset(handles.threshold_slider, 'SliderStep', [0.01, 0.1], 'Value', 0.14);\n\nset(handles.sensitivity_txt, 'String', '0.94');\nset(handles.threshold_txt, 'String', '0.14');\n\nset(handles.contrast_low_slider,'Min', 0, 'Max', 1, 'SliderStep', [0.01, 0.1], 'Value', 0);\nset(handles.contrast_high_slider, 'Min', 0, 'Max', 1,'SliderStep', [0.01, 0.1], 'Value', 0.8);\n\nset(handles.contrast_low_txt, 'String', '0');\nset(handles.contrast_high_txt, 'String', '0.8');\n\nset(handles.contrast_low_txt, 'Enable', 'off');\nset(handles.contrast_high_txt, 'Enable', 'off');\nset(handles.contrast_low_slider, 'Enable', 'off');\nset(handles.contrast_high_slider, 'Enable', 'off');\nset(handles.sensitivity_txt, 'Enable', 'off');\nset(handles.threshold_txt, 'Enable', 'off');\nset(handles.sensitivity_slider, 'Enable', 'off');\nset(handles.threshold_slider, 'Enable', 'off');\nset(handles.radius1_pop, 'Enable', 'off');\nset(handles.radius2_pop, 'Enable', 'off');\nset(handles.dark_check,'Enable', 'off'); \nset(handles.bright_check,'Enable', 'off'); \nset(handles.analyze_button, 'Enable', 'off');\nset(handles.add_button, 'Enable', 'off');\nset(handles.wiener_check, 'Enable','off');\nset(handles.w_1_pop, 'Enable','off');\nset(handles.w_2_pop, 'Enable','off');\nset(handles.manual_check, 'Enable','off');\nset(handles.reset_button, 'Enable', 'off');\n\nset(handles.text5, 'Visible', 'off');\nset(handles.dice_txt, 'Visible', 'off'); \n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = ci_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n\n\n% --- Executes on button press in load_button.\nfunction load_button_Callback(hObject, eventdata, handles)\n% hObject handle to load_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal img;\nglobal img_url;\n[f p] = uigetfile({'*.dcm','DICOM Files'});\n\ntry\n img_d = dicomread([p f]);\n img=im2double(img_d);\n img=uint8(255*mat2gray(img));\n\n imshow(img,'Parent',handles.axes1);\n img_url = strcat(p,f);\n\n ci_loadingF(handles,img_url);\n \n set(handles.contrast_low_txt, 'Enable', 'on');\n set(handles.contrast_high_txt, 'Enable', 'on');\n set(handles.contrast_low_slider, 'Enable', 'on');\n set(handles.contrast_high_slider, 'Enable', 'on');\n set(handles.sensitivity_txt, 'Enable', 'on');\n set(handles.threshold_txt, 'Enable', 'on');\n set(handles.sensitivity_slider, 'Enable', 'on');\n set(handles.threshold_slider, 'Enable', 'on');\n set(handles.radius1_pop, 'Enable', 'on');\n set(handles.radius2_pop, 'Enable', 'on');\n set(handles.dark_check,'Enable', 'on'); \n set(handles.bright_check,'Enable', 'on'); \n set(handles.analyze_button, 'Enable', 'on');\n set(handles.wiener_check, 'Enable','on');\n set(handles.w_1_pop, 'Enable','on');\n set(handles.w_2_pop, 'Enable','on');\n set(handles.manual_check, 'Enable','on');\n set(handles.reset_button, 'Enable', 'on');\n set(handles.text5, 'Visible', 'off');\n set(handles.dice_txt, 'Visible', 'off'); \n\ncatch\n h = msgbox('Please upload an image');\nend\n\n \n% --- Executes on button press in analyze_button.\nfunction analyze_button_Callback(hObject, eventdata, handles)\n% hObject handle to analyze_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.analyze_button, 'Enable', 'off');\nglobal img_url;\nciF(handles,img_url); \nset(handles.load_button, 'Visible', 'off');\nset(handles.add_button, 'Enable', 'on');\nset(handles.text5, 'Visible', 'on');\nset(handles.dice_txt, 'Visible', 'on'); \n\n\n% --- Executes on button press in add_button.\nfunction add_button_Callback(hObject, eventdata, handles)\n% hObject handle to add_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nglobal img;\nglobal img_url;\n[f p] = uigetfile({'*.dcm','DICOM Files'});\n\ntry\n img_d = dicomread([p f]);\n img=im2double(img_d);\n img=uint8(255*mat2gray(img));\n\n imshow(img,'Parent',handles.axes1);\n img_url = strcat(p,f);\n\n ci_loadingF(handles,img_url);\n set(handles.analyze_button, 'Enable', 'on');\n set(handles.text5, 'Visible', 'off');\n set(handles.dice_txt, 'Visible', 'off'); \n\n \ncatch\n h = msgbox('Please upload an image');\nend\n\n\n% --- Executes on selection change in radius2_pop.\nfunction radius2_pop_Callback(hObject, eventdata, handles)\n% hObject handle to radius2_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns radius2_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from radius2_pop\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction radius2_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to radius2_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in radius1_pop.\nfunction radius1_pop_Callback(hObject, eventdata, handles)\n% hObject handle to radius1_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns radius1_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from radius1_pop\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction radius1_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to radius1_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n\nfunction comment_txt_Callback(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of comment_txt as text\n% str2double(get(hObject,'String')) returns contents of comment_txt as a double\n\n\n% --- Executes during object creation, after setting all properties.\nfunction comment_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to comment_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on slider movement.\nfunction contrast_high_slider_Callback(hObject, eventdata, handles)\n% hObject handle to contrast_high_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get(handles.contrast_high_slider, 'Value');\nset(handles.contrast_high_txt, 'String', num2str(a));\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction contrast_high_slider_CreateFcn(hObject, eventdata, handles)\n% hObject handle to contrast_high_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n\nfunction contrast_high_txt_Callback(hObject, eventdata, handles)\n% hObject handle to contrast_high_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of contrast_high_txt as text\n% str2double(get(hObject,'String')) returns contents of contrast_high_txt as a double\na = get(handles.contrast_high_txt, 'String');\nset(handles.contrast_high_slider, 'Value', str2num(a));\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction contrast_high_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to contrast_high_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in wiener_check.\nfunction wiener_check_Callback(hObject, eventdata, handles)\n% hObject handle to wiener_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of wiener_check\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes on selection change in w_1_pop.\nfunction w_1_pop_Callback(hObject, eventdata, handles)\n% hObject handle to w_1_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns w_1_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from w_1_pop\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction w_1_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to w_1_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on selection change in w_2_pop.\nfunction w_2_pop_Callback(hObject, eventdata, handles)\n% hObject handle to w_2_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: contents = cellstr(get(hObject,'String')) returns w_2_pop contents as cell array\n% contents{get(hObject,'Value')} returns selected item from w_2_pop\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction w_2_pop_CreateFcn(hObject, eventdata, handles)\n% hObject handle to w_2_pop (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: popupmenu controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on slider movement.\nfunction threshold_slider_Callback(hObject, eventdata, handles)\n% hObject handle to threshold_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get(handles.threshold_slider, 'Value');\nset(handles.threshold_txt, 'String', num2str(a));\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction threshold_slider_CreateFcn(hObject, eventdata, handles)\n% hObject handle to threshold_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n\nfunction threshold_txt_Callback(hObject, eventdata, handles)\n% hObject handle to threshold_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of threshold_txt as text\n% str2double(get(hObject,'String')) returns contents of threshold_txt as a double\na = get(handles.threshold_txt, 'String');\nset(handles.threshold_slider, 'Value', str2num(a));\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction threshold_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to threshold_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on slider movement.\nfunction sensitivity_slider_Callback(hObject, eventdata, handles)\n% hObject handle to sensitivity_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get(handles.sensitivity_slider, 'Value');\nset(handles.sensitivity_txt, 'String', num2str(a));\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction sensitivity_slider_CreateFcn(hObject, eventdata, handles)\n% hObject handle to sensitivity_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n\nfunction sensitivity_txt_Callback(hObject, eventdata, handles)\n% hObject handle to sensitivity_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of sensitivity_txt as text\n% str2double(get(hObject,'String')) returns contents of sensitivity_txt as a double\na = get(handles.sensitivity_txt,'String');\nset(handles.sensitivity_slider, 'Value', str2num(a));\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction sensitivity_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to sensitivity_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in dark_check.\nfunction dark_check_Callback(hObject, eventdata, handles)\n% hObject handle to dark_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of dark_check\nset(handles.bright_check, 'Value', 0);\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes on button press in bright_check.\nfunction bright_check_Callback(hObject, eventdata, handles)\n% hObject handle to bright_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of bright_check\nset(handles.dark_check, 'Value', 0);\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes on slider movement.\nfunction contrast_low_slider_Callback(hObject, eventdata, handles)\n% hObject handle to contrast_low_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'Value') returns position of slider\n% get(hObject,'Min') and get(hObject,'Max') to determine range of slider\na = get(handles.contrast_low_slider, 'Value');\nset(handles.contrast_low_txt, 'String', num2str(a));\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction contrast_low_slider_CreateFcn(hObject, eventdata, handles)\n% hObject handle to contrast_low_slider (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: slider controls usually have a light gray background.\nif isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor',[.9 .9 .9]);\nend\n\n\n\nfunction contrast_low_txt_Callback(hObject, eventdata, handles)\n% hObject handle to contrast_low_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hints: get(hObject,'String') returns contents of contrast_low_txt as text\n% str2double(get(hObject,'String')) returns contents of contrast_low_txt as a double\na = get(handles.contrast_low_txt, 'String');\nset(handles.contrast_low_slider, 'Value', str2num(a));\n\nglobal img_url;\nci_loadingF(handles,img_url);\n\n% --- Executes during object creation, after setting all properties.\nfunction contrast_low_txt_CreateFcn(hObject, eventdata, handles)\n% hObject handle to contrast_low_txt (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles empty - handles not created until after all CreateFcns called\n\n% Hint: edit controls usually have a white background on Windows.\n% See ISPC and COMPUTER.\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in home_button.\nfunction home_button_Callback(hObject, eventdata, handles)\n% hObject handle to home_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nclose(ci);\nrun('qalma');\n\n\n% --- Executes on button press in manual_check.\nfunction manual_check_Callback(hObject, eventdata, handles)\n% hObject handle to manual_check (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: get(hObject,'Value') returns toggle state of manual_check\nglobal img_url;\n\nif get(handles.manual_check, 'Value') == 1\n h = msgbox('Please click on the BBs after clicking the analyze button');\n try\n ci_loadingF(handles,img_url);\n catch\n h1 = msgbox('Please load an image first');\n end\nelse\n try\n ci_loadingF(handles,img_url);\n catch\n h1 = msgbox('Please load an image first');\n end \nend\n\n\n% --- Executes when user attempts to close figure1.\nfunction figure1_CloseRequestFcn(hObject, eventdata, handles)\n% hObject handle to figure1 (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Hint: delete(hObject) closes the figure\ndelete(hObject);\nclearvars;\n\n\n% --- Executes on button press in reset_button.\nfunction reset_button_Callback(hObject, eventdata, handles)\n% hObject handle to reset_button (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\nset(handles.wiener_check,'Value', 1);\nset(handles.dark_check,'Value', 1); \nset(handles.w_1_pop, 'string', {1:10}, 'Value', 5);\nset(handles.w_2_pop, 'string', {1:10}, 'Value', 5);\n\nset(handles.radius1_pop, 'string', {1:20}, 'Value', 1, 'Visible' , 'on');\nset(handles.radius2_pop, 'string', {1:20}, 'Value', 3, 'Visible' , 'on');\n\nset(handles.sensitivity_slider, 'SliderStep', [0.01, 0.1], 'Value', 0.94);\nset(handles.threshold_slider, 'SliderStep', [0.01, 0.1], 'Value', 0.14);\n\nset(handles.sensitivity_txt, 'String', '0.94');\nset(handles.threshold_txt, 'String', '0.14');\n\nset(handles.contrast_low_slider,'Min', 0, 'Max', 1, 'SliderStep', [0.01, 0.1], 'Value', 0);\nset(handles.contrast_high_slider, 'Min', 0, 'Max', 1,'SliderStep', [0.01, 0.1], 'Value', 0.8);\n\nset(handles.contrast_low_txt, 'String', '0');\nset(handles.contrast_high_txt, 'String', '0.8');\n\nset(handles.text5, 'Visible', 'off');\nset(handles.dice_txt, 'Visible', 'off'); \n\nglobal img_url;\nci_loadingF(handles,img_url);\n"} +{"plateform": "github", "repo_name": "andyzeng/arc-robot-vision-master", "name": "fill_depth_cross_bf.m", "ext": ".m", "path": "arc-robot-vision-master/suction-based-grasping/external/bxf/fill_depth_cross_bf.m", "size": 1990, "source_encoding": "utf_8", "md5": "b7e5bbcb1bedcb7426978f7df1777af9", "text": "% In-paints the depth image using a cross-bilateral filter. The operation \n% is implemented via several filterings at various scales. The number of\n% scales is determined by the number of spacial and range sigmas provided.\n% 3 spacial/range sigmas translated into filtering at 3 scales.\n%\n% Args:\n% imgRgb - the RGB image, a uint8 HxWx3 matrix\n% imgDepthAbs - the absolute depth map, a HxW double matrix whose values\n% indicate depth in meters.\n% spaceSigmas - (optional) sigmas for the spacial gaussian term.\n% rangeSigmas - (optional) sigmas for the intensity gaussian term.\n%\n% Returns:\n% imgDepthAbs - the inpainted depth image.\nfunction imgDepthAbs = fill_depth_cross_bf(imgRgb, imgDepthAbs, ...\n spaceSigmas, rangeSigmas)\n \n error(nargchk(2,4,nargin));\n assert(isa(imgRgb, 'uint8'), 'imgRgb must be uint8');\n assert(isa(imgDepthAbs, 'double'), 'imgDepthAbs must be a double');\n\n if nargin < 3\n %spaceSigmas = [ 12];\n spaceSigmas = [12 5 8];\n end\n if nargin < 4\n % rangeSigmas = [0.2];\n rangeSigmas = [0.2 0.08 0.02];\n end\n \n assert(numel(spaceSigmas) == numel(rangeSigmas));\n assert(isa(rangeSigmas, 'double'));\n assert(isa(spaceSigmas, 'double'));\n \n % Create the 'noise' image and get the maximum observed depth.\n imgIsNoise = imgDepthAbs == 0 | imgDepthAbs == 10;\n maxDepthObs = max(imgDepthAbs(~imgIsNoise));\n \n % If depth map is empty, exit function\n if isempty(maxDepthObs)\n return; \n end\n \n % Convert the depth image to uint8.\n imgDepth = imgDepthAbs ./ maxDepthObs;\n imgDepth(imgDepth > 1) = 1;\n imgDepth = uint8(imgDepth * 255);\n \n % Run the cross-bilateral filter.\n if ispc\n imgDepthAbs = mex_cbf_windows(imgDepth, rgb2gray(imgRgb), imgIsNoise, spaceSigmas(:), rangeSigmas(:));\n else\n imgDepthAbs = mex_cbf(imgDepth, rgb2gray(imgRgb), imgIsNoise, spaceSigmas(:), rangeSigmas(:));\n end\n \n % Convert back to absolute depth (meters).\n imgDepthAbs = im2double(imgDepthAbs) .* maxDepthObs;\nend"} +{"plateform": "github", "repo_name": "andyzeng/arc-robot-vision-master", "name": "sub2ind2d.m", "ext": ".m", "path": "arc-robot-vision-master/parallel-jaw-grasping/baseline/sub2ind2d.m", "size": 135, "source_encoding": "utf_8", "md5": "4970286e0c7d89b91364ca0d54668cff", "text": "% A faster version of sub2ind for 2D case\nfunction linIndex = sub2ind2d(sz, rowSub, colSub)\n linIndex = (colSub-1) * sz(1) + rowSub;\n\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "addSubFoldersToPath.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/addSubFoldersToPath.m", "size": 792, "source_encoding": "utf_8", "md5": "1e9a817e1ab0ef5e56a1b36ec9f9397c", "text": "function addSubFoldersToPath()\n\npathOfThisFunction = mfilename('fullpath');\n[currentpath, ~, ~]= fileparts(pathOfThisFunction);\nallSubpaths = strsplit( genpath(currentpath) ,':');\nblacklist={'.git','.ignore','.graffle','.'}; % '.' is any hidden folder\n\npathsToAdd={};\nfor n=1:numel(allSubpaths)\n\tif shouldAddThisPath(allSubpaths{1,n},blacklist)\n\t\tpathsToAdd{end+1} = allSubpaths{n};\n\tend\nend\n\ndisp('Temporarily adding toolbox subdirecties to the path: ')\nfprintf('\\t%s\\n',pathsToAdd{:})\naddpath( strjoin(pathsToAdd, ':') )\nend\n\nfunction addThisPath = shouldAddThisPath(path,blacklist)\naddThisPath = true;\nfor ignoreStr = blacklist\n\tif isStringMatch(path,ignoreStr{1})\n\t\taddThisPath=false;\n\tend\nend\nend\n\nfunction matchFound = isStringMatch(str,pattern)\nmatchFound = ~strfind(str,pattern);\nend\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "checkGitHubDependencies.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/checkGitHubDependencies.m", "size": 2973, "source_encoding": "utf_8", "md5": "30b69fd5ee94882628374c7dbfc419ea", "text": "function checkGitHubDependencies(dependencies)\n% This function takes a cell array of url's to hithub repositories, loop through\n% them and ensure they exist on the path, or clone them to your local machine.\n%\n% Example input:\n%\n% dependencies={...\n% \t'https://github.com/drbenvincent/mcmc-utils-matlab',...\n% \t'https://github.com/altmany/export_fig'};\n\nassert(iscellstr(dependencies),'Input to function should be a cell array of url''s to github repositories')\n\n% ensure dependencies is a row\nif iscolumn(dependencies)\n\tdependencies = dependencies';\nend\nassert(isrow(dependencies))\n\nfor url=dependencies\n\tprocessDependency(url{:});\nend\n\nend\n\n\nfunction processDependency(url)\ndisplayDependencyToCommandWindow(url);\nrepoName = getRepoNameFromUrl(url);\nif ~isRepoFolderOnPath(repoName)\n\ttargetPath = fullfile(defineInstallPath(),repoName);\n\ttargetPath = removeTrailingColon(targetPath);\n\tcloneGitHubRepo(url, repoName, targetPath);\nelse\n\tupdateGitHubRepo(defineInstallPath(),repoName);\nend\nend\n\nfunction displayDependencyToCommandWindow(url)\ndisp( makeHyperlink(url, makeWeblinkCode(url)) )\nend\n\nfunction repoName = getRepoNameFromUrl(url)\n[~,repoName] = fileparts(url);\nend\n\nfunction installPath = defineInstallPath()\n% installPath will be the Matlab userpath (eg /Users/Username/Documents/MATLAB)\nif isempty(userpath)\n\tuserpath('reset')\nend\ninstallPath = userpath;\n% Fix the trailing \":\" which only sometimes appears (or \";\" on PC)\ninstallPath = removeTrailingColon(installPath);\nend\n\nfunction str = removeTrailingColon(str)\nif str(end)==systemDelimiter()\n\tstr(end)='';\nend\nend\n\nfunction onPath = isRepoFolderOnPath(repoName)\n\tonPath = exist(repoName,'dir')==7;\nend\n\nfunction cloneGitHubRepo(repoAddress, repoName, installPath)\n% ensure the folder exists\n%targetPath = removeTrailingColon(fullfile(defineInstallPath(),repoName));\nensureFolderExists(installPath);\naddpath(installPath);\n% do the cloning\noriginalPath = cd;\ntry\n\tcd(defineInstallPath())\n\tcommand = sprintf('git clone %s.git', repoAddress);\n\t[status, cmdout] = system(command);\ncatch ME\n\trethrow(ME)\nend\ncd(originalPath)\nend\n\nfunction updateGitHubRepo(installPath,repoName)\noriginalPath = cd;\ntry\n\tcd(fullfile(installPath,repoName))\n\t[status, cmdout] = system('git pull');\ncatch ME\n\trethrow(ME)\n\t%warning('Unable to update GitHub repository')\nend\ncd(originalPath)\nend\n\nfunction weblinkCode = makeWeblinkCode(url)\nassert(ischar(url))\nweblinkCode = sprintf('web(''%s'')', url);\nend\n\nfunction hyperlink = makeHyperlink(text, codeToRun)\nassert(ischar(text))\nassert(ischar(codeToRun))\ncodeToRun = ['matlab: ' codeToRun];\nhyperlink = sprintf('%s', codeToRun, text);\nend\n\nfunction delimiter = systemDelimiter()\nif ismac\n\t\tdelimiter = ':';\n\telseif ispc\n\t\tdelimiter = ';';\nend\nend\n\n% TODO: Work out how to make this work in Matlab\n% function results = exectuteFunctionInPathProvided(func, targetPath)\n% originalPath = cd;\n% cd(targetPath)\n% results = func();\n% cd(originalPath)\n% end\n\n\n\n\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "pdftops.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/pdftops.m", "size": 6161, "source_encoding": "utf_8", "md5": "5edac4bbbdae30223cb246a4ec7313d6", "text": "function varargout = pdftops(cmd)\r\n%PDFTOPS Calls a local pdftops executable with the input command\r\n%\r\n% Example:\r\n% [status result] = pdftops(cmd)\r\n%\r\n% Attempts to locate a pdftops executable, finally asking the user to\r\n% specify the directory pdftops was installed into. The resulting path is\r\n% stored for future reference.\r\n% \r\n% Once found, the executable is called with the input command string.\r\n%\r\n% This function requires that you have pdftops (from the Xpdf package)\r\n% installed on your system. You can download this from:\r\n% http://www.foolabs.com/xpdf\r\n%\r\n% IN:\r\n% cmd - Command string to be passed into pdftops (e.g. '-help').\r\n%\r\n% OUT:\r\n% status - 0 iff command ran without problem.\r\n% result - Output from pdftops.\r\n\r\n% Copyright: Oliver Woodford, 2009-2010\r\n\r\n% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.\r\n% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path under linux.\r\n% 23/01/2014 - Add full path to pdftops.txt in warning.\r\n% 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation\r\n% 02/05/2016 - Added possible error explanation suggested by Michael Pacer (issue #137)\r\n% 02/05/2016 - Search additional possible paths suggested by Jonas Stein (issue #147)\r\n% 03/05/2016 - Display the specific error message if pdftops fails for some reason (issue #148)\r\n\r\n % Call pdftops\r\n [varargout{1:nargout}] = system([xpdf_command(xpdf_path()) cmd]);\r\nend\r\n\r\nfunction path_ = xpdf_path\r\n % Return a valid path\r\n % Start with the currently set path\r\n path_ = user_string('pdftops');\r\n % Check the path works\r\n if check_xpdf_path(path_)\r\n return\r\n end\r\n % Check whether the binary is on the path\r\n if ispc\r\n bin = 'pdftops.exe';\r\n else\r\n bin = 'pdftops';\r\n end\r\n if check_store_xpdf_path(bin)\r\n path_ = bin;\r\n return\r\n end\r\n % Search the obvious places\r\n if ispc\r\n paths = {'C:\\Program Files\\xpdf\\pdftops.exe', 'C:\\Program Files (x86)\\xpdf\\pdftops.exe'};\r\n else\r\n paths = {'/usr/bin/pdftops', '/usr/local/bin/pdftops'};\r\n end\r\n for a = 1:numel(paths)\r\n path_ = paths{a};\r\n if check_store_xpdf_path(path_)\r\n return\r\n end\r\n end\r\n\r\n % Ask the user to enter the path\r\n errMsg1 = 'Pdftops not found. Please locate the program, or install xpdf-tools from ';\r\n url1 = 'http://foolabs.com/xpdf';\r\n fprintf(2, '%s\\n', [errMsg1 '' url1 '']);\r\n errMsg1 = [errMsg1 url1];\r\n %if strncmp(computer,'MAC',3) % Is a Mac\r\n % % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title\r\n % uiwait(warndlg(errMsg1))\r\n %end\r\n\r\n % Provide an alternative possible explanation as per issue #137\r\n errMsg2 = 'If you have pdftops installed, perhaps Matlab is shaddowing it as described in ';\r\n url2 = 'https://github.com/altmany/export_fig/issues/137';\r\n fprintf(2, '%s\\n', [errMsg2 'issue #137']);\r\n errMsg2 = [errMsg2 url1];\r\n\r\n state = 0;\r\n while 1\r\n if state\r\n option1 = 'Install pdftops';\r\n else\r\n option1 = 'Issue #137';\r\n end\r\n answer = questdlg({errMsg1,'',errMsg2},'Pdftops error',option1,'Locate pdftops','Cancel','Cancel');\r\n drawnow; % prevent a Matlab hang: http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem\r\n switch answer\r\n case 'Install pdftops'\r\n web('-browser',url1);\r\n case 'Issue #137'\r\n web('-browser',url2);\r\n state = 1;\r\n case 'Locate pdftops'\r\n base = uigetdir('/', errMsg1);\r\n if isequal(base, 0)\r\n % User hit cancel or closed window\r\n break\r\n end\r\n base = [base filesep]; %#ok\r\n bin_dir = {'', ['bin' filesep], ['lib' filesep]};\r\n for a = 1:numel(bin_dir)\r\n path_ = [base bin_dir{a} bin];\r\n if exist(path_, 'file') == 2\r\n break\r\n end\r\n end\r\n if check_store_xpdf_path(path_)\r\n return\r\n end\r\n\r\n otherwise % User hit Cancel or closed window\r\n break\r\n end\r\n end\r\n error('pdftops executable not found.');\r\nend\r\n\r\nfunction good = check_store_xpdf_path(path_)\r\n % Check the path is valid\r\n good = check_xpdf_path(path_);\r\n if ~good\r\n return\r\n end\r\n % Update the current default path to the path found\r\n if ~user_string('pdftops', path_)\r\n warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));\r\n return\r\n end\r\nend\r\n\r\nfunction good = check_xpdf_path(path_)\r\n % Check the path is valid\r\n [good, message] = system([xpdf_command(path_) '-h']); %#ok\r\n % system returns good = 1 even when the command runs\r\n % Look for something distinct in the help text\r\n good = ~isempty(strfind(message, 'PostScript'));\r\n\r\n % Display the error message if the pdftops executable exists but fails for some reason\r\n if ~good && exist(path_,'file') % file exists but generates an error\r\n fprintf('Error running %s:\\n', path_);\r\n fprintf(2,'%s\\n\\n',message);\r\n end\r\nend\r\n\r\nfunction cmd = xpdf_command(path_)\r\n % Initialize any required system calls before calling ghostscript\r\n % TODO: in Unix/Mac, find a way to determine whether to use \"export\" (bash) or \"setenv\" (csh/tcsh)\r\n shell_cmd = '';\r\n if isunix\r\n % Avoids an error on Linux with outdated MATLAB lib files\r\n % R20XXa/bin/glnxa64/libtiff.so.X\r\n % R20XXa/sys/os/glnxa64/libstdc++.so.X\r\n shell_cmd = 'export LD_LIBRARY_PATH=\"\"; ';\r\n end\r\n if ismac\r\n shell_cmd = 'export DYLD_LIBRARY_PATH=\"\"; ';\r\n end\r\n % Construct the command string\r\n cmd = sprintf('%s\"%s\" ', shell_cmd, path_);\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "crop_borders.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/crop_borders.m", "size": 5133, "source_encoding": "utf_8", "md5": "b744bf935914cfa6d9ff82140b48291e", "text": "function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding, crop_amounts)\r\n%CROP_BORDERS Crop the borders of an image or stack of images\r\n%\r\n% [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])\r\n%\r\n%IN:\r\n% A - HxWxCxN stack of images.\r\n% bcol - Cx1 background colour vector.\r\n% padding - scalar indicating how much padding to have in relation to\r\n% the cropped-image-size (0<=padding<=1). Default: 0\r\n% crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left]\r\n% where NaN/Inf indicate auto-cropping, 0 means no cropping,\r\n% and any other value mean cropping in pixel amounts.\r\n%\r\n%OUT:\r\n% B - JxKxCxN cropped stack of images.\r\n% vA - coordinates in A that contain the cropped image\r\n% vB - coordinates in B where the cropped version of A is placed\r\n% bb_rel - relative bounding box (used for eps-cropping)\r\n\r\n%{\r\n% 06/03/15: Improved image cropping thanks to Oscar Hartogensis\r\n% 08/06/15: Fixed issue #76: case of transparent figure bgcolor\r\n% 21/02/16: Enabled specifying non-automated crop amounts\r\n% 04/04/16: Fix per Luiz Carvalho for old Matlab releases\r\n% 23/10/16: Fixed issue #175: there used to be a 1px minimal padding in case of crop, now removed\r\n%}\r\n\r\n if nargin < 3\r\n padding = 0;\r\n end\r\n if nargin < 4\r\n crop_amounts = nan(1,4); % =auto-cropping\r\n end\r\n crop_amounts(end+1:4) = NaN; % fill missing values with NaN\r\n\r\n [h, w, c, n] = size(A);\r\n if isempty(bcol) % case of transparent bgcolor\r\n bcol = A(ceil(end/2),1,:,1);\r\n end\r\n if isscalar(bcol)\r\n bcol = bcol(ones(c, 1));\r\n end\r\n\r\n % Crop margin from left\r\n if ~isfinite(crop_amounts(4))\r\n bail = false;\r\n for l = 1:w\r\n for a = 1:c\r\n if ~all(col(A(:,l,a,:)) == bcol(a))\r\n bail = true;\r\n break;\r\n end\r\n end\r\n if bail\r\n break;\r\n end\r\n end\r\n else\r\n l = 1 + abs(crop_amounts(4));\r\n end\r\n\r\n % Crop margin from right\r\n if ~isfinite(crop_amounts(2))\r\n bcol = A(ceil(end/2),w,:,1);\r\n bail = false;\r\n for r = w:-1:l\r\n for a = 1:c\r\n if ~all(col(A(:,r,a,:)) == bcol(a))\r\n bail = true;\r\n break;\r\n end\r\n end\r\n if bail\r\n break;\r\n end\r\n end\r\n else\r\n r = w - abs(crop_amounts(2));\r\n end\r\n\r\n % Crop margin from top\r\n if ~isfinite(crop_amounts(1))\r\n bcol = A(1,ceil(end/2),:,1);\r\n bail = false;\r\n for t = 1:h\r\n for a = 1:c\r\n if ~all(col(A(t,:,a,:)) == bcol(a))\r\n bail = true;\r\n break;\r\n end\r\n end\r\n if bail\r\n break;\r\n end\r\n end\r\n else\r\n t = 1 + abs(crop_amounts(1));\r\n end\r\n\r\n % Crop margin from bottom\r\n bcol = A(h,ceil(end/2),:,1);\r\n if ~isfinite(crop_amounts(3))\r\n bail = false;\r\n for b = h:-1:t\r\n for a = 1:c\r\n if ~all(col(A(b,:,a,:)) == bcol(a))\r\n bail = true;\r\n break;\r\n end\r\n end\r\n if bail\r\n break;\r\n end\r\n end\r\n else\r\n b = h - abs(crop_amounts(3));\r\n end\r\n\r\n if padding == 0 % no padding\r\n % Issue #175: there used to be a 1px minimal padding in case of crop, now removed\r\n %{\r\n if ~isequal([t b l r], [1 h 1 w]) % Check if we're actually croppping\r\n padding = 1; % Leave one boundary pixel to avoid bleeding on resize\r\n bcol(:) = nan; % make the 1px padding transparent\r\n end\r\n %}\r\n elseif abs(padding) < 1 % pad value is a relative fraction of image size\r\n padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING\r\n else % pad value is in units of 1/72\" points\r\n padding = round(padding); % fix cases of non-integer pad value\r\n end\r\n\r\n if padding > 0 % extra padding\r\n % Create an empty image, containing the background color, that has the\r\n % cropped image size plus the padded border\r\n B = repmat(bcol,[(b-t)+1+padding*2,(r-l)+1+padding*2,1,n]); % Fix per Luiz Carvalho\r\n % vA - coordinates in A that contain the cropped image\r\n vA = [t b l r];\r\n % vB - coordinates in B where the cropped version of A will be placed\r\n vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];\r\n % Place the original image in the empty image\r\n B(vB(1):vB(2), vB(3):vB(4), :, :) = A(vA(1):vA(2), vA(3):vA(4), :, :);\r\n A = B;\r\n else % extra cropping\r\n vA = [t-padding b+padding l-padding r+padding];\r\n A = A(vA(1):vA(2), vA(3):vA(4), :, :);\r\n vB = [NaN NaN NaN NaN];\r\n end\r\n\r\n % For EPS cropping, determine the relative BoundingBox - bb_rel\r\n bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];\r\nend\r\n\r\nfunction A = col(A)\r\n A = A(:);\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "isolate_axes.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/isolate_axes.m", "size": 4851, "source_encoding": "utf_8", "md5": "611d9727e84ad6ba76dcb3543434d0ce", "text": "function fh = isolate_axes(ah, vis)\r\n%ISOLATE_AXES Isolate the specified axes in a figure on their own\r\n%\r\n% Examples:\r\n% fh = isolate_axes(ah)\r\n% fh = isolate_axes(ah, vis)\r\n%\r\n% This function will create a new figure containing the axes/uipanels\r\n% specified, and also their associated legends and colorbars. The objects\r\n% specified must all be in the same figure, but they will generally only be\r\n% a subset of the objects in the figure.\r\n%\r\n% IN:\r\n% ah - An array of axes and uipanel handles, which must come from the\r\n% same figure.\r\n% vis - A boolean indicating whether the new figure should be visible.\r\n% Default: false.\r\n%\r\n% OUT:\r\n% fh - The handle of the created figure.\r\n\r\n% Copyright (C) Oliver Woodford 2011-2013\r\n\r\n% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs\r\n% 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio\r\n% for pointing out that the function is also used in export_fig.m\r\n% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it\r\n% 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!)\r\n% 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting\r\n% 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro\r\n% on FEX page as a comment on 24-Apr-2014); standardized indentation & help section\r\n% 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2\r\n\r\n % Make sure we have an array of handles\r\n if ~all(ishandle(ah))\r\n error('ah must be an array of handles');\r\n end\r\n % Check that the handles are all for axes or uipanels, and are all in the same figure\r\n fh = ancestor(ah(1), 'figure');\r\n nAx = numel(ah);\r\n for a = 1:nAx\r\n if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})\r\n error('All handles must be axes or uipanel handles.');\r\n end\r\n if ~isequal(ancestor(ah(a), 'figure'), fh)\r\n error('Axes must all come from the same figure.');\r\n end\r\n end\r\n % Tag the objects so we can find them in the copy\r\n old_tag = get(ah, 'Tag');\r\n if nAx == 1\r\n old_tag = {old_tag};\r\n end\r\n set(ah, 'Tag', 'ObjectToCopy');\r\n % Create a new figure exactly the same as the old one\r\n fh = copyfig(fh); %copyobj(fh, 0);\r\n if nargin < 2 || ~vis\r\n set(fh, 'Visible', 'off');\r\n end\r\n % Reset the object tags\r\n for a = 1:nAx\r\n set(ah(a), 'Tag', old_tag{a});\r\n end\r\n % Find the objects to save\r\n ah = findall(fh, 'Tag', 'ObjectToCopy');\r\n if numel(ah) ~= nAx\r\n close(fh);\r\n error('Incorrect number of objects found.');\r\n end\r\n % Set the axes tags to what they should be\r\n for a = 1:nAx\r\n set(ah(a), 'Tag', old_tag{a});\r\n end\r\n % Keep any legends and colorbars which overlap the subplots\r\n % Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we\r\n % don't test for the type, only the tag (hopefully nobody but Matlab uses them!)\r\n lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar');\r\n nLeg = numel(lh);\r\n if nLeg > 0\r\n set([ah(:); lh(:)], 'Units', 'normalized');\r\n try\r\n ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property\r\n catch\r\n ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition\r\n end\r\n if nAx > 1\r\n ax_pos = cell2mat(ax_pos(:));\r\n end\r\n ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);\r\n try\r\n leg_pos = get(lh, 'OuterPosition');\r\n catch\r\n leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1\r\n end\r\n if nLeg > 1;\r\n leg_pos = cell2mat(leg_pos);\r\n end\r\n leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);\r\n ax_pos = shiftdim(ax_pos, -1);\r\n % Overlap test\r\n M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...\r\n bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...\r\n bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...\r\n bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));\r\n ah = [ah; lh(any(M, 2))];\r\n end\r\n % Get all the objects in the figure\r\n axs = findall(fh);\r\n % Delete everything except for the input objects and associated items\r\n delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));\r\nend\r\n\r\nfunction ah = allchildren(ah)\r\n ah = findall(ah);\r\n if iscell(ah)\r\n ah = cell2mat(ah);\r\n end\r\n ah = ah(:);\r\nend\r\n\r\nfunction ph = allancestors(ah)\r\n ph = [];\r\n for a = 1:numel(ah)\r\n h = get(ah(a), 'parent');\r\n while h ~= 0\r\n ph = [ph; h];\r\n h = get(h, 'parent');\r\n end\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "im2gif.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/im2gif.m", "size": 6234, "source_encoding": "utf_8", "md5": "8ee74d7d94e524410788276aa41dd5f1", "text": "%IM2GIF Convert a multiframe image to an animated GIF file\r\n%\r\n% Examples:\r\n% im2gif infile\r\n% im2gif infile outfile\r\n% im2gif(A, outfile)\r\n% im2gif(..., '-nocrop')\r\n% im2gif(..., '-nodither')\r\n% im2gif(..., '-ncolors', n)\r\n% im2gif(..., '-loops', n)\r\n% im2gif(..., '-delay', n) \r\n% \r\n% This function converts a multiframe image to an animated GIF.\r\n%\r\n% To create an animation from a series of figures, export to a multiframe\r\n% TIFF file using export_fig, then convert to a GIF, as follows:\r\n%\r\n% for a = 2 .^ (3:6)\r\n% peaks(a);\r\n% export_fig test.tif -nocrop -append\r\n% end\r\n% im2gif('test.tif', '-delay', 0.5);\r\n%\r\n%IN:\r\n% infile - string containing the name of the input image.\r\n% outfile - string containing the name of the output image (must have the\r\n% .gif extension). Default: infile, with .gif extension.\r\n% A - HxWxCxN array of input images, stacked along fourth dimension, to\r\n% be converted to gif.\r\n% -nocrop - option indicating that the borders of the output are not to\r\n% be cropped.\r\n% -nodither - option indicating that dithering is not to be used when\r\n% converting the image.\r\n% -ncolors - option pair, the value of which indicates the maximum number\r\n% of colors the GIF can have. This can also be a quantization\r\n% tolerance, between 0 and 1. Default/maximum: 256.\r\n% -loops - option pair, the value of which gives the number of times the\r\n% animation is to be looped. Default: 65535.\r\n% -delay - option pair, the value of which gives the time, in seconds,\r\n% between frames. Default: 1/15.\r\n\r\n% Copyright (C) Oliver Woodford 2011\r\n\r\nfunction im2gif(A, varargin)\r\n\r\n% Parse the input arguments\r\n[A, options] = parse_args(A, varargin{:});\r\n\r\nif options.crop ~= 0\r\n % Crop\r\n A = crop_borders(A, A(ceil(end/2),1,:,1));\r\nend\r\n\r\n% Convert to indexed image\r\n[h, w, c, n] = size(A);\r\nA = reshape(permute(A, [1 2 4 3]), h, w*n, c);\r\nmap = unique(reshape(A, h*w*n, c), 'rows');\r\nif size(map, 1) > 256\r\n dither_str = {'dither', 'nodither'};\r\n dither_str = dither_str{1+(options.dither==0)};\r\n if options.ncolors <= 1\r\n [B, map] = rgb2ind(A, options.ncolors, dither_str);\r\n if size(map, 1) > 256\r\n [B, map] = rgb2ind(A, 256, dither_str);\r\n end\r\n else\r\n [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);\r\n end\r\nelse\r\n if max(map(:)) > 1\r\n map = double(map) / 255;\r\n A = double(A) / 255;\r\n end\r\n B = rgb2ind(im2double(A), map);\r\nend\r\nB = reshape(B, h, w, 1, n);\r\n\r\n% Bug fix to rgb2ind\r\nmap(B(1)+1,:) = im2double(A(1,1,:));\r\n\r\n% Save as a gif\r\nimwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);\r\nend\r\n\r\n%% Parse the input arguments\r\nfunction [A, options] = parse_args(A, varargin)\r\n% Set the defaults\r\noptions = struct('outfile', '', ...\r\n 'dither', true, ...\r\n 'crop', true, ...\r\n 'ncolors', 256, ...\r\n 'loops', 65535, ...\r\n 'delay', 1/15);\r\n\r\n% Go through the arguments\r\na = 0;\r\nn = numel(varargin);\r\nwhile a < n\r\n a = a + 1;\r\n if ischar(varargin{a}) && ~isempty(varargin{a})\r\n if varargin{a}(1) == '-'\r\n opt = lower(varargin{a}(2:end));\r\n switch opt\r\n case 'nocrop'\r\n options.crop = false;\r\n case 'nodither'\r\n options.dither = false;\r\n otherwise\r\n if ~isfield(options, opt)\r\n error('Option %s not recognized', varargin{a});\r\n end\r\n a = a + 1;\r\n if ischar(varargin{a}) && ~ischar(options.(opt))\r\n options.(opt) = str2double(varargin{a});\r\n else\r\n options.(opt) = varargin{a};\r\n end\r\n end\r\n else\r\n options.outfile = varargin{a};\r\n end\r\n end\r\nend\r\n\r\nif isempty(options.outfile)\r\n if ~ischar(A)\r\n error('No output filename given.');\r\n end\r\n % Generate the output filename from the input filename\r\n [path, outfile] = fileparts(A);\r\n options.outfile = fullfile(path, [outfile '.gif']);\r\nend\r\n\r\nif ischar(A)\r\n % Read in the image\r\n A = imread_rgb(A);\r\nend\r\nend\r\n\r\n%% Read image to uint8 rgb array\r\nfunction [A, alpha] = imread_rgb(name)\r\n% Get file info\r\ninfo = imfinfo(name);\r\n% Special case formats\r\nswitch lower(info(1).Format)\r\n case 'gif'\r\n [A, map] = imread(name, 'frames', 'all');\r\n if ~isempty(map)\r\n map = uint8(map * 256 - 0.5); % Convert to uint8 for storage\r\n A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0\r\n A = permute(A, [1 2 5 4 3]);\r\n end\r\n case {'tif', 'tiff'}\r\n A = cell(numel(info), 1);\r\n for a = 1:numel(A)\r\n [A{a}, map] = imread(name, 'Index', a, 'Info', info);\r\n if ~isempty(map)\r\n map = uint8(map * 256 - 0.5); % Convert to uint8 for storage\r\n A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0\r\n end\r\n if size(A{a}, 3) == 4\r\n % TIFF in CMYK colourspace - convert to RGB\r\n if isfloat(A{a})\r\n A{a} = A{a} * 255;\r\n else\r\n A{a} = single(A{a});\r\n end\r\n A{a} = 255 - A{a};\r\n A{a}(:,:,4) = A{a}(:,:,4) / 255;\r\n A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));\r\n end\r\n end\r\n A = cat(4, A{:});\r\n otherwise\r\n [A, map, alpha] = imread(name);\r\n A = A(:,:,:,1); % Keep only first frame of multi-frame files\r\n if ~isempty(map)\r\n map = uint8(map * 256 - 0.5); % Convert to uint8 for storage\r\n A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0\r\n elseif size(A, 3) == 4\r\n % Assume 4th channel is an alpha matte\r\n alpha = A(:,:,4);\r\n A = A(:,:,1:3);\r\n end\r\nend\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "read_write_entire_textfile.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/read_write_entire_textfile.m", "size": 961, "source_encoding": "utf_8", "md5": "775aa1f538c76516c7fb406a4f129320", "text": "%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory\r\n%\r\n% Read or write an entire text file to/from memory, without leaving the\r\n% file open if an error occurs.\r\n%\r\n% Reading:\r\n% fstrm = read_write_entire_textfile(fname)\r\n% Writing:\r\n% read_write_entire_textfile(fname, fstrm)\r\n%\r\n%IN:\r\n% fname - Pathname of text file to be read in.\r\n% fstrm - String to be written to the file, including carriage returns.\r\n%\r\n%OUT:\r\n% fstrm - String read from the file. If an fstrm input is given the\r\n% output is the same as that input. \r\n\r\nfunction fstrm = read_write_entire_textfile(fname, fstrm)\r\nmodes = {'rt', 'wt'};\r\nwriting = nargin > 1;\r\nfh = fopen(fname, modes{1+writing});\r\nif fh == -1\r\n error('Unable to open file %s.', fname);\r\nend\r\ntry\r\n if writing\r\n fwrite(fh, fstrm, 'char*1');\r\n else\r\n fstrm = fread(fh, '*char')';\r\n end\r\ncatch ex\r\n fclose(fh);\r\n rethrow(ex);\r\nend\r\nfclose(fh);\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "pdf2eps.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/pdf2eps.m", "size": 1522, "source_encoding": "utf_8", "md5": "4c8f0603619234278ed413670d24bdb6", "text": "%PDF2EPS Convert a pdf file to eps format using pdftops\r\n%\r\n% Examples:\r\n% pdf2eps source dest\r\n%\r\n% This function converts a pdf file to eps format.\r\n%\r\n% This function requires that you have pdftops, from the Xpdf suite of\r\n% functions, installed on your system. This can be downloaded from:\r\n% http://www.foolabs.com/xpdf \r\n%\r\n%IN:\r\n% source - filename of the source pdf file to convert. The filename is\r\n% assumed to already have the extension \".pdf\".\r\n% dest - filename of the destination eps file. The filename is assumed to\r\n% already have the extension \".eps\".\r\n\r\n% Copyright (C) Oliver Woodford 2009-2010\r\n\r\n% Thanks to Aldebaro Klautau for reporting a bug when saving to\r\n% non-existant directories.\r\n\r\nfunction pdf2eps(source, dest)\r\n% Construct the options string for pdftops\r\noptions = ['-q -paper match -eps -level2 \"' source '\" \"' dest '\"'];\r\n% Convert to eps using pdftops\r\n[status, message] = pdftops(options);\r\n% Check for error\r\nif status\r\n % Report error\r\n if isempty(message)\r\n error('Unable to generate eps. Check destination directory is writable.');\r\n else\r\n error(message);\r\n end\r\nend\r\n% Fix the DSC error created by pdftops\r\nfid = fopen(dest, 'r+');\r\nif fid == -1\r\n % Cannot open the file\r\n return\r\nend\r\nfgetl(fid); % Get the first line\r\nstr = fgetl(fid); % Get the second line\r\nif strcmp(str(1:min(13, end)), '% Produced by')\r\n fseek(fid, -numel(str)-1, 'cof');\r\n fwrite(fid, '%'); % Turn ' ' into '%'\r\nend\r\nfclose(fid);\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "print2array.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/print2array.m", "size": 10376, "source_encoding": "utf_8", "md5": "a2022c32ae3efa6007a326692227bd39", "text": "function [A, bcol] = print2array(fig, res, renderer, gs_options)\r\n%PRINT2ARRAY Exports a figure to an image array\r\n%\r\n% Examples:\r\n% A = print2array\r\n% A = print2array(figure_handle)\r\n% A = print2array(figure_handle, resolution)\r\n% A = print2array(figure_handle, resolution, renderer)\r\n% A = print2array(figure_handle, resolution, renderer, gs_options)\r\n% [A bcol] = print2array(...)\r\n%\r\n% This function outputs a bitmap image of the given figure, at the desired\r\n% resolution.\r\n%\r\n% If renderer is '-painters' then ghostcript needs to be installed. This\r\n% can be downloaded from: http://www.ghostscript.com\r\n%\r\n% IN:\r\n% figure_handle - The handle of the figure to be exported. Default: gcf.\r\n% resolution - Resolution of the output, as a factor of screen\r\n% resolution. Default: 1.\r\n% renderer - string containing the renderer paramater to be passed to\r\n% print. Default: '-opengl'.\r\n% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If\r\n% multiple options are needed, enclose in call array: {'-a','-b'}\r\n%\r\n% OUT:\r\n% A - MxNx3 uint8 image of the figure.\r\n% bcol - 1x3 uint8 vector of the background color\r\n\r\n% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-\r\n%{\r\n% 05/09/11: Set EraseModes to normal when using opengl or zbuffer\r\n% renderers. Thanks to Pawel Kocieniewski for reporting the issue.\r\n% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.\r\n% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size\r\n% and erasemode settings. Makes it a bit slower, but more reliable.\r\n% Thanks to Phil Trinh and Meelis Lootus for reporting the issues.\r\n% 09/12/11: Pass font path to ghostscript.\r\n% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to\r\n% Ken Campbell for reporting it.\r\n% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.\r\n% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for\r\n% reporting the issue.\r\n% 26/02/15: If temp dir is not writable, use the current folder for temp\r\n% EPS/TIF files (Javier Paredes)\r\n% 27/02/15: Display suggested workarounds to internal print() error (issue #16)\r\n% 28/02/15: Enable users to specify optional ghostscript options (issue #36)\r\n% 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation\r\n% 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)\r\n% 07/07/15: Fixed issue #83: use numeric handles in HG1\r\n% 11/12/16: Fixed cropping issue reported by Harry D.\r\n%}\r\n\r\n % Generate default input arguments, if needed\r\n if nargin < 2\r\n res = 1;\r\n if nargin < 1\r\n fig = gcf;\r\n end\r\n end\r\n % Warn if output is large\r\n old_mode = get(fig, 'Units');\r\n set(fig, 'Units', 'pixels');\r\n px = get(fig, 'Position');\r\n set(fig, 'Units', old_mode);\r\n npx = prod(px(3:4)*res)/1e6;\r\n if npx > 30\r\n % 30M pixels or larger!\r\n warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);\r\n end\r\n % Retrieve the background colour\r\n bcol = get(fig, 'Color');\r\n % Set the resolution parameter\r\n res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];\r\n % Generate temporary file name\r\n tmp_nam = [tempname '.tif'];\r\n try\r\n % Ensure that the temp dir is writable (Javier Paredes 26/2/15)\r\n fid = fopen(tmp_nam,'w');\r\n fwrite(fid,1);\r\n fclose(fid);\r\n delete(tmp_nam); % cleanup\r\n isTempDirOk = true;\r\n catch\r\n % Temp dir is not writable, so use the current folder\r\n [dummy,fname,fext] = fileparts(tmp_nam); %#ok\r\n fpath = pwd;\r\n tmp_nam = fullfile(fpath,[fname fext]);\r\n isTempDirOk = false;\r\n end\r\n % Enable users to specify optional ghostscript options (issue #36)\r\n if nargin > 3 && ~isempty(gs_options)\r\n if iscell(gs_options)\r\n gs_options = sprintf(' %s',gs_options{:});\r\n elseif ~ischar(gs_options)\r\n error('gs_options input argument must be a string or cell-array of strings');\r\n else\r\n gs_options = [' ' gs_options];\r\n end\r\n else\r\n gs_options = '';\r\n end\r\n if nargin > 2 && strcmp(renderer, '-painters')\r\n % First try to print directly to tif file\r\n try\r\n % Print the file into a temporary TIF file and read it into array A\r\n [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);\r\n if err, rethrow(ex); end\r\n catch % error - try to print to EPS and then using Ghostscript to TIF\r\n % Print to eps file\r\n if isTempDirOk\r\n tmp_eps = [tempname '.eps'];\r\n else\r\n tmp_eps = fullfile(fpath,[fname '.eps']);\r\n end\r\n print2eps(tmp_eps, fig, 0, renderer, '-loose');\r\n try\r\n % Initialize the command to export to tiff using ghostscript\r\n cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];\r\n % Set the font path\r\n fp = font_path();\r\n if ~isempty(fp)\r\n cmd_str = [cmd_str ' -sFONTPATH=\"' fp '\"'];\r\n end\r\n % Add the filenames\r\n cmd_str = [cmd_str ' -sOutputFile=\"' tmp_nam '\" \"' tmp_eps '\"' gs_options];\r\n % Execute the ghostscript command\r\n ghostscript(cmd_str);\r\n catch me\r\n % Delete the intermediate file\r\n delete(tmp_eps);\r\n rethrow(me);\r\n end\r\n % Delete the intermediate file\r\n delete(tmp_eps);\r\n % Read in the generated bitmap\r\n A = imread(tmp_nam);\r\n % Delete the temporary bitmap file\r\n delete(tmp_nam);\r\n end\r\n % Set border pixels to the correct colour\r\n if isequal(bcol, 'none')\r\n bcol = [];\r\n elseif isequal(bcol, [1 1 1])\r\n bcol = uint8([255 255 255]);\r\n else\r\n for l = 1:size(A, 2)\r\n if ~all(reshape(A(:,l,:) == 255, [], 1))\r\n break;\r\n end\r\n end\r\n for r = size(A, 2):-1:l\r\n if ~all(reshape(A(:,r,:) == 255, [], 1))\r\n break;\r\n end\r\n end\r\n for t = 1:size(A, 1)\r\n if ~all(reshape(A(t,:,:) == 255, [], 1))\r\n break;\r\n end\r\n end\r\n for b = size(A, 1):-1:t\r\n if ~all(reshape(A(b,:,:) == 255, [], 1))\r\n break;\r\n end\r\n end\r\n bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));\r\n for c = 1:size(A, 3)\r\n A(:,[1:l-1, r+1:end],c) = bcol(c);\r\n A([1:t-1, b+1:end],:,c) = bcol(c);\r\n end\r\n end\r\n else\r\n if nargin < 3\r\n renderer = '-opengl';\r\n end\r\n % Print the file into a temporary TIF file and read it into array A\r\n [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam);\r\n % Throw any error that occurred\r\n if err\r\n % Display suggested workarounds to internal print() error (issue #16)\r\n fprintf(2, 'An error occured with Matlab''s builtin print function.\\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\\n\\n');\r\n rethrow(ex);\r\n end\r\n % Set the background color\r\n if isequal(bcol, 'none')\r\n bcol = [];\r\n else\r\n bcol = bcol * 255;\r\n if isequal(bcol, round(bcol))\r\n bcol = uint8(bcol);\r\n else\r\n bcol = squeeze(A(1,1,:));\r\n end\r\n end\r\n end\r\n % Check the output size is correct\r\n if isequal(res, round(res))\r\n px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below\r\n if ~isequal(size(A), px)\r\n % Correct the output size\r\n A = A(1:min(end,px(1)),1:min(end,px(2)),:);\r\n end\r\n end\r\nend\r\n\r\n% Function to create a TIF image of the figure and read it into an array\r\nfunction [A, err, ex] = read_tif_img(fig, res_str, renderer, tmp_nam)\r\n err = false;\r\n ex = [];\r\n % Temporarily set the paper size\r\n old_pos_mode = get(fig, 'PaperPositionMode');\r\n old_orientation = get(fig, 'PaperOrientation');\r\n set(fig, 'PaperPositionMode','auto', 'PaperOrientation','portrait');\r\n try\r\n % Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)\r\n fp = []; % in case we get an error below\r\n fp = findall(fig, 'Type','patch', 'LineWidth',0.75);\r\n set(fp, 'LineWidth',0.5);\r\n % Fix issue #83: use numeric handles in HG1\r\n if ~using_hg2(fig), fig = double(fig); end\r\n % Print to tiff file\r\n print(fig, renderer, res_str, '-dtiff', tmp_nam);\r\n % Read in the printed file\r\n A = imread(tmp_nam);\r\n % Delete the temporary file\r\n delete(tmp_nam);\r\n catch ex\r\n err = true;\r\n end\r\n set(fp, 'LineWidth',0.75); % restore original figure appearance\r\n % Reset the paper size\r\n set(fig, 'PaperPositionMode',old_pos_mode, 'PaperOrientation',old_orientation);\r\nend\r\n\r\n% Function to return (and create, where necessary) the font path\r\nfunction fp = font_path()\r\n fp = user_string('gs_font_path');\r\n if ~isempty(fp)\r\n return\r\n end\r\n % Create the path\r\n % Start with the default path\r\n fp = getenv('GS_FONTPATH');\r\n % Add on the typical directories for a given OS\r\n if ispc\r\n if ~isempty(fp)\r\n fp = [fp ';'];\r\n end\r\n fp = [fp getenv('WINDIR') filesep 'Fonts'];\r\n else\r\n if ~isempty(fp)\r\n fp = [fp ':'];\r\n end\r\n fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];\r\n end\r\n user_string('gs_font_path', fp);\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "append_pdfs.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/append_pdfs.m", "size": 2759, "source_encoding": "utf_8", "md5": "9b52be41aff48bea6f27992396900640", "text": "%APPEND_PDFS Appends/concatenates multiple PDF files\r\n%\r\n% Example:\r\n% append_pdfs(output, input1, input2, ...)\r\n% append_pdfs(output, input_list{:})\r\n% append_pdfs test.pdf temp1.pdf temp2.pdf\r\n%\r\n% This function appends multiple PDF files to an existing PDF file, or\r\n% concatenates them into a PDF file if the output file doesn't yet exist.\r\n%\r\n% This function requires that you have ghostscript installed on your\r\n% system. Ghostscript can be downloaded from: http://www.ghostscript.com\r\n%\r\n% IN:\r\n% output - string of output file name (including the extension, .pdf).\r\n% If it exists it is appended to; if not, it is created.\r\n% input1 - string of an input file name (including the extension, .pdf).\r\n% All input files are appended in order.\r\n% input_list - cell array list of input file name strings. All input\r\n% files are appended in order.\r\n\r\n% Copyright: Oliver Woodford, 2011\r\n\r\n% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in\r\n% one go is much faster than appending them one at a time.\r\n\r\n% Thanks to Michael Teo for reporting the issue of a too long command line.\r\n% Issue resolved on 5/5/2011, by passing gs a command file.\r\n\r\n% Thanks to Martin Wittmann for pointing out the quality issue when\r\n% appending multiple bitmaps.\r\n% Issue resolved (to best of my ability) 1/6/2011, using the prepress\r\n% setting\r\n\r\n% 26/02/15: If temp dir is not writable, use the output folder for temp\r\n% files when appending (Javier Paredes); sanity check of inputs\r\n\r\nfunction append_pdfs(varargin)\r\n\r\nif nargin < 2, return; end % sanity check\r\n\r\n% Are we appending or creating a new file\r\nappend = exist(varargin{1}, 'file') == 2;\r\noutput = [tempname '.pdf'];\r\ntry\r\n % Ensure that the temp dir is writable (Javier Paredes 26/2/15)\r\n fid = fopen(output,'w');\r\n fwrite(fid,1);\r\n fclose(fid);\r\n delete(output);\r\n isTempDirOk = true;\r\ncatch\r\n % Temp dir is not writable, so use the output folder\r\n [dummy,fname,fext] = fileparts(output); %#ok\r\n fpath = fileparts(varargin{1});\r\n output = fullfile(fpath,[fname fext]);\r\n isTempDirOk = false;\r\nend\r\nif ~append\r\n output = varargin{1};\r\n varargin = varargin(2:end);\r\nend\r\n% Create the command file\r\nif isTempDirOk\r\n cmdfile = [tempname '.txt'];\r\nelse\r\n cmdfile = fullfile(fpath,[fname '.txt']);\r\nend\r\nfh = fopen(cmdfile, 'w');\r\nfprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=\"%s\" -f', output);\r\nfprintf(fh, ' \"%s\"', varargin{:});\r\nfclose(fh);\r\n% Call ghostscript\r\nghostscript(['@\"' cmdfile '\"']);\r\n% Delete the command file\r\ndelete(cmdfile);\r\n% Rename the file if needed\r\nif append\r\n movefile(output, varargin{1});\r\nend\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "using_hg2.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/using_hg2.m", "size": 1100, "source_encoding": "utf_8", "md5": "47ca10d86740c27b9f6b397373ae16cd", "text": "%USING_HG2 Determine if the HG2 graphics engine is used\r\n%\r\n% tf = using_hg2(fig)\r\n%\r\n%IN:\r\n% fig - handle to the figure in question.\r\n%\r\n%OUT:\r\n% tf - boolean indicating whether the HG2 graphics engine is being used\r\n% (true) or not (false).\r\n\r\n% 19/06/2015 - Suppress warning in R2015b; cache result for improved performance\r\n% 06/06/2016 - Fixed issue #156 (bad return value in R2016b)\r\n\r\nfunction tf = using_hg2(fig)\r\n persistent tf_cached\r\n if isempty(tf_cached)\r\n try\r\n if nargin < 1, fig = figure('visible','off'); end\r\n oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval');\r\n try\r\n % This generates a [supressed] warning in R2015b:\r\n tf = ~graphicsversion(fig, 'handlegraphics');\r\n catch\r\n tf = ~verLessThan('matlab','8.4'); % =R2014b\r\n end\r\n warning(oldWarn);\r\n catch\r\n tf = false;\r\n end\r\n if nargin < 1, delete(fig); end\r\n tf_cached = tf;\r\n else\r\n tf = tf_cached;\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "eps2pdf.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/eps2pdf.m", "size": 8793, "source_encoding": "utf_8", "md5": "474e976cf6454d5d7850baf14494fedf", "text": "function eps2pdf(source, dest, crop, append, gray, quality, gs_options)\r\n%EPS2PDF Convert an eps file to pdf format using ghostscript\r\n%\r\n% Examples:\r\n% eps2pdf source dest\r\n% eps2pdf(source, dest, crop)\r\n% eps2pdf(source, dest, crop, append)\r\n% eps2pdf(source, dest, crop, append, gray)\r\n% eps2pdf(source, dest, crop, append, gray, quality)\r\n% eps2pdf(source, dest, crop, append, gray, quality, gs_options)\r\n%\r\n% This function converts an eps file to pdf format. The output can be\r\n% optionally cropped and also converted to grayscale. If the output pdf\r\n% file already exists then the eps file can optionally be appended as a new\r\n% page on the end of the eps file. The level of bitmap compression can also\r\n% optionally be set.\r\n%\r\n% This function requires that you have ghostscript installed on your\r\n% system. Ghostscript can be downloaded from: http://www.ghostscript.com\r\n%\r\n% Inputs:\r\n% source - filename of the source eps file to convert. The filename is\r\n% assumed to already have the extension \".eps\".\r\n% dest - filename of the destination pdf file. The filename is assumed\r\n% to already have the extension \".pdf\".\r\n% crop - boolean indicating whether to crop the borders off the pdf.\r\n% Default: true.\r\n% append - boolean indicating whether the eps should be appended to the\r\n% end of the pdf as a new page (if the pdf exists already).\r\n% Default: false.\r\n% gray - boolean indicating whether the output pdf should be grayscale\r\n% or not. Default: false.\r\n% quality - scalar indicating the level of image bitmap quality to\r\n% output. A larger value gives a higher quality. quality > 100\r\n% gives lossless output. Default: ghostscript prepress default.\r\n% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If\r\n% multiple options are needed, enclose in call array: {'-a','-b'}\r\n\r\n% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-\r\n\r\n% Suggestion of appending pdf files provided by Matt C at:\r\n% http://www.mathworks.com/matlabcentral/fileexchange/23629\r\n\r\n% Thank you to Fabio Viola for pointing out compression artifacts, leading\r\n% to the quality setting.\r\n% Thank you to Scott for pointing out the subsampling of very small images,\r\n% which was fixed for lossless compression settings.\r\n\r\n% 9/12/2011 Pass font path to ghostscript.\r\n% 26/02/15: If temp dir is not writable, use the dest folder for temp\r\n% destination files (Javier Paredes)\r\n% 28/02/15: Enable users to specify optional ghostscript options (issue #36)\r\n% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve\r\n% some /findfont errors according to James Rankin, FEX Comment 23/01/15)\r\n% 23/06/15: Added extra debug info in case of ghostscript error; code indentation\r\n% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)\r\n% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)\r\n% 20/03/17: Added informational message in case of GS croak (issue #186)\r\n\r\n % Intialise the options string for ghostscript\r\n options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=\"' dest '\"'];\r\n % Set crop option\r\n if nargin < 3 || crop\r\n options = [options ' -dEPSCrop'];\r\n end\r\n % Set the font path\r\n fp = font_path();\r\n if ~isempty(fp)\r\n options = [options ' -sFONTPATH=\"' fp '\"'];\r\n end\r\n % Set the grayscale option\r\n if nargin > 4 && gray\r\n options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];\r\n end\r\n % Set the bitmap quality\r\n if nargin > 5 && ~isempty(quality)\r\n options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];\r\n if quality > 100\r\n options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c \".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams\"'];\r\n else\r\n options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];\r\n v = 1 + (quality < 80);\r\n quality = 1 - quality / 100;\r\n s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);\r\n options = sprintf('%s -c \".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams\"', options, s, s);\r\n end\r\n end\r\n % Enable users to specify optional ghostscript options (issue #36)\r\n if nargin > 6 && ~isempty(gs_options)\r\n if iscell(gs_options)\r\n gs_options = sprintf(' %s',gs_options{:});\r\n elseif ~ischar(gs_options)\r\n error('gs_options input argument must be a string or cell-array of strings');\r\n else\r\n gs_options = [' ' gs_options];\r\n end\r\n options = [options gs_options];\r\n end\r\n % Check if the output file exists\r\n if nargin > 3 && append && exist(dest, 'file') == 2\r\n % File exists - append current figure to the end\r\n tmp_nam = tempname;\r\n try\r\n % Ensure that the temp dir is writable (Javier Paredes 26/2/15)\r\n fid = fopen(tmp_nam,'w');\r\n fwrite(fid,1);\r\n fclose(fid);\r\n delete(tmp_nam);\r\n catch\r\n % Temp dir is not writable, so use the dest folder\r\n [dummy,fname,fext] = fileparts(tmp_nam); %#ok\r\n fpath = fileparts(dest);\r\n tmp_nam = fullfile(fpath,[fname fext]);\r\n end\r\n % Copy the file\r\n copyfile(dest, tmp_nam);\r\n % Add the output file names\r\n options = [options ' -f \"' tmp_nam '\" \"' source '\"'];\r\n try\r\n % Convert to pdf using ghostscript\r\n [status, message] = ghostscript(options);\r\n catch me\r\n % Delete the intermediate file\r\n delete(tmp_nam);\r\n rethrow(me);\r\n end\r\n % Delete the intermediate file\r\n delete(tmp_nam);\r\n else\r\n % File doesn't exist or should be over-written\r\n % Add the output file names\r\n options = [options ' -f \"' source '\"'];\r\n % Convert to pdf using ghostscript\r\n [status, message] = ghostscript(options);\r\n end\r\n % Check for error\r\n if status\r\n % Retry without the -sFONTPATH= option (this might solve some GS\r\n % /findfont errors according to James Rankin, FEX Comment 23/01/15)\r\n orig_options = options;\r\n if ~isempty(fp)\r\n options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');\r\n status = ghostscript(options);\r\n if ~status, return; end % hurray! (no error)\r\n end\r\n % Report error\r\n if isempty(message)\r\n error('Unable to generate pdf. Check destination directory is writable.');\r\n elseif ~isempty(strfind(message,'/typecheck in /findfont'))\r\n % Suggest a workaround for issue #41 (missing font path)\r\n font_name = strtrim(regexprep(message,'.*Operand stack:\\s*(.*)\\s*Execution.*','$1'));\r\n fprintf(2, 'Ghostscript error: could not find the following font(s): %s\\n', font_name);\r\n fpath = fileparts(mfilename('fullpath'));\r\n gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');\r\n fprintf(2, ' try to add the font''s folder to your %s file\\n\\n', gs_fonts_file);\r\n error('export_fig error');\r\n else\r\n fprintf(2, '\\nGhostscript error: perhaps %s is open by another application\\n', dest);\r\n if ~isempty(gs_options)\r\n fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\\n', gs_options);\r\n end\r\n fprintf(2, ' or maybe you have another gs executable in your system''s path\\n');\r\n fprintf(2, 'Ghostscript options: %s\\n\\n', orig_options);\r\n error(message);\r\n end\r\n end\r\nend\r\n\r\n% Function to return (and create, where necessary) the font path\r\nfunction fp = font_path()\r\n fp = user_string('gs_font_path');\r\n if ~isempty(fp)\r\n return\r\n end\r\n % Create the path\r\n % Start with the default path\r\n fp = getenv('GS_FONTPATH');\r\n % Add on the typical directories for a given OS\r\n if ispc\r\n if ~isempty(fp)\r\n fp = [fp ';'];\r\n end\r\n fp = [fp getenv('WINDIR') filesep 'Fonts'];\r\n else\r\n if ~isempty(fp)\r\n fp = [fp ':'];\r\n end\r\n fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];\r\n end\r\n user_string('gs_font_path', fp);\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "export_fig.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/export_fig.m", "size": 64681, "source_encoding": "utf_8", "md5": "6eb52ba116cd2632d3e98cfafa45bca1", "text": "function [imageData, alpha] = export_fig(varargin)\r\n%EXPORT_FIG Exports figures in a publication-quality format\r\n%\r\n% Examples:\r\n% imageData = export_fig\r\n% [imageData, alpha] = export_fig\r\n% export_fig filename\r\n% export_fig filename -format1 -format2\r\n% export_fig ... -nocrop\r\n% export_fig ... -c[,,,]\r\n% export_fig ... -transparent\r\n% export_fig ... -native\r\n% export_fig ... -m\r\n% export_fig ... -r\r\n% export_fig ... -a\r\n% export_fig ... -q\r\n% export_fig ... -p\r\n% export_fig ... -d\r\n% export_fig ... -depsc\r\n% export_fig ... -\r\n% export_fig ... -\r\n% export_fig ... -append\r\n% export_fig ... -bookmark\r\n% export_fig ... -clipboard\r\n% export_fig ... -update\r\n% export_fig ... -nofontswap\r\n% export_fig ... -font_space \r\n% export_fig ... -linecaps\r\n% export_fig ... -noinvert\r\n% export_fig(..., handle)\r\n%\r\n% This function saves a figure or single axes to one or more vector and/or\r\n% bitmap file formats, and/or outputs a rasterized version to the workspace,\r\n% with the following properties:\r\n% - Figure/axes reproduced as it appears on screen\r\n% - Cropped borders (optional)\r\n% - Embedded fonts (vector formats)\r\n% - Improved line and grid line styles\r\n% - Anti-aliased graphics (bitmap formats)\r\n% - Render images at native resolution (optional for bitmap formats)\r\n% - Transparent background supported (pdf, eps, png, tiff)\r\n% - Semi-transparent patch objects supported (png, tiff)\r\n% - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)\r\n% - Variable image compression, including lossless (pdf, eps, jpg)\r\n% - Optional rounded line-caps (pdf, eps)\r\n% - Optionally append to file (pdf, tiff)\r\n% - Vector formats: pdf, eps\r\n% - Bitmap formats: png, tiff, jpg, bmp, export to workspace\r\n%\r\n% This function is especially suited to exporting figures for use in\r\n% publications and presentations, because of the high quality and\r\n% portability of media produced.\r\n%\r\n% Note that the background color and figure dimensions are reproduced\r\n% (the latter approximately, and ignoring cropping & magnification) in the\r\n% output file. For transparent background (and semi-transparent patch\r\n% objects), use the -transparent option or set the figure 'Color' property\r\n% to 'none'. To make axes transparent set the axes 'Color' property to\r\n% 'none'. PDF, EPS, TIF & PNG are the only formats that support a transparent\r\n% background; only TIF & PNG formats support transparency of patch objects.\r\n%\r\n% The choice of renderer (opengl, zbuffer or painters) has a large impact\r\n% on the quality of output. The default value (opengl for bitmaps, painters\r\n% for vector formats) generally gives good results, but if you aren't\r\n% satisfied then try another renderer. Notes: 1) For vector formats (EPS,\r\n% PDF), only painters generates vector graphics. 2) For bitmaps, only\r\n% opengl can render transparent patch objects correctly. 3) For bitmaps,\r\n% only painters will correctly scale line dash and dot lengths when\r\n% magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when\r\n% using painters.\r\n%\r\n% When exporting to vector format (PDF & EPS) and bitmap format using the\r\n% painters renderer, this function requires that ghostscript is installed\r\n% on your system. You can download this from:\r\n% http://www.ghostscript.com\r\n% When exporting to eps it additionally requires pdftops, from the Xpdf\r\n% suite of functions. You can download this from:\r\n% http://www.foolabs.com/xpdf\r\n%\r\n% Inputs:\r\n% filename - string containing the name (optionally including full or\r\n% relative path) of the file the figure is to be saved as. If\r\n% a path is not specified, the figure is saved in the current\r\n% directory. If no name and no output arguments are specified,\r\n% the default name, 'export_fig_out', is used. If neither a\r\n% file extension nor a format are specified, a \".png\" is added\r\n% and the figure saved in that format.\r\n% -format1, -format2, etc. - strings containing the extensions of the\r\n% file formats the figure is to be saved as.\r\n% Valid options are: '-pdf', '-eps', '-png',\r\n% '-tif', '-jpg' and '-bmp'. All combinations\r\n% of formats are valid.\r\n% -nocrop - option indicating that the borders of the output are not to\r\n% be cropped.\r\n% -c[,,,] - option indicating crop amounts. Must be\r\n% a 4-element vector of numeric values: [top,right,bottom,left]\r\n% where NaN/Inf indicate auto-cropping, 0 means no cropping,\r\n% and any other value mean cropping in pixel amounts.\r\n% -transparent - option indicating that the figure background is to be\r\n% made transparent (png, pdf, tif and eps output only).\r\n% -m - option where val indicates the factor to magnify the\r\n% on-screen figure pixel dimensions by when generating bitmap\r\n% outputs (does not affect vector formats). Default: '-m1'.\r\n% -r - option val indicates the resolution (in pixels per inch) to\r\n% export bitmap and vector outputs at, keeping the dimensions\r\n% of the on-screen figure. Default: '-r864' (for vector output\r\n% only). Note that the -m option overides the -r option for\r\n% bitmap outputs only.\r\n% -native - option indicating that the output resolution (when outputting\r\n% a bitmap format) should be such that the vertical resolution\r\n% of the first suitable image found in the figure is at the\r\n% native resolution of that image. To specify a particular\r\n% image to use, give it the tag 'export_fig_native'. Notes:\r\n% This overrides any value set with the -m and -r options. It\r\n% also assumes that the image is displayed front-to-parallel\r\n% with the screen. The output resolution is approximate and\r\n% should not be relied upon. Anti-aliasing can have adverse\r\n% effects on image quality (disable with the -a1 option).\r\n% -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to\r\n% use for bitmap outputs. '-a1' means no anti-\r\n% aliasing; '-a4' is the maximum amount (default).\r\n% - - option to force a particular renderer (painters, opengl or\r\n% zbuffer). Default value: opengl for bitmap formats or\r\n% figures with patches and/or transparent annotations;\r\n% painters for vector formats without patches/transparencies.\r\n% - - option indicating which colorspace color figures should\r\n% be saved in: RGB (default), CMYK or gray. CMYK is only\r\n% supported in pdf, eps and tiff output.\r\n% -q - option to vary bitmap image quality (in pdf, eps and jpg\r\n% files only). Larger val, in the range 0-100, gives higher\r\n% quality/lower compression. val > 100 gives lossless\r\n% compression. Default: '-q95' for jpg, ghostscript prepress\r\n% default for pdf & eps. Note: lossless compression can\r\n% sometimes give a smaller file size than the default lossy\r\n% compression, depending on the type of images.\r\n% -p - option to pad a border of width val to exported files, where\r\n% val is either a relative size with respect to cropped image\r\n% size (i.e. p=0.01 adds a 1% border). For EPS & PDF formats,\r\n% val can also be integer in units of 1/72\" points (abs(val)>1).\r\n% val can be positive (padding) or negative (extra cropping).\r\n% If used, the -nocrop flag will be ignored, i.e. the image will\r\n% always be cropped and then padded. Default: 0 (i.e. no padding).\r\n% -append - option indicating that if the file (pdfs only) already\r\n% exists, the figure is to be appended as a new page, instead\r\n% of being overwritten (default).\r\n% -bookmark - option to indicate that a bookmark with the name of the\r\n% figure is to be created in the output file (pdf only).\r\n% -clipboard - option to save output as an image on the system clipboard.\r\n% Note: background transparency is not preserved in clipboard\r\n% -d - option to indicate a ghostscript setting. For example,\r\n% -dMaxBitmap=0 or -dNoOutputFonts (Ghostscript 9.15+).\r\n% -depsc - option to use EPS level-3 rather than the default level-2 print\r\n% device. This solves some bugs with Matlab's default -depsc2 device\r\n% such as discolored subplot lines on images (vector formats only).\r\n% -update - option to download and install the latest version of export_fig\r\n% -nofontswap - option to avoid font swapping. Font swapping is automatically\r\n% done in vector formats (only): 11 standard Matlab fonts are\r\n% replaced by the original figure fonts. This option prevents this.\r\n% -font_space - option to set a spacer character for font-names that\r\n% contain spaces, used by EPS/PDF. Default: ''\r\n% -linecaps - option to create rounded line-caps (vector formats only).\r\n% -noinvert - option to avoid setting figure's InvertHardcopy property to\r\n% 'off' during output (this solves some problems of empty outputs).\r\n% handle - The handle of the figure, axes or uipanels (can be an array of\r\n% handles, but the objects must be in the same figure) to be\r\n% saved. Default: gcf.\r\n%\r\n% Outputs:\r\n% imageData - MxNxC uint8 image array of the exported image.\r\n% alpha - MxN single array of alphamatte values in the range [0,1],\r\n% for the case when the background is transparent.\r\n%\r\n% Some helpful examples and tips can be found at:\r\n% https://github.com/altmany/export_fig\r\n%\r\n% See also PRINT, SAVEAS, ScreenCapture (on the Matlab File Exchange)\r\n\r\n%{\r\n% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-\r\n\r\n% The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG\r\n% (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782).\r\n% The idea for using pdftops came from the MATLAB newsgroup (id: 168171).\r\n% The idea of editing the EPS file to change line styles comes from Jiro\r\n% Doke's FIXPSLINESTYLE (fex id: 17928).\r\n% The idea of changing dash length with line width came from comments on\r\n% fex id: 5743, but the implementation is mine :)\r\n% The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id:\r\n% 20979).\r\n% The idea of appending figures in pdfs came from Matt C in comments on the\r\n% FEX (id: 23629)\r\n\r\n% Thanks to Roland Martin for pointing out the colour MATLAB\r\n% bug/feature with colorbar axes and transparent backgrounds.\r\n% Thanks also to Andrew Matthews for describing a bug to do with the figure\r\n% size changing in -nodisplay mode. I couldn't reproduce it, but included a\r\n% fix anyway.\r\n% Thanks to Tammy Threadgill for reporting a bug where an axes is not\r\n% isolated from gui objects.\r\n%}\r\n%{\r\n% 23/02/12: Ensure that axes limits don't change during printing\r\n% 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for reporting it).\r\n% 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling bookmarking of figures in pdf files.\r\n% 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep tick marks fixed.\r\n% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it.\r\n% 25/09/13: Add support for changing resolution in vector formats. Thanks to Jan Jaap Meijer for suggesting it.\r\n% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner for suggesting it.\r\n% 24/02/15: Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'\r\n% 25/02/15: Fix issue #4 (using HG2 on R2014a and earlier)\r\n% 25/02/15: Fix issue #21 (bold TeX axes labels/titles in R2014b)\r\n% 26/02/15: If temp dir is not writable, use the user-specified folder for temporary EPS/PDF files (Javier Paredes)\r\n% 27/02/15: Modified repository URL from github.com/ojwoodford to /altmany\r\n% Indented main function\r\n% Added top-level try-catch block to display useful workarounds\r\n% 28/02/15: Enable users to specify optional ghostscript options (issue #36)\r\n% 06/03/15: Improved image padding & cropping thanks to Oscar Hartogensis\r\n% 26/03/15: Fixed issue #49 (bug with transparent grayscale images); fixed out-of-memory issue\r\n% 26/03/15: Fixed issue #42: non-normalized annotations on HG1\r\n% 26/03/15: Fixed issue #46: Ghostscript crash if figure units <> pixels\r\n% 27/03/15: Fixed issue #39: bad export of transparent annotations/patches\r\n% 28/03/15: Fixed issue #50: error on some Matlab versions with the fix for issue #42\r\n% 29/03/15: Fixed issue #33: bugs in Matlab's print() function with -cmyk\r\n% 29/03/15: Improved processing of input args (accept space between param name & value, related to issue #51)\r\n% 30/03/15: When exporting *.fig files, then saveas *.fig if figure is open, otherwise export the specified fig file\r\n% 30/03/15: Fixed edge case bug introduced yesterday (commit #ae1755bd2e11dc4e99b95a7681f6e211b3fa9358)\r\n% 09/04/15: Consolidated header comment sections; initialize output vars only if requested (nargout>0)\r\n% 14/04/15: Workaround for issue #45: lines in image subplots are exported in invalid color\r\n% 15/04/15: Fixed edge-case in parsing input parameters; fixed help section to show the -depsc option (issue #45)\r\n% 21/04/15: Bug fix: Ghostscript croaks on % chars in output PDF file (reported by Sven on FEX page, 15-Jul-2014)\r\n% 22/04/15: Bug fix: Pdftops croaks on relative paths (reported by Tintin Milou on FEX page, 19-Jan-2015)\r\n% 04/05/15: Merged fix #63 (Kevin Mattheus Moerman): prevent tick-label changes during export\r\n% 07/05/15: Partial fix for issue #65: PDF export used painters rather than opengl renderer (thanks Nguyenr)\r\n% 08/05/15: Fixed issue #65: bad PDF append since commit #e9f3cdf 21/04/15 (thanks Robert Nguyen)\r\n% 12/05/15: Fixed issue #67: exponent labels cropped in export, since fix #63 (04/05/15)\r\n% 28/05/15: Fixed issue #69: set non-bold label font only if the string contains symbols (\\beta etc.), followup to issue #21\r\n% 29/05/15: Added informative error message in case user requested SVG output (issue #72)\r\n% 09/06/15: Fixed issue #58: -transparent removed anti-aliasing when exporting to PNG\r\n% 19/06/15: Added -update option to download and install the latest version of export_fig\r\n% 07/07/15: Added -nofontswap option to avoid font-swapping in EPS/PDF\r\n% 16/07/15: Fixed problem with anti-aliasing on old Matlab releases\r\n% 11/09/15: Fixed issue #103: magnification must never become negative; also fixed reported error msg in parsing input params\r\n% 26/09/15: Alert if trying to export transparent patches/areas to non-PNG outputs (issue #108)\r\n% 04/10/15: Do not suggest workarounds for certain errors that have already been handled previously\r\n% 01/11/15: Fixed issue #112: use same renderer in print2eps as export_fig (thanks to Jesús Pestana Puerta)\r\n% 10/11/15: Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX\r\n% 19/11/15: Fixed clipboard export in R2015b (thanks to Dan K via FEX)\r\n% 21/02/16: Added -c option for indicating specific crop amounts (idea by Cedric Noordam on FEX)\r\n% 08/05/16: Added message about possible error reason when groot.Units~=pixels (issue #149)\r\n% 17/05/16: Fixed case of image YData containing more than 2 elements (issue #151)\r\n% 08/08/16: Enabled exporting transparency to TIF, in addition to PNG/PDF (issue #168)\r\n% 11/12/16: Added alert in case of error creating output PDF/EPS file (issue #179)\r\n% 13/12/16: Minor fix to the commit for issue #179 from 2 days ago\r\n% 22/03/17: Fixed issue #187: only set manual ticks when no exponent is present\r\n% 09/04/17: Added -linecaps option (idea by Baron Finer, issue #192)\r\n% 15/09/17: Fixed issue #205: incorrect tick-labels when Ticks number don't match the TickLabels number\r\n% 15/09/17: Fixed issue #210: initialize alpha map to ones instead of zeros when -transparent is not used\r\n% 18/09/17: Added -font_space option to replace font-name spaces in EPS/PDF (workaround for issue #194)\r\n% 18/09/17: Added -noinvert option to solve some export problems with some graphic cards (workaround for issue #197)\r\n%}\r\n\r\n if nargout\r\n [imageData, alpha] = deal([]);\r\n end\r\n hadError = false;\r\n displaySuggestedWorkarounds = true;\r\n\r\n % Ensure the figure is rendered correctly _now_ so that properties like axes limits are up-to-date\r\n drawnow;\r\n pause(0.05); % this solves timing issues with Java Swing's EDT (http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem)\r\n\r\n % Parse the input arguments\r\n fig = get(0, 'CurrentFigure');\r\n [fig, options] = parse_args(nargout, fig, varargin{:});\r\n\r\n % Ensure that we have a figure handle\r\n if isequal(fig,-1)\r\n return; % silent bail-out\r\n elseif isempty(fig)\r\n error('No figure found');\r\n end\r\n\r\n % Isolate the subplot, if it is one\r\n cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'}));\r\n if cls\r\n % Given handles of one or more axes, so isolate them from the rest\r\n fig = isolate_axes(fig);\r\n else\r\n % Check we have a figure\r\n if ~isequal(get(fig, 'Type'), 'figure')\r\n error('Handle must be that of a figure, axes or uipanel');\r\n end\r\n % Get the old InvertHardcopy mode\r\n old_mode = get(fig, 'InvertHardcopy');\r\n end\r\n\r\n % Hack the font units where necessary (due to a font rendering bug in print?).\r\n % This may not work perfectly in all cases.\r\n % Also it can change the figure layout if reverted, so use a copy.\r\n magnify = options.magnify * options.aa_factor;\r\n if isbitmap(options) && magnify ~= 1\r\n fontu = findall(fig, 'FontUnits', 'normalized');\r\n if ~isempty(fontu)\r\n % Some normalized font units found\r\n if ~cls\r\n fig = copyfig(fig);\r\n set(fig, 'Visible', 'off');\r\n fontu = findall(fig, 'FontUnits', 'normalized');\r\n cls = true;\r\n end\r\n set(fontu, 'FontUnits', 'points');\r\n end\r\n end\r\n\r\n try\r\n % MATLAB \"feature\": axes limits and tick marks can change when printing\r\n Hlims = findall(fig, 'Type', 'axes');\r\n if ~cls\r\n % Record the old axes limit and tick modes\r\n Xlims = make_cell(get(Hlims, 'XLimMode'));\r\n Ylims = make_cell(get(Hlims, 'YLimMode'));\r\n Zlims = make_cell(get(Hlims, 'ZLimMode'));\r\n Xtick = make_cell(get(Hlims, 'XTickMode'));\r\n Ytick = make_cell(get(Hlims, 'YTickMode'));\r\n Ztick = make_cell(get(Hlims, 'ZTickMode'));\r\n Xlabel = make_cell(get(Hlims, 'XTickLabelMode')); \r\n Ylabel = make_cell(get(Hlims, 'YTickLabelMode')); \r\n Zlabel = make_cell(get(Hlims, 'ZTickLabelMode')); \r\n end\r\n\r\n % Set all axes limit and tick modes to manual, so the limits and ticks can't change\r\n % Fix Matlab R2014b bug (issue #34): plot markers are not displayed when ZLimMode='manual'\r\n set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual');\r\n set_tick_mode(Hlims, 'X');\r\n set_tick_mode(Hlims, 'Y');\r\n if ~using_hg2(fig)\r\n set(Hlims,'ZLimMode', 'manual');\r\n set_tick_mode(Hlims, 'Z');\r\n end\r\n catch\r\n % ignore - fix issue #4 (using HG2 on R2014a and earlier)\r\n end\r\n\r\n % Fix issue #21 (bold TeX axes labels/titles in R2014b when exporting to EPS/PDF)\r\n try\r\n if using_hg2(fig) && isvector(options)\r\n % Set the FontWeight of axes labels/titles to 'normal'\r\n % Fix issue #69: set non-bold font only if the string contains symbols (\\beta etc.)\r\n texLabels = findall(fig, 'type','text', 'FontWeight','bold');\r\n symbolIdx = ~cellfun('isempty',strfind({texLabels.String},'\\'));\r\n set(texLabels(symbolIdx), 'FontWeight','normal');\r\n end\r\n catch\r\n % ignore\r\n end\r\n\r\n % Fix issue #42: non-normalized annotations on HG1 (internal Matlab bug)\r\n annotationHandles = [];\r\n try\r\n if ~using_hg2(fig)\r\n annotationHandles = findall(fig,'Type','hggroup','-and','-property','Units','-and','-not','Units','norm');\r\n try % suggested by Jesús Pestana Puerta (jespestana) 30/9/2015\r\n originalUnits = get(annotationHandles,'Units');\r\n set(annotationHandles,'Units','norm');\r\n catch\r\n end\r\n end\r\n catch\r\n % should never happen, but ignore in any case - issue #50\r\n end\r\n\r\n % Fix issue #46: Ghostscript crash if figure units <> pixels\r\n oldFigUnits = get(fig,'Units');\r\n set(fig,'Units','pixels');\r\n\r\n % Set to print exactly what is there\r\n if options.invert_hardcopy\r\n set(fig, 'InvertHardcopy', 'off');\r\n end\r\n % Set the renderer\r\n switch options.renderer\r\n case 1\r\n renderer = '-opengl';\r\n case 2\r\n renderer = '-zbuffer';\r\n case 3\r\n renderer = '-painters';\r\n otherwise\r\n renderer = '-opengl'; % Default for bitmaps\r\n end\r\n\r\n % Handle transparent patches\r\n hasTransparency = ~isempty(findall(fig,'-property','FaceAlpha','-and','-not','FaceAlpha',1));\r\n hasPatches = ~isempty(findall(fig,'type','patch'));\r\n if hasTransparency\r\n % Alert if trying to export transparent patches/areas to non-supported outputs (issue #108)\r\n % http://www.mathworks.com/matlabcentral/answers/265265-can-export_fig-or-else-draw-vector-graphics-with-transparent-surfaces\r\n % TODO - use transparency when exporting to PDF by not passing via print2eps\r\n msg = 'export_fig currently supports transparent patches/areas only in PNG output. ';\r\n if options.pdf\r\n warning('export_fig:transparency', '%s\\nTo export transparent patches/areas to PDF, use the print command:\\n print(gcf, ''-dpdf'', ''%s.pdf'');', msg, options.name);\r\n elseif ~options.png && ~options.tif % issue #168\r\n warning('export_fig:transparency', '%s\\nTo export the transparency correctly, try using the ScreenCapture utility on the Matlab File Exchange: http://bit.ly/1QFrBip', msg);\r\n end\r\n end\r\n\r\n try\r\n % Do the bitmap formats first\r\n if isbitmap(options)\r\n if abs(options.bb_padding) > 1\r\n displaySuggestedWorkarounds = false;\r\n error('For bitmap output (png,jpg,tif,bmp) the padding value (-p) must be between -1 100\r\n imwrite(A, [options.name '.jpg'], 'Mode', 'lossless');\r\n else\r\n imwrite(A, [options.name '.jpg'], 'Quality', quality);\r\n end\r\n end\r\n % Save tif images in cmyk if wanted (and possible)\r\n if options.tif\r\n if options.colourspace == 1 && size(A, 3) == 3\r\n A = double(255 - A);\r\n K = min(A, [], 3);\r\n K_ = 255 ./ max(255 - K, 1);\r\n C = (A(:,:,1) - K) .* K_;\r\n M = (A(:,:,2) - K) .* K_;\r\n Y = (A(:,:,3) - K) .* K_;\r\n A = uint8(cat(3, C, M, Y, K));\r\n clear C M Y K K_\r\n end\r\n append_mode = {'overwrite', 'append'};\r\n imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1});\r\n end\r\n end\r\n\r\n % Now do the vector formats\r\n if isvector(options)\r\n % Set the default renderer to painters\r\n if ~options.renderer\r\n if hasTransparency || hasPatches\r\n % This is *MUCH* slower, but more accurate for patches and transparent annotations (issue #39)\r\n renderer = '-opengl';\r\n else\r\n renderer = '-painters';\r\n end\r\n end\r\n options.rendererStr = renderer; % fix for issue #112\r\n % Generate some filenames\r\n tmp_nam = [tempname '.eps'];\r\n try\r\n % Ensure that the temp dir is writable (Javier Paredes 30/1/15)\r\n fid = fopen(tmp_nam,'w');\r\n fwrite(fid,1);\r\n fclose(fid);\r\n delete(tmp_nam);\r\n isTempDirOk = true;\r\n catch\r\n % Temp dir is not writable, so use the user-specified folder\r\n [dummy,fname,fext] = fileparts(tmp_nam); %#ok\r\n fpath = fileparts(options.name);\r\n tmp_nam = fullfile(fpath,[fname fext]);\r\n isTempDirOk = false;\r\n end\r\n if isTempDirOk\r\n pdf_nam_tmp = [tempname '.pdf'];\r\n else\r\n pdf_nam_tmp = fullfile(fpath,[fname '.pdf']);\r\n end\r\n if options.pdf\r\n pdf_nam = [options.name '.pdf'];\r\n try copyfile(pdf_nam, pdf_nam_tmp, 'f'); catch, end % fix for issue #65\r\n else\r\n pdf_nam = pdf_nam_tmp;\r\n end\r\n % Generate the options for print\r\n p2eArgs = {renderer, sprintf('-r%d', options.resolution)};\r\n if options.colourspace == 1 % CMYK\r\n % Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option\r\n %p2eArgs{end+1} = '-cmyk';\r\n end\r\n if ~options.crop\r\n % Issue #56: due to internal bugs in Matlab's print() function, we can't use its internal cropping mechanism,\r\n % therefore we always use '-loose' (in print2eps.m) and do our own cropping (in crop_borders)\r\n %p2eArgs{end+1} = '-loose';\r\n end\r\n if any(strcmpi(varargin,'-depsc'))\r\n % Issue #45: lines in image subplots are exported in invalid color.\r\n % The workaround is to use the -depsc parameter instead of the default -depsc2\r\n p2eArgs{end+1} = '-depsc';\r\n end\r\n try\r\n % Generate an eps\r\n print2eps(tmp_nam, fig, options, p2eArgs{:});\r\n % Remove the background, if desired\r\n if options.transparent && ~isequal(get(fig, 'Color'), 'none')\r\n eps_remove_background(tmp_nam, 1 + using_hg2(fig));\r\n end\r\n % Fix colorspace to CMYK, if requested (workaround for issue #33)\r\n if options.colourspace == 1 % CMYK\r\n % Issue #33: due to internal bugs in Matlab's print() function, we can't use its -cmyk option\r\n change_rgb_to_cmyk(tmp_nam);\r\n end\r\n % Add a bookmark to the PDF if desired\r\n if options.bookmark\r\n fig_nam = get(fig, 'Name');\r\n if isempty(fig_nam)\r\n warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.');\r\n end\r\n add_bookmark(tmp_nam, fig_nam);\r\n end\r\n % Generate a pdf\r\n eps2pdf(tmp_nam, pdf_nam_tmp, 1, options.append, options.colourspace==2, options.quality, options.gs_options);\r\n % Ghostscript croaks on % chars in the output PDF file, so use tempname and then rename the file\r\n try\r\n % Rename the file (except if it is already the same)\r\n % Abbie K's comment on the commit for issue #179 (#commitcomment-20173476)\r\n if ~isequal(pdf_nam_tmp, pdf_nam)\r\n movefile(pdf_nam_tmp, pdf_nam, 'f');\r\n end\r\n catch\r\n % Alert in case of error creating output PDF/EPS file (issue #179)\r\n if exist(pdf_nam_tmp, 'file')\r\n error(['Could not create ' pdf_nam ' - perhaps the folder does not exist, or you do not have write permissions']);\r\n else\r\n error('Could not generate the intermediary EPS file.');\r\n end\r\n end\r\n catch ex\r\n % Delete the eps\r\n delete(tmp_nam);\r\n rethrow(ex);\r\n end\r\n % Delete the eps\r\n delete(tmp_nam);\r\n if options.eps || options.linecaps\r\n try\r\n % Generate an eps from the pdf\r\n % since pdftops can't handle relative paths (e.g., '..\\'), use a temp file\r\n eps_nam_tmp = strrep(pdf_nam_tmp,'.pdf','.eps');\r\n pdf2eps(pdf_nam, eps_nam_tmp);\r\n\r\n % Issue #192: enable rounded line-caps\r\n if options.linecaps\r\n fstrm = read_write_entire_textfile(eps_nam_tmp);\r\n fstrm = regexprep(fstrm, '[02] J', '1 J');\r\n read_write_entire_textfile(eps_nam_tmp, fstrm);\r\n if options.pdf\r\n eps2pdf(eps_nam_tmp, pdf_nam, 1, options.append, options.colourspace==2, options.quality, options.gs_options);\r\n end\r\n end\r\n\r\n if options.eps\r\n movefile(eps_nam_tmp, [options.name '.eps'], 'f');\r\n else % if options.pdf\r\n try delete(eps_nam_tmp); catch, end\r\n end\r\n catch ex\r\n if ~options.pdf\r\n % Delete the pdf\r\n delete(pdf_nam);\r\n end\r\n try delete(eps_nam_tmp); catch, end\r\n rethrow(ex);\r\n end\r\n if ~options.pdf\r\n % Delete the pdf\r\n delete(pdf_nam);\r\n end\r\n end\r\n end\r\n\r\n % Revert the figure or close it (if requested)\r\n if cls || options.closeFig\r\n % Close the created figure\r\n close(fig);\r\n else\r\n % Reset the hardcopy mode\r\n set(fig, 'InvertHardcopy', old_mode);\r\n % Reset the axes limit and tick modes\r\n for a = 1:numel(Hlims)\r\n try\r\n set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a},... \r\n 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a},...\r\n 'XTickLabelMode', Xlabel{a}, 'YTickLabelMode', Ylabel{a}, 'ZTickLabelMode', Zlabel{a}); \r\n catch\r\n % ignore - fix issue #4 (using HG2 on R2014a and earlier)\r\n end\r\n end\r\n % Revert the tex-labels font weights\r\n try set(texLabels, 'FontWeight','bold'); catch, end\r\n % Revert annotation units\r\n for handleIdx = 1 : numel(annotationHandles)\r\n try\r\n oldUnits = originalUnits{handleIdx};\r\n catch\r\n oldUnits = originalUnits;\r\n end\r\n try set(annotationHandles(handleIdx),'Units',oldUnits); catch, end\r\n end\r\n % Revert figure units\r\n set(fig,'Units',oldFigUnits);\r\n end\r\n\r\n % Output to clipboard (if requested)\r\n if options.clipboard\r\n % Delete the output file if unchanged from the default name ('export_fig_out.png')\r\n if strcmpi(options.name,'export_fig_out')\r\n try\r\n fileInfo = dir('export_fig_out.png');\r\n if ~isempty(fileInfo)\r\n timediff = now - fileInfo.datenum;\r\n ONE_SEC = 1/24/60/60;\r\n if timediff < ONE_SEC\r\n delete('export_fig_out.png');\r\n end\r\n end\r\n catch\r\n % never mind...\r\n end\r\n end\r\n\r\n % Save the image in the system clipboard\r\n % credit: Jiro Doke's IMCLIPBOARD: http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard\r\n try\r\n error(javachk('awt', 'export_fig -clipboard output'));\r\n catch\r\n warning('export_fig -clipboard output failed: requires Java to work');\r\n return;\r\n end\r\n try\r\n % Import necessary Java classes\r\n import java.awt.Toolkit\r\n import java.awt.image.BufferedImage\r\n import java.awt.datatransfer.DataFlavor\r\n\r\n % Get System Clipboard object (java.awt.Toolkit)\r\n cb = Toolkit.getDefaultToolkit.getSystemClipboard();\r\n\r\n % Add java class (ImageSelection) to the path\r\n if ~exist('ImageSelection', 'class')\r\n javaaddpath(fileparts(which(mfilename)), '-end');\r\n end\r\n\r\n % Get image size\r\n ht = size(imageData, 1);\r\n wd = size(imageData, 2);\r\n\r\n % Convert to Blue-Green-Red format\r\n try\r\n imageData2 = imageData(:, :, [3 2 1]);\r\n catch\r\n % Probably gray-scaled image (2D, without the 3rd [RGB] dimension)\r\n imageData2 = imageData(:, :, [1 1 1]);\r\n end\r\n\r\n % Convert to 3xWxH format\r\n imageData2 = permute(imageData2, [3, 2, 1]);\r\n\r\n % Append Alpha data (unused - transparency is not supported in clipboard copy)\r\n alphaData2 = uint8(permute(255*alpha,[3,2,1])); %=255*ones(1,wd,ht,'uint8')\r\n imageData2 = cat(1, imageData2, alphaData2);\r\n\r\n % Create image buffer\r\n imBuffer = BufferedImage(wd, ht, BufferedImage.TYPE_INT_RGB);\r\n imBuffer.setRGB(0, 0, wd, ht, typecast(imageData2(:), 'int32'), 0, wd);\r\n\r\n % Create ImageSelection object from the image buffer\r\n imSelection = ImageSelection(imBuffer);\r\n\r\n % Set clipboard content to the image\r\n cb.setContents(imSelection, []);\r\n catch\r\n warning('export_fig -clipboard output failed: %s', lasterr); %#ok\r\n end\r\n end\r\n\r\n % Don't output the data to console unless requested\r\n if ~nargout\r\n clear imageData alpha\r\n end\r\n catch err\r\n % Display possible workarounds before the error message\r\n if displaySuggestedWorkarounds && ~strcmpi(err.message,'export_fig error')\r\n if ~hadError, fprintf(2, 'export_fig error. '); end\r\n fprintf(2, 'Please ensure:\\n');\r\n fprintf(2, ' that you are using the latest version of export_fig\\n');\r\n if ismac\r\n fprintf(2, ' and that you have Ghostscript installed\\n');\r\n else\r\n fprintf(2, ' and that you have Ghostscript installed\\n');\r\n end\r\n try\r\n if options.eps\r\n fprintf(2, ' and that you have pdftops installed\\n');\r\n end\r\n catch\r\n % ignore - probably an error in parse_args\r\n end\r\n fprintf(2, ' and that you do not have multiple versions of export_fig installed by mistake\\n');\r\n fprintf(2, ' and that you did not made a mistake in the expected input arguments\\n');\r\n try\r\n % Alert per issue #149\r\n if ~strncmpi(get(0,'Units'),'pixel',5)\r\n fprintf(2, ' or try to set groot''s Units property back to its default value of ''pixels'' (details)\\n');\r\n end\r\n catch\r\n % ignore - maybe an old MAtlab release\r\n end\r\n fprintf(2, '\\nIf the problem persists, then please report a new issue.\\n\\n');\r\n end\r\n rethrow(err)\r\n end\r\nend\r\n\r\nfunction options = default_options()\r\n % Default options used by export_fig\r\n options = struct(...\r\n 'name', 'export_fig_out', ...\r\n 'crop', true, ...\r\n 'crop_amounts', nan(1,4), ... % auto-crop all 4 image sides\r\n 'transparent', false, ...\r\n 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters\r\n 'pdf', false, ...\r\n 'eps', false, ...\r\n 'png', false, ...\r\n 'tif', false, ...\r\n 'jpg', false, ...\r\n 'bmp', false, ...\r\n 'clipboard', false, ...\r\n 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray\r\n 'append', false, ...\r\n 'im', false, ...\r\n 'alpha', false, ...\r\n 'aa_factor', 0, ...\r\n 'bb_padding', 0, ...\r\n 'magnify', [], ...\r\n 'resolution', [], ...\r\n 'bookmark', false, ...\r\n 'closeFig', false, ...\r\n 'quality', [], ...\r\n 'update', false, ...\r\n 'fontswap', true, ...\r\n 'font_space', '', ...\r\n 'linecaps', false, ...\r\n 'invert_hardcopy', true, ...\r\n 'gs_options', {{}});\r\nend\r\n\r\nfunction [fig, options] = parse_args(nout, fig, varargin)\r\n % Parse the input arguments\r\n\r\n % Set the defaults\r\n native = false; % Set resolution to native of an image\r\n options = default_options();\r\n options.im = (nout == 1); % user requested imageData output\r\n options.alpha = (nout == 2); % user requested alpha output\r\n\r\n % Go through the other arguments\r\n skipNext = false;\r\n for a = 1:nargin-2\r\n if skipNext\r\n skipNext = false;\r\n continue;\r\n end\r\n if all(ishandle(varargin{a}))\r\n fig = varargin{a};\r\n elseif ischar(varargin{a}) && ~isempty(varargin{a})\r\n if varargin{a}(1) == '-'\r\n switch lower(varargin{a}(2:end))\r\n case 'nocrop'\r\n options.crop = false;\r\n options.crop_amounts = [0,0,0,0];\r\n case {'trans', 'transparent'}\r\n options.transparent = true;\r\n case 'opengl'\r\n options.renderer = 1;\r\n case 'zbuffer'\r\n options.renderer = 2;\r\n case 'painters'\r\n options.renderer = 3;\r\n case 'pdf'\r\n options.pdf = true;\r\n case 'eps'\r\n options.eps = true;\r\n case 'png'\r\n options.png = true;\r\n case {'tif', 'tiff'}\r\n options.tif = true;\r\n case {'jpg', 'jpeg'}\r\n options.jpg = true;\r\n case 'bmp'\r\n options.bmp = true;\r\n case 'rgb'\r\n options.colourspace = 0;\r\n case 'cmyk'\r\n options.colourspace = 1;\r\n case {'gray', 'grey'}\r\n options.colourspace = 2;\r\n case {'a1', 'a2', 'a3', 'a4'}\r\n options.aa_factor = str2double(varargin{a}(3));\r\n case 'append'\r\n options.append = true;\r\n case 'bookmark'\r\n options.bookmark = true;\r\n case 'native'\r\n native = true;\r\n case 'clipboard'\r\n options.clipboard = true;\r\n options.im = true;\r\n options.alpha = true;\r\n case 'svg'\r\n msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\\n' ...\r\n ' 1. saveas(gcf,''filename.svg'')\\n' ...\r\n ' 2. plot2svg utility: http://github.com/jschwizer99/plot2svg\\n' ...\r\n ' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\\n'];\r\n error(sprintf(msg)); %#ok\r\n case 'update'\r\n % Download the latest version of export_fig into the export_fig folder\r\n try\r\n zipFileName = 'https://github.com/altmany/export_fig/archive/master.zip';\r\n folderName = fileparts(which(mfilename('fullpath')));\r\n targetFileName = fullfile(folderName, datestr(now,'yyyy-mm-dd.zip'));\r\n urlwrite(zipFileName,targetFileName);\r\n catch\r\n error('Could not download %s into %s\\n',zipFileName,targetFileName);\r\n end\r\n\r\n % Unzip the downloaded zip file in the export_fig folder\r\n try\r\n unzip(targetFileName,folderName);\r\n catch\r\n error('Could not unzip %s\\n',targetFileName);\r\n end\r\n case 'nofontswap'\r\n options.fontswap = false;\r\n case 'font_space'\r\n options.font_space = varargin{a+1};\r\n skipNext = true;\r\n case 'linecaps'\r\n options.linecaps = true;\r\n case 'noinvert'\r\n options.invert_hardcopy = false;\r\n otherwise\r\n try\r\n wasError = false;\r\n if strcmpi(varargin{a}(1:2),'-d')\r\n varargin{a}(2) = 'd'; % ensure lowercase 'd'\r\n options.gs_options{end+1} = varargin{a};\r\n elseif strcmpi(varargin{a}(1:2),'-c')\r\n if numel(varargin{a})==2\r\n skipNext = true;\r\n vals = str2num(varargin{a+1}); %#ok\r\n else\r\n vals = str2num(varargin{a}(3:end)); %#ok\r\n end\r\n if numel(vals)~=4\r\n wasError = true;\r\n error('option -c cannot be parsed: must be a 4-element numeric vector');\r\n end\r\n options.crop_amounts = vals;\r\n options.crop = true;\r\n else % scalar parameter value\r\n val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\\d*.?\\d+', 'match'));\r\n if isempty(val) || isnan(val)\r\n % Issue #51: improved processing of input args (accept space between param name & value)\r\n val = str2double(varargin{a+1});\r\n if isscalar(val) && ~isnan(val)\r\n skipNext = true;\r\n end\r\n end\r\n if ~isscalar(val) || isnan(val)\r\n wasError = true;\r\n error('option %s is not recognised or cannot be parsed', varargin{a});\r\n end\r\n switch lower(varargin{a}(2))\r\n case 'm'\r\n % Magnification may never be negative\r\n if val <= 0\r\n wasError = true;\r\n error('Bad magnification value: %g (must be positive)', val);\r\n end\r\n options.magnify = val;\r\n case 'r'\r\n options.resolution = val;\r\n case 'q'\r\n options.quality = max(val, 0);\r\n case 'p'\r\n options.bb_padding = val;\r\n end\r\n end\r\n catch err\r\n % We might have reached here by raising an intentional error\r\n if wasError % intentional raise\r\n rethrow(err)\r\n else % unintentional\r\n error(['Unrecognized export_fig input option: ''' varargin{a} '''']);\r\n end\r\n end\r\n end\r\n else\r\n [p, options.name, ext] = fileparts(varargin{a});\r\n if ~isempty(p)\r\n options.name = [p filesep options.name];\r\n end\r\n switch lower(ext)\r\n case {'.tif', '.tiff'}\r\n options.tif = true;\r\n case {'.jpg', '.jpeg'}\r\n options.jpg = true;\r\n case '.png'\r\n options.png = true;\r\n case '.bmp'\r\n options.bmp = true;\r\n case '.eps'\r\n options.eps = true;\r\n case '.pdf'\r\n options.pdf = true;\r\n case '.fig'\r\n % If no open figure, then load the specified .fig file and continue\r\n if isempty(fig)\r\n fig = openfig(varargin{a},'invisible');\r\n varargin{a} = fig;\r\n options.closeFig = true;\r\n else\r\n % save the current figure as the specified .fig file and exit\r\n saveas(fig(1),varargin{a});\r\n fig = -1;\r\n return\r\n end\r\n case '.svg'\r\n msg = ['SVG output is not supported by export_fig. Use one of the following alternatives:\\n' ...\r\n ' 1. saveas(gcf,''filename.svg'')\\n' ...\r\n ' 2. plot2svg utility: http://github.com/jschwizer99/plot2svg\\n' ...\r\n ' 3. export_fig to EPS/PDF, then convert to SVG using generic (non-Matlab) tools\\n'];\r\n error(sprintf(msg)); %#ok\r\n otherwise\r\n options.name = varargin{a};\r\n end\r\n end\r\n end\r\n end\r\n\r\n % Quick bail-out if no figure found\r\n if isempty(fig), return; end\r\n\r\n % Do border padding with repsect to a cropped image\r\n if options.bb_padding\r\n options.crop = true;\r\n end\r\n\r\n % Set default anti-aliasing now we know the renderer\r\n if options.aa_factor == 0\r\n try isAA = strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on'); catch, isAA = false; end\r\n options.aa_factor = 1 + 2 * (~(using_hg2(fig) && isAA) | (options.renderer == 3));\r\n end\r\n\r\n % Convert user dir '~' to full path\r\n if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\\')\r\n options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));\r\n end\r\n\r\n % Compute the magnification and resolution\r\n if isempty(options.magnify)\r\n if isempty(options.resolution)\r\n options.magnify = 1;\r\n options.resolution = 864;\r\n else\r\n options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');\r\n end\r\n elseif isempty(options.resolution)\r\n options.resolution = 864;\r\n end\r\n\r\n % Set the default format\r\n if ~isvector(options) && ~isbitmap(options)\r\n options.png = true;\r\n end\r\n\r\n % Check whether transparent background is wanted (old way)\r\n if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')\r\n options.transparent = true;\r\n end\r\n\r\n % If requested, set the resolution to the native vertical resolution of the\r\n % first suitable image found\r\n if native && isbitmap(options)\r\n % Find a suitable image\r\n list = findall(fig, 'Type','image', 'Tag','export_fig_native');\r\n if isempty(list)\r\n list = findall(fig, 'Type','image', 'Visible','on');\r\n end\r\n for hIm = list(:)'\r\n % Check height is >= 2\r\n height = size(get(hIm, 'CData'), 1);\r\n if height < 2\r\n continue\r\n end\r\n % Account for the image filling only part of the axes, or vice versa\r\n yl = get(hIm, 'YData');\r\n if isscalar(yl)\r\n yl = [yl(1)-0.5 yl(1)+height+0.5];\r\n else\r\n yl = [min(yl), max(yl)]; % fix issue #151 (case of yl containing more than 2 elements)\r\n if ~diff(yl)\r\n continue\r\n end\r\n yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1));\r\n end\r\n hAx = get(hIm, 'Parent');\r\n yl2 = get(hAx, 'YLim');\r\n % Find the pixel height of the axes\r\n oldUnits = get(hAx, 'Units');\r\n set(hAx, 'Units', 'pixels');\r\n pos = get(hAx, 'Position');\r\n set(hAx, 'Units', oldUnits);\r\n if ~pos(4)\r\n continue\r\n end\r\n % Found a suitable image\r\n % Account for stretch-to-fill being disabled\r\n pbar = get(hAx, 'PlotBoxAspectRatio');\r\n pos = min(pos(4), pbar(2)*pos(3)/pbar(1));\r\n % Set the magnification to give native resolution\r\n options.magnify = abs((height * diff(yl2)) / (pos * diff(yl))); % magnification must never be negative: issue #103\r\n break\r\n end\r\n end\r\nend\r\n\r\nfunction A = downsize(A, factor)\r\n % Downsample an image\r\n if factor == 1\r\n % Nothing to do\r\n return\r\n end\r\n try\r\n % Faster, but requires image processing toolbox\r\n A = imresize(A, 1/factor, 'bilinear');\r\n catch\r\n % No image processing toolbox - resize manually\r\n % Lowpass filter - use Gaussian as is separable, so faster\r\n % Compute the 1d Gaussian filter\r\n filt = (-factor-1:factor+1) / (factor * 0.6);\r\n filt = exp(-filt .* filt);\r\n % Normalize the filter\r\n filt = single(filt / sum(filt));\r\n % Filter the image\r\n padding = floor(numel(filt) / 2);\r\n for a = 1:size(A, 3)\r\n A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid');\r\n end\r\n % Subsample\r\n A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);\r\n end\r\nend\r\n\r\nfunction A = rgb2grey(A)\r\n A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); % #ok\r\nend\r\n\r\nfunction A = check_greyscale(A)\r\n % Check if the image is greyscale\r\n if size(A, 3) == 3 && ...\r\n all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ...\r\n all(reshape(A(:,:,2) == A(:,:,3), [], 1))\r\n A = A(:,:,1); % Save only one channel for 8-bit output\r\n end\r\nend\r\n\r\nfunction eps_remove_background(fname, count)\r\n % Remove the background of an eps file\r\n % Open the file\r\n fh = fopen(fname, 'r+');\r\n if fh == -1\r\n error('Not able to open file %s.', fname);\r\n end\r\n % Read the file line by line\r\n while count\r\n % Get the next line\r\n l = fgets(fh);\r\n if isequal(l, -1)\r\n break; % Quit, no rectangle found\r\n end\r\n % Check if the line contains the background rectangle\r\n if isequal(regexp(l, ' *0 +0 +\\d+ +\\d+ +r[fe] *[\\n\\r]+', 'start'), 1)\r\n % Set the line to whitespace and quit\r\n l(1:regexp(l, '[\\n\\r]', 'start', 'once')-1) = ' ';\r\n fseek(fh, -numel(l), 0);\r\n fprintf(fh, l);\r\n % Reduce the count\r\n count = count - 1;\r\n end\r\n end\r\n % Close the file\r\n fclose(fh);\r\nend\r\n\r\nfunction b = isvector(options)\r\n b = options.pdf || options.eps;\r\nend\r\n\r\nfunction b = isbitmap(options)\r\n b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;\r\nend\r\n\r\n% Helper function\r\nfunction A = make_cell(A)\r\n if ~iscell(A)\r\n A = {A};\r\n end\r\nend\r\n\r\nfunction add_bookmark(fname, bookmark_text)\r\n % Adds a bookmark to the temporary EPS file after %%EndPageSetup\r\n % Read in the file\r\n fh = fopen(fname, 'r');\r\n if fh == -1\r\n error('File %s not found.', fname);\r\n end\r\n try\r\n fstrm = fread(fh, '*char')';\r\n catch ex\r\n fclose(fh);\r\n rethrow(ex);\r\n end\r\n fclose(fh);\r\n\r\n % Include standard pdfmark prolog to maximize compatibility\r\n fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse'));\r\n % Add page bookmark\r\n fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\\n[ /Title (%s) /OUT pdfmark',bookmark_text));\r\n\r\n % Write out the updated file\r\n fh = fopen(fname, 'w');\r\n if fh == -1\r\n error('Unable to open %s for writing.', fname);\r\n end\r\n try\r\n fwrite(fh, fstrm, 'char*1');\r\n catch ex\r\n fclose(fh);\r\n rethrow(ex);\r\n end\r\n fclose(fh);\r\nend\r\n\r\nfunction set_tick_mode(Hlims, ax)\r\n % Set the tick mode of linear axes to manual\r\n % Leave log axes alone as these are tricky\r\n M = get(Hlims, [ax 'Scale']);\r\n if ~iscell(M)\r\n M = {M};\r\n end\r\n %idx = cellfun(@(c) strcmp(c, 'linear'), M);\r\n idx = find(strcmp(M,'linear'));\r\n %set(Hlims(idx), [ax 'TickMode'], 'manual'); % issue #187\r\n %set(Hlims(idx), [ax 'TickLabelMode'], 'manual'); % this hides exponent label in HG2!\r\n for idx2 = 1 : numel(idx)\r\n try\r\n % Fix for issue #187 - only set manual ticks when no exponent is present\r\n hAxes = Hlims(idx(idx2));\r\n props = {[ax 'TickMode'],'manual', [ax 'TickLabelMode'],'manual'};\r\n if isempty(strtrim(hAxes.([ax 'Ruler']).SecondaryLabel.String))\r\n % Fix for issue #205 - only set manual ticks when the Ticks number match the TickLabels number\r\n if numel(hAxes.([ax 'Tick'])) == numel(hAxes.([ax 'TickLabel']))\r\n set(hAxes, props{:}); % no exponent and matching ticks, so update both ticks and tick labels to manual\r\n end\r\n end\r\n catch % probably HG1\r\n set(hAxes, props{:}); % revert back to old behavior\r\n end\r\n end\r\nend\r\n\r\nfunction change_rgb_to_cmyk(fname) % convert RGB => CMYK within an EPS file\r\n % Do post-processing on the eps file\r\n try\r\n % Read the EPS file into memory\r\n fstrm = read_write_entire_textfile(fname);\r\n\r\n % Replace all gray-scale colors\r\n fstrm = regexprep(fstrm, '\\n([\\d.]+) +GC\\n', '\\n0 0 0 ${num2str(1-str2num($1))} CC\\n');\r\n \r\n % Replace all RGB colors\r\n fstrm = regexprep(fstrm, '\\n[0.]+ +[0.]+ +[0.]+ +RC\\n', '\\n0 0 0 1 CC\\n'); % pure black\r\n fstrm = regexprep(fstrm, '\\n([\\d.]+) +([\\d.]+) +([\\d.]+) +RC\\n', '\\n${sprintf(''%.4g '',[1-[str2num($1),str2num($2),str2num($3)]/max([str2num($1),str2num($2),str2num($3)]),1-max([str2num($1),str2num($2),str2num($3)])])} CC\\n');\r\n\r\n % Overwrite the file with the modified contents\r\n read_write_entire_textfile(fname, fstrm);\r\n catch\r\n % never mind - leave as is...\r\n end\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "ghostscript.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/ghostscript.m", "size": 7902, "source_encoding": "utf_8", "md5": "ff62a40d651197dbea5d3c39998b3bad", "text": "function varargout = ghostscript(cmd)\r\n%GHOSTSCRIPT Calls a local GhostScript executable with the input command\r\n%\r\n% Example:\r\n% [status result] = ghostscript(cmd)\r\n%\r\n% Attempts to locate a ghostscript executable, finally asking the user to\r\n% specify the directory ghostcript was installed into. The resulting path\r\n% is stored for future reference.\r\n% \r\n% Once found, the executable is called with the input command string.\r\n%\r\n% This function requires that you have Ghostscript installed on your\r\n% system. You can download this from: http://www.ghostscript.com\r\n%\r\n% IN:\r\n% cmd - Command string to be passed into ghostscript.\r\n%\r\n% OUT:\r\n% status - 0 iff command ran without problem.\r\n% result - Output from ghostscript.\r\n\r\n% Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015-\r\n%{\r\n% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.\r\n% Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems.\r\n% 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and\r\n% Shaun Kline for pointing out the issue\r\n% 04/05/11 - Thanks to David Chorlian for pointing out an alternative\r\n% location for gs on linux.\r\n% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish\r\n% Punnoose for highlighting the issue.\r\n% 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick\r\n% Steinbring for proposing the fix.\r\n% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes \r\n% for the fix.\r\n% 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen\r\n% Vermeer for raising the issue.\r\n% 27/02/15 - If Ghostscript croaks, display suggested workarounds\r\n% 30/03/15 - Improved performance by caching status of GS path check, if ok\r\n% 14/05/15 - Clarified warning message in case GS path could not be saved\r\n% 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74)\r\n% 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX\r\n%}\r\n\r\n try\r\n % Call ghostscript\r\n [varargout{1:nargout}] = system([gs_command(gs_path()) cmd]);\r\n catch err\r\n % Display possible workarounds for Ghostscript croaks\r\n url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12\r\n url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20\r\n hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end\r\n fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\\n * %s ',hg2_str,url1,url1);\r\n if using_hg2\r\n fprintf(2, '(GS 9.10)\\n * %s (R2014a)',url2,url2);\r\n end\r\n fprintf('\\n\\n');\r\n if ismac || isunix\r\n url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27\r\n fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\\n * %s\\n\\n',url3,url3);\r\n % issue #20\r\n fpath = which(mfilename);\r\n if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end\r\n fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from \"export...\" to \"setenv ...\"\\nat the bottom of %s\\n\\n',fpath,fpath);\r\n end\r\n rethrow(err);\r\n end\r\nend\r\n\r\nfunction path_ = gs_path\r\n % Return a valid path\r\n % Start with the currently set path\r\n path_ = user_string('ghostscript');\r\n % Check the path works\r\n if check_gs_path(path_)\r\n return\r\n end\r\n % Check whether the binary is on the path\r\n if ispc\r\n bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};\r\n else\r\n bin = {'gs'};\r\n end\r\n for a = 1:numel(bin)\r\n path_ = bin{a};\r\n if check_store_gs_path(path_)\r\n return\r\n end\r\n end\r\n % Search the obvious places\r\n if ispc\r\n default_location = 'C:\\Program Files\\gs\\';\r\n dir_list = dir(default_location);\r\n if isempty(dir_list)\r\n default_location = 'C:\\Program Files (x86)\\gs\\'; % Possible location on 64-bit systems\r\n dir_list = dir(default_location);\r\n end\r\n executable = {'\\bin\\gswin32c.exe', '\\bin\\gswin64c.exe'};\r\n ver_num = 0;\r\n % If there are multiple versions, use the newest\r\n for a = 1:numel(dir_list)\r\n ver_num2 = sscanf(dir_list(a).name, 'gs%g');\r\n if ~isempty(ver_num2) && ver_num2 > ver_num\r\n for b = 1:numel(executable)\r\n path2 = [default_location dir_list(a).name executable{b}];\r\n if exist(path2, 'file') == 2\r\n path_ = path2;\r\n ver_num = ver_num2;\r\n end\r\n end\r\n end\r\n end\r\n if check_store_gs_path(path_)\r\n return\r\n end\r\n else\r\n executable = {'/usr/bin/gs', '/usr/local/bin/gs'};\r\n for a = 1:numel(executable)\r\n path_ = executable{a};\r\n if check_store_gs_path(path_)\r\n return\r\n end\r\n end\r\n end\r\n % Ask the user to enter the path\r\n while true\r\n if strncmp(computer, 'MAC', 3) % Is a Mac\r\n % Give separate warning as the uigetdir dialogue box doesn't have a\r\n % title\r\n uiwait(warndlg('Ghostscript not found. Please locate the program.'))\r\n end\r\n base = uigetdir('/', 'Ghostcript not found. Please locate the program.');\r\n if isequal(base, 0)\r\n % User hit cancel or closed window\r\n break;\r\n end\r\n base = [base filesep]; %#ok\r\n bin_dir = {'', ['bin' filesep], ['lib' filesep]};\r\n for a = 1:numel(bin_dir)\r\n for b = 1:numel(bin)\r\n path_ = [base bin_dir{a} bin{b}];\r\n if exist(path_, 'file') == 2\r\n if check_store_gs_path(path_)\r\n return\r\n end\r\n end\r\n end\r\n end\r\n end\r\n if ismac\r\n error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?');\r\n else\r\n error('Ghostscript not found. Have you installed it from www.ghostscript.com?');\r\n end\r\nend\r\n\r\nfunction good = check_store_gs_path(path_)\r\n % Check the path is valid\r\n good = check_gs_path(path_);\r\n if ~good\r\n return\r\n end\r\n % Update the current default path to the path found\r\n if ~user_string('ghostscript', path_)\r\n filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt');\r\n warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_);\r\n return\r\n end\r\nend\r\n\r\nfunction good = check_gs_path(path_)\r\n persistent isOk\r\n if isempty(path_)\r\n isOk = false;\r\n elseif ~isequal(isOk,true)\r\n % Check whether the path is valid\r\n [status, message] = system([gs_command(path_) '-h']); %#ok\r\n isOk = status == 0;\r\n end\r\n good = isOk;\r\nend\r\n\r\nfunction cmd = gs_command(path_)\r\n % Initialize any required system calls before calling ghostscript\r\n % TODO: in Unix/Mac, find a way to determine whether to use \"export\" (bash) or \"setenv\" (csh/tcsh)\r\n shell_cmd = '';\r\n if isunix\r\n shell_cmd = 'export LD_LIBRARY_PATH=\"\"; '; % Avoids an error on Linux with GS 9.07\r\n end\r\n if ismac\r\n shell_cmd = 'export DYLD_LIBRARY_PATH=\"\"; '; % Avoids an error on Mac with GS 9.07\r\n end\r\n % Construct the command string\r\n cmd = sprintf('%s\"%s\" ', shell_cmd, path_);\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "fix_lines.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/export-fig/fix_lines.m", "size": 6441, "source_encoding": "utf_8", "md5": "ffda929ebad8144b1e72d528fa5d9460", "text": "%FIX_LINES Improves the line style of eps files generated by print\r\n%\r\n% Examples:\r\n% fix_lines fname\r\n% fix_lines fname fname2\r\n% fstrm_out = fixlines(fstrm_in)\r\n%\r\n% This function improves the style of lines in eps files generated by\r\n% MATLAB's print function, making them more similar to those seen on\r\n% screen. Grid lines are also changed from a dashed style to a dotted\r\n% style, for greater differentiation from dashed lines.\r\n% \r\n% The function also places embedded fonts after the postscript header, in\r\n% versions of MATLAB which place the fonts first (R2006b and earlier), in\r\n% order to allow programs such as Ghostscript to find the bounding box\r\n% information.\r\n%\r\n%IN:\r\n% fname - Name or path of source eps file.\r\n% fname2 - Name or path of destination eps file. Default: same as fname.\r\n% fstrm_in - File contents of a MATLAB-generated eps file.\r\n%\r\n%OUT:\r\n% fstrm_out - Contents of the eps file with line styles fixed.\r\n\r\n% Copyright: (C) Oliver Woodford, 2008-2014\r\n\r\n% The idea of editing the EPS file to change line styles comes from Jiro\r\n% Doke's FIXPSLINESTYLE (fex id: 17928)\r\n% The idea of changing dash length with line width came from comments on\r\n% fex id: 5743, but the implementation is mine :)\r\n\r\n% Thank you to Sylvain Favrot for bringing the embedded font/bounding box\r\n% interaction in older versions of MATLAB to my attention.\r\n% Thank you to D Ko for bringing an error with eps files with tiff previews\r\n% to my attention.\r\n% Thank you to Laurence K for suggesting the check to see if the file was\r\n% opened.\r\n\r\n% 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+)\r\n% 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39\r\n\r\nfunction fstrm = fix_lines(fstrm, fname2)\r\n\r\n% Issue #20: warn users if using this function in HG2 (R2014b+)\r\nif using_hg2\r\n warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.');\r\nend\r\n \r\nif nargout == 0 || nargin > 1\r\n if nargin < 2\r\n % Overwrite the input file\r\n fname2 = fstrm;\r\n end\r\n % Read in the file\r\n fstrm = read_write_entire_textfile(fstrm);\r\nend\r\n\r\n% Move any embedded fonts after the postscript header\r\nif strcmp(fstrm(1:15), '%!PS-AdobeFont-')\r\n % Find the start and end of the header\r\n ind = regexp(fstrm, '[\\n\\r]%!PS-Adobe-');\r\n [ind2, ind2] = regexp(fstrm, '[\\n\\r]%%EndComments[\\n\\r]+');\r\n % Put the header first\r\n if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)\r\n fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);\r\n end\r\nend\r\n\r\n% Make sure all line width commands come before the line style definitions,\r\n% so that dash lengths can be based on the correct widths\r\n% Find all line style sections\r\nind = [regexp(fstrm, '[\\n\\r]SO[\\n\\r]'),... % This needs to be here even though it doesn't have dots/dashes!\r\n regexp(fstrm, '[\\n\\r]DO[\\n\\r]'),...\r\n regexp(fstrm, '[\\n\\r]DA[\\n\\r]'),...\r\n regexp(fstrm, '[\\n\\r]DD[\\n\\r]')];\r\nind = sort(ind);\r\n% Find line width commands\r\n[ind2, ind3] = regexp(fstrm, '[\\n\\r]\\d* w[\\n\\r]');\r\n% Go through each line style section and swap with any line width commands\r\n% near by\r\nb = 1;\r\nm = numel(ind);\r\nn = numel(ind2);\r\nfor a = 1:m\r\n % Go forwards width commands until we pass the current line style\r\n while b <= n && ind2(b) < ind(a)\r\n b = b + 1;\r\n end\r\n if b > n\r\n % No more width commands\r\n break;\r\n end\r\n % Check we haven't gone past another line style (including SO!)\r\n if a < m && ind2(b) > ind(a+1)\r\n continue;\r\n end\r\n % Are the commands close enough to be confident we can swap them?\r\n if (ind2(b) - ind(a)) > 8\r\n continue;\r\n end\r\n % Move the line style command below the line width command\r\n fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];\r\n b = b + 1;\r\nend\r\n\r\n% Find any grid line definitions and change to GR format\r\n% Find the DO sections again as they may have moved\r\nind = int32(regexp(fstrm, '[\\n\\r]DO[\\n\\r]'));\r\nif ~isempty(ind)\r\n % Find all occurrences of what are believed to be axes and grid lines\r\n ind2 = int32(regexp(fstrm, '[\\n\\r] *\\d* *\\d* *mt *\\d* *\\d* *L[\\n\\r]'));\r\n if ~isempty(ind2)\r\n % Now see which DO sections come just before axes and grid lines\r\n ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);\r\n ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right\r\n ind = ind(ind2);\r\n % Change any regions we believe to be grid lines to GR\r\n fstrm(ind+1) = 'G';\r\n fstrm(ind+2) = 'R';\r\n end\r\nend\r\n\r\n% Define the new styles, including the new GR format\r\n% Dot and dash lengths have two parts: a constant amount plus a line width\r\n% variable amount. The constant amount comes after dpi2point, and the\r\n% variable amount comes after currentlinewidth. If you want to change\r\n% dot/dash lengths for a one particular line style only, edit the numbers\r\n% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and\r\n% /GR (grid lines) lines for the style you want to change.\r\nnew_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width\r\n '/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width\r\n '/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines\r\n '/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines\r\n '/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines\r\n '/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines\r\n '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant\r\n\r\n% Construct the output\r\n% This is the original (memory-intensive) code:\r\n%first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section\r\n%[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');\r\n%[remaining, remaining] = strtok(remaining, '%');\r\n%fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\\r', new_style{:}) remaining];\r\nfstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\\r',new_style{:}),'%']);\r\n\r\n% Write the output file\r\nif nargout == 0 || nargin > 1\r\n read_write_entire_textfile(fname2, fstrm);\r\nend\r\nend\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "PosteriorPrediction1D.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/mcmc-utils-matlab/+mcmc/PosteriorPrediction1D.m", "size": 7063, "source_encoding": "utf_8", "md5": "3b31fa324f33b1e3af91b9ef1a04d68e", "text": "classdef PosteriorPrediction1D < handle\n\t%% PosteriorPrediction1D\n\n\tproperties\n\t\tvariableNames\n\t\tfh\n\t\txInterp\n\t\t%samples\n\t\tY\n\t\tnSamples\n\t\tsamples\n\t\tciType\n\t\tnExamples\n\t\tpointEstimateType\n\t\tpointEstimate\n\t\tshouldPlotData\n\t\txData, yData\n\t\tciWidth\n\t\th % a structure containing handles to figure and plot objects\n\tend\n\n\tproperties(Access = protected)\n\tend\n\n\n\tmethods\n\n\t\t% Class constructor\n\t\tfunction obj=PosteriorPrediction1D(fh, varargin)\n\n\t\t\tp = inputParser;\n\t\t\tp.FunctionName = mfilename;\n\t\t\tp.addRequired('fh',@(x) isa(x,'function_handle'));\n\t\t\tp.addParameter('xInterp',[],@isvector);\n\t\t\tp.addParameter('samples',[],@ismatrix);\n\t\t\tp.addParameter('variableNames',{},@iscellstr);\n\t\t\tp.addParameter('ciType','examples',@(x)any(strcmp(x,{'examples','range','probMass'})));\n\t\t\tp.addParameter('nExamples',100,@isscalar);\n\t\t\tp.addParameter('ciWidth',0.95,@isscalar);\n\t\t\tp.addParameter('pointEstimateType','mean',@isstr);\n\t\t\tp.addParameter('shouldPlotData',true,@islogical);\n\t\t\tp.addParameter('xData',[],@isvector);\n\t\t\tp.addParameter('yData',[],@isvector);\n\t\t\tp.addParameter('pointEstimate',[],@isvector);% if we have precomputed point estimate due to numerical problems (eg with log transformed data etc).\n\t\t\tp.parse(fh, varargin{:});\n\t\t\t% add p.Results fields into obj\n\t\t\tfields = fieldnames(p.Results);\n\t\t\tfor n=1:numel(fields)\n\t\t\t\tobj.(fields{n}) = p.Results.(fields{n});\n\t\t\tend\n\n\t\t\tobj.nSamples= size(obj.samples,1);\n\n\t\t\t% predefine handles for point estimates\n\t\t\tobj.h.hPointEst=[];\n\n\t\t\tif isempty(p.Results.pointEstimate)\n\t\t\t\ttemp = mcmc.UnivariateDistribution(obj.samples,...\n\t\t\t\t\t'shouldPlot',false,...\n\t\t\t\t\t'pointEstimateType',p.Results.pointEstimateType);\n\t\t\t\tobj.pointEstimate = temp.(p.Results.pointEstimateType);\n\t\t\tend\n\n\t\t\t% High-level plotting commands\n\t\t\tif p.Results.shouldPlotData\n\t\t\t\tswitch obj.ciType\n\t\t\t\t\tcase{'examples'}\n\t\t\t\t\t\tobj.plotExamples();\n\t\t\t\t\tcase{'range'}\n\t\t\t\t\t\tobj.plotCI();\n\t\t\t\t\tcase{'probMass'}\n\t\t\t\t\t\tobj.plotProbMass();\n\t\t\t\tend\n\t\t\t\taxis tight\n\t\t\t\tobj.plotPointEstimate();\n\t\t\t\tobj.plotData();\n\t\t\tend\n\t\tend\n\n\t\tfunction evaluateFunction(obj,ExamplesToPlot)\n\t\t\t% Evaluate the 1D function for the x-values specified and for\n\t\t\t% each of the MCMC samples. This will result in a matrix with:\n\t\t\t% rows = number of x-axis values\n\t\t\t% cols = number of MCMC samples\n\t\t\t\n %fprintf('Evaluating the function over %d MCMC samples...\\n', numel(ExamplesToPlot));\n\n\t\t\tif isempty(ExamplesToPlot)\n\t\t\t\tExamplesToPlot = [1:obj.nSamples];\n\t\t\tend\n\n\t\t\ttry\n\t\t\t\t% If the function handle can deal with vectorised inputs\n\t\t\t\t% then this should compute much faster\n\t\t\t\t%obj.Y = obj.fh(obj.xInterp, obj.samples(:,:))';\n\t\t\t\tobj.Y = obj.fh(obj.xInterp, obj.samples(ExamplesToPlot,:))';\n\t\t\tcatch\n\t\t\t\t% but if that fails, fall back on looping through mcmc\n\t\t\t\t% samples\n\t\t\t\twarning('*** SLOWNESS WARNING ***')\n\t\t\t\twarning('Recommend writing your function in a way that can handle vectorised inputs')\n\t\t\t\tY = zeros(numel(obj.xInterp),numel(ExamplesToPlot));\n\t\t\t\tfor s=1:numel(ExamplesToPlot)\n\t\t\t\t\tobj.Y(:,s) = obj.fh(obj.xInterp, obj.samples(ExamplesToPlot(s),:));\n\t\t\t\tend\n\t\t\tend\n\n\t\tend\n\n\n\t\tfunction obj = plotPointEstimate(obj)\n\t\t\t% Plot a single curve with the single set of parameters. These\n\t\t\t% might correspond to the mode of the MCMC parameters, for\n\t\t\t% example.\n\t\t\t% Calculate the y-values\n\t\t\tYpointEstimate = obj.fh(obj.xInterp, obj.pointEstimate);\n\t\t\t% plot the point estimate\n\t\t\thold on\n\t\t\thPointEst = plot(obj.xInterp, YpointEstimate,'k-', 'LineWidth', 3);\n\t\t\t% concatenate handle onto a list, so that we can plot multiple\n\t\t\t% point estimates and have handles to each\n\t\t\tif numel(obj.h.hPointEst)==0\n\t\t\t\tobj.h.hPointEst = hPointEst;\n\t\t\telse\n\t\t\t\tobj.h.hPointEst = [obj.h.hPointEst hPointEst];\n\t\t\tend\n\t\tend\n\n\n\t\tfunction obj = plotExamples(obj)\n\t\t\t% Plots a random set of example functions, each one corresponds\n\t\t\t% to a particular MCMC sample.\n\t\t\t% If we've asked for more examples, than MCMC samples, then\n\t\t\t% just plot all.\n\t\t\tif obj.nExamples > obj.nSamples\n\t\t\t\tobj.nExamples = obj.nSamples;\n\t\t\tend\n\t\t\t% shuffle the deck and pick the top nExamples\n\t\t\tshuffledExamples = randperm(obj.nSamples);\n\t\t\tExamplesToPlot = shuffledExamples([1:obj.nExamples]);\n\t\t\t% Evaluate the function just for these examples\n\t\t\tobj.evaluateFunction(ExamplesToPlot);\n try\n hExamples = plot(obj.xInterp, obj.Y,'-',...\n 'Color',[0.5 0.5 0.5 0.1]);\n catch % backward compatability\n hExamples = plot(obj.xInterp, obj.Y,'-',...\n 'Color',[0.5 0.5 0.5]);\n end\n\n% \t\t\thExamples = plot(obj.xInterp, obj.Y(:,ExamplesToPlot),'k-');\n\t\t\tobj.h.Axis\t\t= gca;\n\t\t\tobj.h.hExamples = hExamples;\n\t\t\tformatAxes(obj)\n\t\tend\n\n\t\tfunction obj = plotCI(obj)\n\t\t\tobj.evaluateFunction([1:obj.nSamples]);\n\t\t\t% Plots shaded 95%\n\t\t\tvals = [(1-0.95)/2 1-((1-0.95)/2)].*100;\n\t\t\tCI = prctile(obj.Y',vals);\n\t\t\t% draw the shaded error bar zone\n\t\t\tx = [obj.xInterp,fliplr(obj.xInterp)];\n\t\t\ty = [CI(2,:),fliplr(CI(1,:))];\n\t\t\thCI =patch(x,y,[0.8 0.8 0.8]);\n\t\t\thCI.EdgeColor='none';\n\t\t\t% save handle to CI\n\t\t\tobj.h.hCI = hCI;\n\t\t\tformatAxes(obj)\n\t\tend\n\n\t\tfunction obj = plotProbMass(obj)\n\t\t\t% Plots the posterior predictive distribution in the form of a\n\t\t\t% 2D probability mass function.\n\t\t\tobj.evaluateFunction([1:obj.nSamples]);\n\t\t\tyi = linspace( min(obj.Y(:)), max(obj.Y(:)), 100);\n\t\t\t[PM]=calcProbabilityMass(obj,yi);\n\t\t\thProbMass=imagesc(obj.xInterp, yi, PM);\n\t\t\taxis xy\n\t\t\t% save handle to prob mass\n\t\t\tobj.h.hExamples = hProbMass;\n\t\t\tformatAxes(obj)\n\t\tend\n\n\t\tfunction obj = plotData(obj)\n\t\t\thold on\n\t\t\tif isempty(obj.xData), return, end\n\t\t\tif isempty(obj.yData), return, end\n\t\t\tif ~obj.shouldPlotData, return, end\n\t\t\thData=plot(obj.xData,obj.yData,...\n\t\t\t\t'o',...\n\t\t\t\t'MarkerSize',8,...\n\t\t\t\t'MarkerEdgeColor','k',...\n\t\t\t\t'MarkerFaceColor','w');\n\t\t\t% save handle to data points\n\t\t\tobj.h.hData = hData;\n\t\t\tformatAxes(obj)\n\t\tend\n\n\tend\n\nend\n\n\n\n\n\n\n\n%% Private functions\n\nfunction [PM]=calcProbabilityMass(obj,yi)\n% The matrix obj.Y has a number of rows equal to the number of x-axis\n% values that we are evaluating the function over, and has a number of\n% columns equal to the number of MCMC samples provided. What we do here is\n% to loop over the x-values and convert the set of samples into a\n% probability mass function by use of the hist function. We do this for the\n% y values specified in the vector yi.\ndisplay('Calculating probability mass...')\nobj.evaluateFunction([1:obj.nSamples]);\n% preallocate\nPM = zeros(size(obj.Y,1), numel(yi));\n% loop over x-values, calculating posterior mass for the corresponding\n% samples\nfor x=1:size(obj.Y,1)\n\tPM(x,:) = hist( obj.Y(x,:) , yi );\n\t% scale so the max of each column (x-value) is equal to 1\n\tPM(x,:) =PM(x,:) / max(PM(x,:));\nend\nPM=PM'; % transpose\nend\n\n\nfunction formatAxes(obj)\nif ~isempty(obj.xData)\n\txlim([min(obj.xData) max(obj.xData)])\nend\n% axes on top layer\nah=gca; ah.Layer='top';\naxis square\nbox off\nif ~isempty(obj.variableNames)\n\txlabel(obj.variableNames{1},'Interpreter','latex')\n\tylabel(obj.variableNames{2},'Interpreter','latex')\nend\nend\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "kde.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/mcmc-utils-matlab/+mcmc/+kde/kde.m", "size": 5689, "source_encoding": "utf_8", "md5": "910728965b89850c5c417eef4698a074", "text": "function [bandwidth,density,xmesh,cdf]=kde(data,n,tstar_max,MIN,MAX)\n% Tom Edit: added a tstar_max to limit the bandwidth if desired. It is a\n% scaled value, default = inf;\n% \n% Reliable and extremely fast kernel density estimator for one-dimensional data;\n% Gaussian kernel is assumed and the bandwidth is chosen automatically;\n% Unlike many other implementations, this one is immune to problems\n% caused by multimodal densities with widely separated modes (see example). The\n% estimation does not deteriorate for multimodal densities, because we never assume\n% a parametric model for the data.\n% INPUTS:\n% data - a vector of data from which the density estimate is constructed;\n% n - the number of mesh points used in the uniform discretization of the\n% interval [MIN, MAX]; n has to be a power of two; if n is not a power of two, then\n% n is rounded up to the next power of two, i.e., n is set to n=2^ceil(log2(n));\n% the default value of n is n=2^12;\n% MIN, MAX - defines the interval [MIN,MAX] on which the density estimate is constructed;\n% the default values of MIN and MAX are:\n% MIN=min(data)-Range/10 and MAX=max(data)+Range/10, where Range=max(data)-min(data);\n% OUTPUTS:\n% bandwidth - the optimal bandwidth (Gaussian kernel assumed);\n% density - column vector of length 'n' with the values of the density\n% estimate at the grid points;\n% xmesh - the grid over which the density estimate is computed;\n% - If no output is requested, then the code automatically plots a graph of\n% the density estimate.\n% cdf - column vector of length 'n' with the values of the cdf\n% Reference:\n% Kernel density estimation via diffusion\n% Z. I. Botev, J. F. Grotowski, and D. P. Kroese (2010)\n% Annals of Statistics, Volume 38, Number 5, pages 2916-2957.\n\n%\n% Example:\n% data=[randn(100,1);randn(100,1)*2+35 ;randn(100,1)+55];\n% kde(data,2^14,min(data)-5,max(data)+5);\n\nif ~exist('tstar_max','var')\n tstar_max = inf;\nend\n\ndata=data(:); %make data a column vector\nif nargin<2 % if n is not supplied switch to the default\n n=2^14;\nend\nn=2^ceil(log2(n)); % round up n to the next power of 2;\nif nargin<5 %define the default interval [MIN,MAX]\n minimum=min(data); maximum=max(data);\n Range=maximum-minimum;\n MIN=minimum-Range/2; MAX=maximum+Range/2;\nend\n% set up the grid over which the density estimate is computed;\nR=MAX-MIN; dx=R/(n-1); xmesh=MIN+[0:dx:R]; N=length(unique(data));\n%bin the data uniformly using the grid defined above;\ninitial_data=histc(data,xmesh)/N; initial_data=initial_data/sum(initial_data);\na=dct1d(initial_data); % discrete cosine transform of initial data\n% now compute the optimal bandwidth^2 using the referenced method\nI=[1:n-1]'.^2; a2=(a(2:end)/2).^2;\n% use fzero to solve the equation t=zeta*gamma^[5](t)\nt_star=root(@(t)fixed_point(t,N,I,a2),N);\nt_star = min(t_star,tstar_max);\n% smooth the discrete cosine transform of initial data using t_star\na_t=a.*exp(-[0:n-1]'.^2*pi^2*t_star/2);\n% now apply the inverse discrete cosine transform\nif (nargout>1)|(nargout==0)\n density=idct1d(a_t)/R;\nend\n% take the rescaling of the data into account\nbandwidth=sqrt(t_star)*R;\ndensity(density<0)=eps; % remove negatives due to round-off error\nif nargout==0\n figure(1), plot(xmesh,density)\nend\n% for cdf estimation\nif nargout>3\n f=2*pi^2*sum(I.*a2.*exp(-I*pi^2*t_star));\n t_cdf=(sqrt(pi)*f*N)^(-2/3);\n % now get values of cdf on grid points using IDCT and cumsum function\n a_cdf=a.*exp(-[0:n-1]'.^2*pi^2*t_cdf/2);\n cdf=cumsum(idct1d(a_cdf))*(dx/R);\n % take the rescaling into account if the bandwidth value is required\n bandwidth_cdf=sqrt(t_cdf)*R;\nend\n\nend\n%################################################################\nfunction out=fixed_point(t,N,I,a2)\n% this implements the function t-zeta*gamma^[l](t)\nl=7;\nf=2*pi^(2*l)*sum(I.^l.*a2.*exp(-I*pi^2*t));\nfor s=l-1:-1:2\n K0=prod([1:2:2*s-1])/sqrt(2*pi); const=(1+(1/2)^(s+1/2))/3;\n time=(2*const*K0/N/f)^(2/(3+2*s));\n f=2*pi^(2*s)*sum(I.^s.*a2.*exp(-I*pi^2*time));\nend\nout=t-(2*N*sqrt(pi)*f)^(-2/5);\nend\n\n\n\n%##############################################################\nfunction out = idct1d(data)\n\n% computes the inverse discrete cosine transform\n[nrows,ncols]=size(data);\n% Compute weights\nweights = nrows*exp(i*(0:nrows-1)*pi/(2*nrows)).';\n% Compute x tilde using equation (5.93) in Jain\ndata = real(ifft(weights.*data));\n% Re-order elements of each column according to equations (5.93) and\n% (5.94) in Jain\nout = zeros(nrows,1);\nout(1:2:nrows) = data(1:nrows/2);\nout(2:2:nrows) = data(nrows:-1:nrows/2+1);\n% Reference:\n% A. K. Jain, \"Fundamentals of Digital Image\n% Processing\", pp. 150-153.\nend\n%##############################################################\n\nfunction data=dct1d(data)\n% computes the discrete cosine transform of the column vector data\n[nrows,ncols]= size(data);\n% Compute weights to multiply DFT coefficients\nweight = [1;2*(exp(-i*(1:nrows-1)*pi/(2*nrows))).'];\n% Re-order the elements of the columns of x\ndata = [ data(1:2:end,:); data(end:-2:2,:) ];\n% Multiply FFT by weights:\ndata= real(weight.* fft(data));\nend\n\nfunction t=root(f,N)\n% try to find smallest root whenever there is more than one\nN=50*(N<=50)+1050*(N>=1050)+N*((N<1050)&(N>50));\ntol=10^-12+0.01*(N-50)/1000;\nflag=0;\nwhile flag==0\n try\n t=fzero(f,[0,tol]);\n flag=1;\n catch\n tol=min(tol*2,.1); % double search interval\n end\n if tol==.1 % if all else fails\n t=fminbnd(@(x)abs(f(x)),0,.1); flag=1;\n end\nend\nend\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "kde2d.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/dependencies/mcmc-utils-matlab/+mcmc/+kde2d/kde2d.m", "size": 7506, "source_encoding": "utf_8", "md5": "6d82435d2728e267990a5041d6b289b2", "text": "function [bandwidth,density,X,Y]=kde2d(data,n,MIN_XY,MAX_XY)\r\n% fast and accurate state-of-the-art\r\n% bivariate kernel density estimator\r\n% with diagonal bandwidth matrix.\r\n% The kernel is assumed to be Gaussian.\r\n% The two bandwidth parameters are\r\n% chosen optimally without ever\r\n% using/assuming a parametric model for the data or any \"rules of thumb\".\r\n% Unlike many other procedures, this one\r\n% is immune to accuracy failures in the estimation of\r\n% multimodal densities with widely separated modes (see examples).\r\n% INPUTS: data - an N by 2 array with continuous data\r\n% n - size of the n by n grid over which the density is computed\r\n% n has to be a power of 2, otherwise n=2^ceil(log2(n));\r\n% the default value is 2^8;\r\n% MIN_XY,MAX_XY- limits of the bounding box over which the density is computed;\r\n% the format is:\r\n% MIN_XY=[lower_Xlim,lower_Ylim]\r\n% MAX_XY=[upper_Xlim,upper_Ylim].\r\n% The dafault limits are computed as:\r\n% MAX=max(data,[],1); MIN=min(data,[],1); Range=MAX-MIN;\r\n% MAX_XY=MAX+Range/4; MIN_XY=MIN-Range/4;\r\n% OUTPUT: bandwidth - a row vector with the two optimal\r\n% bandwidths for a bivaroate Gaussian kernel;\r\n% the format is:\r\n% bandwidth=[bandwidth_X, bandwidth_Y];\r\n% density - an n by n matrix containing the density values over the n by n grid;\r\n% density is not computed unless the function is asked for such an output;\r\n% X,Y - the meshgrid over which the variable \"density\" has been computed;\r\n% the intended usage is as follows:\r\n% surf(X,Y,density)\r\n% Example (simple Gaussian mixture)\r\n% clear all\r\n% % generate a Gaussian mixture with distant modes\r\n% data=[randn(500,2);\r\n% randn(500,1)+3.5, randn(500,1);];\r\n% % call the routine\r\n% [bandwidth,density,X,Y]=kde2d(data);\r\n% % plot the data and the density estimate\r\n% contour3(X,Y,density,50), hold on\r\n% plot(data(:,1),data(:,2),'r.','MarkerSize',5)\r\n%\r\n% Example (Gaussian mixture with distant modes):\r\n%\r\n% clear all\r\n% % generate a Gaussian mixture with distant modes\r\n% data=[randn(100,1), randn(100,1)/4;\r\n% randn(100,1)+18, randn(100,1);\r\n% randn(100,1)+15, randn(100,1)/2-18;];\r\n% % call the routine\r\n% [bandwidth,density,X,Y]=kde2d(data);\r\n% % plot the data and the density estimate\r\n% surf(X,Y,density,'LineStyle','none'), view([0,60])\r\n% colormap hot, hold on, alpha(.8)\r\n% set(gca, 'color', 'blue');\r\n% plot(data(:,1),data(:,2),'w.','MarkerSize',5)\r\n%\r\n% Example (Sinusoidal density):\r\n%\r\n% clear all\r\n% X=rand(1000,1); Y=sin(X*10*pi)+randn(size(X))/3; data=[X,Y];\r\n% % apply routine\r\n% [bandwidth,density,X,Y]=kde2d(data);\r\n% % plot the data and the density estimate\r\n% surf(X,Y,density,'LineStyle','none'), view([0,70])\r\n% colormap hot, hold on, alpha(.8)\r\n% set(gca, 'color', 'blue');\r\n% plot(data(:,1),data(:,2),'w.','MarkerSize',5)\r\n%\r\n% Notes: If you have a more accurate density estimator \r\n% (as measured by which routine attains the smallest \r\n% L_2 distance between the estimate and the true density) or you have \r\n% problems running this code, please email me at botev@maths.uq.edu.au \r\n\r\n\r\n% Reference: Z. I. Botev, J. F. Grotowski and D. P. Kroese\r\n% \"KERNEL DENSITY ESTIMATION VIA DIFFUSION\" ,Submitted to the\r\n% Annals of Statistics, 2009\r\nglobal N A2 I\r\nif nargin<2\r\n n=2^8;\r\nend\r\nn=2^ceil(log2(n)); % round up n to the next power of 2;\r\nN=size(data,1);\r\nif nargin<3\r\n MAX=max(data,[],1); MIN=min(data,[],1); Range=MAX-MIN;\r\n MAX_XY=MAX+Range/4; MIN_XY=MIN-Range/4;\r\nend\r\nscaling=MAX_XY-MIN_XY;\r\nif N<=size(data,2)\r\n error('data has to be an N by 2 array where each row represents a two dimensional observation')\r\nend\r\ntransformed_data=(data-repmat(MIN_XY,N,1))./repmat(scaling,N,1);\r\n%bin the data uniformly using regular grid;\r\ninitial_data=ndhist(transformed_data,n);\r\n% discrete cosine transform of initial data\r\na= dct2d(initial_data);\r\n% now compute the optimal bandwidth^2\r\n I=(0:n-1).^2; A2=a.^2;\r\n\r\n t_star=fzero( @(t)(t-evolve(t)),[0,0.1]);\r\n\r\np_02=func([0,2],t_star);p_20=func([2,0],t_star); p_11=func([1,1],t_star);\r\nt_y=(p_02^(3/4)/(4*pi*N*p_20^(3/4)*(p_11+sqrt(p_20*p_02))))^(1/3);\r\nt_x=(p_20^(3/4)/(4*pi*N*p_02^(3/4)*(p_11+sqrt(p_20*p_02))))^(1/3);\r\n% smooth the discrete cosine transform of initial data using t_star\r\na_t=exp(-(0:n-1)'.^2*pi^2*t_x/2)*exp(-(0:n-1).^2*pi^2*t_y/2).*a; \r\n% now apply the inverse discrete cosine transform\r\nif nargout>1\r\n density=idct2d(a_t)*(numel(a_t)/prod(scaling));\r\n [X,Y]=meshgrid(MIN_XY(1):scaling(1)/(n-1):MAX_XY(1),MIN_XY(2):scaling(2)/(n-1):MAX_XY(2));\r\nend\r\nbandwidth=sqrt([t_x,t_y]).*scaling; \r\nend\r\n%#######################################\r\nfunction [out,time]=evolve(t)\r\nglobal N\r\nSum_func = func([0,2],t) + func([2,0],t) + 2*func([1,1],t);\r\ntime=(2*pi*N*Sum_func)^(-1/3);\r\nout=(t-time)/time;\r\nend\r\n%#######################################\r\nfunction out=func(s,t)\r\nglobal N\r\nif sum(s)<=4\r\n Sum_func=func([s(1)+1,s(2)],t)+func([s(1),s(2)+1],t); const=(1+1/2^(sum(s)+1))/3;\r\n time=(-2*const*K(s(1))*K(s(2))/N/Sum_func)^(1/(2+sum(s)));\r\n out=psi(s,time);\r\nelse\r\n out=psi(s,t);\r\nend\r\n\r\nend\r\n%#######################################\r\nfunction out=psi(s,Time)\r\nglobal I A2\r\n% s is a vector\r\nw=exp(-I*pi^2*Time).*[1,.5*ones(1,length(I)-1)];\r\nwx=w.*(I.^s(1));\r\nwy=w.*(I.^s(2));\r\nout=(-1)^sum(s)*(wy*A2*wx')*pi^(2*sum(s));\r\nend\r\n%#######################################\r\nfunction out=K(s)\r\nout=(-1)^s*prod((1:2:2*s-1))/sqrt(2*pi);\r\nend\r\n%#######################################\r\nfunction data=dct2d(data)\r\n% computes the 2 dimensional discrete cosine transform of data\r\n% data is an nd cube\r\n[nrows,ncols]= size(data);\r\nif nrows~=ncols\r\n error('data is not a square array!')\r\nend\r\n% Compute weights to multiply DFT coefficients\r\nw = [1;2*(exp(-i*(1:nrows-1)*pi/(2*nrows))).'];\r\nweight=w(:,ones(1,ncols));\r\ndata=dct1d(dct1d(data)')';\r\n function transform1d=dct1d(x)\r\n\r\n % Re-order the elements of the columns of x\r\n x = [ x(1:2:end,:); x(end:-2:2,:) ];\r\n\r\n % Multiply FFT by weights:\r\n transform1d = real(weight.* fft(x));\r\n end\r\nend\r\n%#######################################\r\nfunction data = idct2d(data)\r\n% computes the 2 dimensional inverse discrete cosine transform\r\n[nrows,ncols]=size(data);\r\n% Compute wieghts\r\nw = exp(i*(0:nrows-1)*pi/(2*nrows)).';\r\nweights=w(:,ones(1,ncols));\r\ndata=idct1d(idct1d(data)');\r\n function out=idct1d(x)\r\n y = real(ifft(weights.*x));\r\n out = zeros(nrows,ncols);\r\n out(1:2:nrows,:) = y(1:nrows/2,:);\r\n out(2:2:nrows,:) = y(nrows:-1:nrows/2+1,:);\r\n end\r\nend\r\n%#######################################\r\nfunction binned_data=ndhist(data,M)\r\n% this function computes the histogram\r\n% of an n-dimensional data set;\r\n% 'data' is nrows by n columns\r\n% M is the number of bins used in each dimension\r\n% so that 'binned_data' is a hypercube with\r\n% size length equal to M;\r\n[nrows,ncols]=size(data);\r\nbins=zeros(nrows,ncols);\r\nfor i=1:ncols\r\n [dum,bins(:,i)] = histc(data(:,i),[0:1/M:1],1);\r\n bins(:,i) = min(bins(:,i),M);\r\nend\r\n% Combine the vectors of 1D bin counts into a grid of nD bin\r\n% counts.\r\nbinned_data = accumarray(bins(all(bins>0,2),:),1/nrows,M(ones(1,ncols)));\r\nend\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "my_shaded_errorbar_zone_UL.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-toolbox/utils-plotting/my_shaded_errorbar_zone_UL.m", "size": 815, "source_encoding": "utf_8", "md5": "5455a1384ba84136387029c983c8a775", "text": "function [h]=my_shaded_errorbar_zone_UL(x,upper,lower,col)\r\n% Plots a shaded region of error\r\n%\r\n% my_shaded_errorbar_zone_UL([-10:0.1:10],[-10:0.1:10]+1,[-10:0.1:10]-1,[0.7 0.7 0.7])\r\n%\r\n% eg, my_shaded_errorbar_zone([-10:0.1:10],x,abs(randn(size(x)))+2,[0 0 1])\r\n%\r\n%handle=patch([x max(x)-x+min(x)],[y+e flipud(y'-e')'],[0.8 0.8 0.8]);\r\n%handle=patch([x max(x)-x+min(x)],[upper flipud(lower')'],[0.8 0.8 0.8]);\r\n%\r\n%\r\n% written by: Benjamin T Vincent\r\n\r\nh = holdDecorator( plotErrorBarZone(x, upper, lower, col) );\r\n\r\nend\r\n\r\nfunction h = plotErrorBarZone(x, upper, lower, col)\r\n% draw the shaded error bar zone\r\nx = [x, fliplr(x)];\r\ny = [upper, fliplr(lower)];\r\nh = patch(x, y, [0.8 0.8 0.8]);\r\n% formatting\r\nuistack(h,'bottom')\r\nset(h,'EdgeColor','none')\r\nset(h,'FaceColor',col)\r\nset(h,'FaceAlpha',0.5)\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "plotUtilityFunction.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-experiments/@Model/plotUtilityFunction.m", "size": 2211, "source_encoding": "utf_8", "md5": "e70f242efd3d46c6ec678cceec49d126", "text": "function plotUtilityFunction(obj, thetaStruct, varargin)\n\np = inputParser;\np.FunctionName = mfilename;\np.addRequired('thetaStruct',@isstruct_or_table);\n% p.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'})));\np.addParameter('data',[],@istable);\np.addParameter('pointEstimateType','mean',@isstr);\n% p.addParameter('maxDelay', [], @isscalar);\np.addParameter('utility_func_function_handle','', @(x) isa(x,'function_handle'))\np.parse(thetaStruct, varargin{:});\ndata = p.Results.data;\n\nplotCurve(data, thetaStruct, p.Results.utility_func_function_handle, p)\n%plotData(data);\nformatAxes(data, p);\nend\n\n\nfunction plotCurve(data, thetaStruct, utility_func_function_handle, p)\n\n\n% create set of rewards to calculate & plot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nxVals = linspace(-100, 100, 100);\n\n% evaluate and plot just the first N particles\nN = 200;\nfnames = fieldnames(thetaStruct);\nfor n=1:numel(fnames)\n thetaStruct.(fnames{n}) = thetaStruct.(fnames{n})([1:N]);\nend\n\n% calculate discount fraction for the given theta samples ~~~~~~~~~~~~~~\nprospect.reward = xVals;\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nutilityOfReward = utility_func_function_handle(prospect, thetaStruct);\n\nplot(xVals, utilityOfReward,...\n 'Color',[0 0.4 1 0.1])\n\nhold on\n\n%% plot posterior median as black line\nfor n=1:numel(fnames)\n thetaStruct.(fnames{n}) = median(thetaStruct.(fnames{n}));\nend\nprospect.reward = xVals;\nutilityOfReward = utility_func_function_handle(prospect, thetaStruct);\nplot(xVals, utilityOfReward,...\n 'Color', 'k',...\n 'LineWidth', 2)\n\nend\n\n\nfunction formatAxes(data, p)\n%opts = calc_opts(data, p);\nxlabel('$R$', 'interpreter','Latex')\nylabel('$u(R)$', 'interpreter','Latex')\n\nset(gca,'XAxisLocation','origin',...\n 'YAxisLocation','origin',...\n 'box', 'off')\n% box off\n% a = get(gca,'YLim');\n% if opts.maxX>0\n% \txlim( [0 opts.maxX] )\n% end\n% ylim([0 min([a(2),10]) ])\ndrawnow\nend\n\n% function opts = calc_opts(data, p)\n% if ~isempty(data)\n% \topts.maxlogB\t= max( abs(data.R_B) );\n% \topts.maxX\t\t= max( data.D_B ) *1.1;\n% else\n% \topts.maxlogB\t= 1000;\n% \topts.maxX\t\t= 20;\n% end\n% \n% if ~isempty(p.Results.maxDelay)\n% \topts.maxX = p.Results.maxDelay;\n% end\n% end\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "plotProbFunction.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-experiments/@Model/plotProbFunction.m", "size": 4833, "source_encoding": "utf_8", "md5": "2fd2b28515f7226b9bda9d45b14e68a6", "text": "function plotProbFunction(obj, thetaStruct, varargin)\n\np = inputParser;\np.FunctionName = mfilename;\np.addRequired('thetaStruct',@isstruct_or_table);\np.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'})));\np.addParameter('data',[],@istable);\np.addParameter('pointEstimateType','mean',@isstr);\np.addParameter('discounting_function_handle','', @(x) isa(x,'function_handle'))\np.parse(thetaStruct, varargin{:});\ndata = p.Results.data;\n\nplotCurve(data, thetaStruct, p.Results.discounting_function_handle, p)\nplotData(data);\nformatAxes(data);\nend\n\n\nfunction plotCurve(data, thetaStruct, discounting_function_handle, p)\n\nswitch p.Results.xScale\n\tcase{'linear'}\n\t\t\n\t\txProbVector = linspace(10^-4, 1, 1000);\n\t\txOddsVector = prob2oddsagainst(xProbVector);\n\t\t\n% \t\t% create set of probs to calculate & plot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n% \t\tif isempty(data)\n% \t\t\txOddsVector = linspace(0,100,1000);\n% \t\telse\n% \t\t\txOddsVector = linspace(0,100,1000);\n% % % zoom to data (only useful with the odds discounting type plot)\n% % \t\t\txOddsVector = xOddsVector( xOddsVector < max(prob2oddsagainst(data.P_B)));\n% \t\tend\n% \t\t% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n \n %% Plot calibration line for h = 1 = risk neutral\n risk_neutral = 1 ./ (1+1.*xOddsVector); % hyperbolic discounting function\n\t\t\n\t\t% converting x axis from odds to probability makes it like the\n\t\t% traditional \"probability weighting plot\", as opposed to the\n\t\t% \"discounting of odds plot\"\n plot(oddsagainst2prob(xOddsVector), risk_neutral, '--',...\n 'Color', [0.7 0.7 0.7],...\n 'LineWidth', 4)\n hold on\n \n % evaluate and plot just the first N particles\n N = 200;\n fnames = fieldnames(thetaStruct);\n\t\tfor n=1:numel(fnames)\n\t\t\tthetaStruct.(fnames{n}) = thetaStruct.(fnames{n})([1:N]);\n\t\tend\n\t\t\n\t\t% calculate discount fraction for the given theta samples ~~~~~~~~~~~~~~\n\t\tprospect.prob = xProbVector;\n\t\t% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\tdF = discounting_function_handle(prospect, thetaStruct);\n\t\t\n\t\tplot(oddsagainst2prob(xOddsVector), dF,...\n\t\t\t'Color',[0 0.4 1 0.1])\n hold on\n \n %% plot posterior median as black line\n for n=1:numel(fnames)\n thetaStruct.(fnames{n}) = median(thetaStruct.(fnames{n}));\n end\n prospect.prob = xProbVector;\n utilityOfReward = discounting_function_handle(prospect, thetaStruct);\n plot(oddsagainst2prob(xOddsVector), utilityOfReward,...\n 'Color', 'k',...\n 'LineWidth', 2)\n\t\t\n\tcase{'log'}\n\t\terror('not yet implemented plotting discount fractions with log x-axis')\nend\nend\n\n\nfunction plotData(data)\nif isempty(data)\n\treturn\nend\n[x, y, markerCol, markerSize] = convertDataIntoMarkers(data);\nplotMarkers(oddsagainst2prob(x), y, markerCol, markerSize)\nend\n\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nfunction [x, y, markerCol, markerSize] = convertDataIntoMarkers(data)\n% find unique experimental designs\nuniqueDesigns = [abs(data.R_A), abs(data.R_B), data.P_A, data.P_B, data.D_A, data.D_B];\n[C, ia, ic] = unique(uniqueDesigns, 'rows');\n%loop over unique designs (ic)\nfor n=1:max(ic)\n\t% binary set of which trials this design was used on\n\tmyset = ic==n;\n\t% Size = number of times this design has been run\n\tF(n) = sum(myset);\n\t% Colour = proportion of times that participant chose immediate\n\t% for that design\n\tmarkerCol(n) = sum(data.R(myset)==0) ./ F(n);\n\t\n\tmarkerSize(n) = F(n);\n\t\n\tx(n) = prob2oddsagainst(data.P_B( ia(n) ));\n\ty(n) = abs(data.R_A( ia(n) )) ./ abs(data.R_B( ia(n) ));\nend\nend\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nfunction plotMarkers(x, y, markerCol, markerSize)\nhold on\nfor i=1:max(numel(x))\n\th = plot(x(i), y(i),'o');\n\th.Color='k';\n\th.MarkerFaceColor=[1 1 1] .* (1-markerCol(i));\n\th.MarkerSize = markerSize(i)+4;\n\thold on\nend\nend\n\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nfunction formatAxes(data)\nopts = calc_opts(data);\nxlabel('odds against Prospect B', 'interpreter','Latex')\nxlabel('objective probability, $P$', 'interpreter','Latex')\nylabel('$\\pi(P)$', 'interpreter','Latex')\nbox off\n% a = get(gca,'YLim');\n% if opts.maxX > 0\n% \txlim( [0 opts.maxX*1.1] )\n% else\n% x=get(gca,'XLim');\n% xlim([0 a(2)])\n% end\nxlim([0 1])\nylim([0 1])\n\n%% Add descriptive helper text\naddTextToFigure('TL', 'risk seeking domain', 10)\naddTextToFigure('BR', 'risk avoidant domain', 10)\n\ndrawnow\nend\n\nfunction opts = calc_opts(data)\nif ~isempty(data)\n\topts.maxlogB\t= max( abs(data.R_B) );\n\topts.maxX\t\t= max( prob2oddsagainst(data.P_B) );\nelse\n\topts.maxlogB\t= 1000;\n\topts.maxX\t\t= 365;\nend\nend\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "plotDiscountFunction.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-experiments/@Model/plotDiscountFunction.m", "size": 4074, "source_encoding": "UNKNOWN", "md5": "cd3e7d94e8978e564eef501175a3a9c6", "text": "function plotDiscountFunction(obj, thetaStruct, varargin)\n\np = inputParser;\np.FunctionName = mfilename;\np.addRequired('thetaStruct',@isstruct_or_table);\np.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'})));\np.addParameter('data',[],@istable);\np.addParameter('pointEstimateType','mean',@isstr);\np.addParameter('maxDelay', [], @isscalar);\np.addParameter('discounting_function_handle','', @(x) isa(x,'function_handle'))\np.parse(thetaStruct, varargin{:});\ndata = p.Results.data;\n\nplotCurve(data, thetaStruct, p.Results.discounting_function_handle, p)\nplotData(data);\nformatAxes(data, p);\nend\n\n\nfunction plotCurve(data, thetaStruct, discounting_function_handle, p)\n\nswitch p.Results.xScale\n\tcase{'linear'}\n\n\t\t% create set of delays to calculate & plot ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\tif ~isempty(p.Results.maxDelay)\n\t\t% if isempty(data)\n\t\t\txVals = logspace(-3,3,1000);\n\t\t\txVals = xVals(xVals0\n\txlim( [0 opts.maxX] )\nelse\n x=get(gca,'XLim');\n xlim([0 a(2)])\nend\nylim([0 min(10, max([a(2),1])) ])\n\n%% Add descriptive helper text\naddTextToFigure('TR', 'choose immediate', 10, 'Color', [0.7 0.7 0.7])\naddTextToFigure('BL', ' choose delayed', 10, 'Color', [0.7 0.7 0.7])\n\ndrawnow\nend\n\nfunction opts = calc_opts(data, p)\nif ~isempty(data)\n\topts.maxlogB\t= max( abs(data.R_B) );\n\topts.maxX\t\t= max( data.D_B ) *1.1;\nelse\n\topts.maxlogB\t= 1000;\n\topts.maxX\t\t= 20;\nend\n\nif ~isempty(p.Results.maxDelay)\n\topts.maxX = p.Results.maxDelay;\nend\nend\n% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "plotDiscountSurface.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-experiments/@Model_hyperbolic1_time_and_prob/plotDiscountSurface.m", "size": 4143, "source_encoding": "UNKNOWN", "md5": "09dea0179f9b5215e875502ae0b37f08", "text": "function plotDiscountSurface(obj, thetaStruct, varargin)\n% plots prob and time discount surface\n\np = inputParser;\np.FunctionName = mfilename;\np.addRequired('thetaStruct',@isstruct);\np.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'})));\np.addParameter('data',[],@isstruct_or_table)\np.addParameter('pointEstimateType','mean',@isstr);\np.addParameter('prob_discounting_function_handle','', @(x) isa(x,'function_handle'))\np.addParameter('time_discounting_function_handle','', @(x) isa(x,'function_handle'))\np.parse(thetaStruct, varargin{:});\ndata = p.Results.data;\n\nplotSurface(data, thetaStruct, p.Results.prob_discounting_function_handle, p.Results.time_discounting_function_handle, p)\nplotData(data)\nformatAxes(data);\ntitle({'P_A chance of �R_A in D_A days','P_B chance of �R_B in D_B days'})\nend\n\n\nfunction plotSurface(data, thetaStruct, probDiscountingFunctionFH, timeDiscountingFunctionFH, p)\n\n% create set of delays to calculate & plot\nN_DELAYS = 10;\nN_ODDS = 12;\nif isempty(data)\n\tdelays = linspace(0,365,N_DELAYS);\nelse\n\tmax_delay_of_data = max([ data.D_A; data.D_B]);\n\tdelays = linspace(0, max_delay_of_data, N_DELAYS);\nend\n\nif isempty(data)\n\todds = linspace(0, 20, N_ODDS);\nelse\n\todds = linspace(0, max(prob2oddsagainst(data.P_B)), N_ODDS);\nend\n\n% Evaluate only the posterior median\nfnames = fieldnames(thetaStruct);\nfor n=1:numel(fnames)\n\tthetaStruct.(fnames{n}) = median(thetaStruct.(fnames{n}));\nend\n\nwarning('CREATE THIS NESTED PARAMETER STRUCTURE AUTOMATICALLY')\nnestedParamStruct.prob.h = thetaStruct.h;\nnestedParamStruct.delay.logk = thetaStruct.logk;\n\n%opts = calc_opts(data);\n\n% create grid of values\n[odds_grid, delays_grid] = meshgrid(odds,delays); % create x,y (b,d) grid values\n\nwarning('this is duplication of model.calcPresentSubjectiveValue()')\nprospect.reward = [];\nprospect.delay = delays_grid(:);\nprospect.prob = oddsagainst2prob(odds_grid(:));\nV = ...\n\tprobDiscountingFunctionFH(prospect, nestedParamStruct.prob) .* ...\n\ttimeDiscountingFunctionFH(prospect, nestedParamStruct.delay);\nV = reshape(V, size(odds_grid));\n\n\n\n%% PLOT\nhmesh = mesh(odds_grid, delays_grid, V);\n% shading\nhmesh.FaceColor\t\t='w';\nhmesh.FaceAlpha\t\t=0.7;\n% edges\nhmesh.MeshStyle\t\t='both';\nhmesh.EdgeColor\t\t='k';\nhmesh.EdgeAlpha\t\t=1;\n\n% plot isolines\nhold on\n[c,h] = contour3(odds_grid, delays_grid, V, [0.2:0.2:0.8]);\nh.LineColor = 'k';\nh.LineWidth = 4;\nend\n\nfunction plotData(data)\nif isempty(data)\n\treturn\nend\n[x,y,z,markerCol,markerSize] = convertDataIntoMarkers(data);\nplotMarkers(x, y, z, markerCol, markerSize)\nend\n\nfunction [x,y,z,markerCol,markerSize] = convertDataIntoMarkers(data)\n% find unique experimental designs\nuniqueDelays = [abs(data.R_A), abs(data.R_B), data.D_A, data.D_B, data.D_A, data.D_B];\n[C, ia, ic] = unique(uniqueDelays,'rows');\n% loop over unique designs (ic)\nfor n=1:max(ic)\n\t% binary set of which trials this design was used on\n\tmyset=ic==n;\n\t% markerSize = number of times this design has been run\n\tmarkerSize(n) = sum(myset);\n\t% Colour = proportion of times participant chose immediate for that design\n\tmarkerCol(n) = sum(data.R(myset)==0) ./ markerSize(n);\n\t\n\tx(n) = prob2oddsagainst( data.P_B( ia(n) ) ); % odds against\n\ty(n) = data.D_B( ia(n) ); % delay\n\tz(n) = abs(data.R_A(ia(n))) ./ abs(data.R_B( ia(n)));\nend\nend\n\nfunction plotMarkers(x, y, z, markerCol, markerSize)\nhold on\nfor i=1:numel(x)\n\th = stem3(x(i), y(i), z(i));\n\th.Color='k';\n\th.MarkerFaceColor=[1 1 1] .* (1-markerCol(i));\n\th.MarkerSize = markerSize(i)+4;\n\thold on\nend\nend\n\nfunction formatAxes(data)\n%opts = calc_opts(data);\nxlabel('Odds against, $\\frac{1-P^B}{P^B}$', 'interpreter','latex')\nylabel('delay $D^B$', 'interpreter','latex')\nzlabel('discount factor (and $\\frac{R_A}{R_B}$)', 'interpreter','latex')\n\nview([90+45, 20])\naxis vis3d\naxis tight\naxis square\nzlim([0 1])\ncamproj('perspective')\nset(gca,'ZTick',[0:0.2:1])\nend\n\nfunction opts = calc_opts(data)\nif ~isempty(data)\n\topts.maxlogB\t= max( abs(data.R_B) );\n\topts.maxD\t\t= max( data.D_B );\nelse\n\topts.maxlogB\t= 1000;\n\topts.maxD\t\t= 365;\nend\n\n% what does this even do?\nopts.nIndifferenceLines = 10;\npow=1; while opts.maxlogB > 10^pow; pow=pow+1; end\nopts.pow = pow;\nend\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "plotDiscountSurface.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-experiments/@Model_hyperbolic1ME_time/plotDiscountSurface.m", "size": 3941, "source_encoding": "UNKNOWN", "md5": "5e5f8fc832f6a6154c0225d60dd272f9", "text": "function plotDiscountSurface(obj, thetaStruct, varargin)\n\np = inputParser;\np.FunctionName = mfilename;\np.addRequired('thetaStruct',@isstruct);\np.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'})));\np.addParameter('data',[],@isstruct_or_table)\np.addParameter('pointEstimateType','mean',@isstr);\np.addParameter('discounting_function_handle','', @(x) isa(x,'function_handle'))\np.parse(thetaStruct, varargin{:});\ndata = p.Results.data;\n\nplotSurface(data, thetaStruct, p.Results.discounting_function_handle, p)\nplotData(data)\nformatAxes(data);\nend\n\n\nfunction plotSurface(data, thetaStruct, discounting_function_handle, p)\n\n% create set of delays to calculate & plot\nN_DELAYS = 10;\nif isempty(data)\n\tdelays = linspace(0,365,N_DELAYS);\nelse\n\tmax_delay_of_data = max([ data.D_A; data.D_B]);\n\tdelays = linspace(0, max_delay_of_data, N_DELAYS);\nend\n\nopts = calc_opts(data);\n\n%% x-axis = b\nN_REWARDS = 10;\nlogbvec = log(logspace(1, opts.pow, N_REWARDS));\n\n% %% y-axis = d\n% dvec = linspace(0, opts.maxD, 15);\n\n%% z-axis (AB)\n[logB,D] = meshgrid(logbvec,delays); % create x,y (b,d) grid values\n\n% -------------------------------------------------------------------------\nwarning('Stop doing this kludge and do it properly (see below)')\nm = median(thetaStruct.m);\nc = median(thetaStruct.c);\nk\t\t= exp(m .* logB + c); % magnitude effect\nAB\t\t= 1 ./ (1 + k.*D); % hyperbolic discount function\n% DO IT PROPERLY, LIKE BELOW ----------------------------------------------\n% delays = D;\n% reward = exp(logB);\n% prospect.reward = reward';\n% prospect.delay = delays';\n% pointEst.m = median(thetaStruct.m);\n% pointEst.c = median(thetaStruct.c);\n% AB = discounting_function_handle(prospect, pointEst);\n% -------------------------------------------------------------------------\n\n%% PLOT\nR_B = exp(logB);\nhmesh = mesh(R_B, D, AB);\n% shading\nhmesh.FaceColor\t\t='w';\nhmesh.FaceAlpha\t\t=0.7;\n% edges\nhmesh.MeshStyle\t\t='both';\nhmesh.EdgeColor\t\t='k';\nhmesh.EdgeAlpha\t\t=1;\n\n% plot isolines\nhold on\n[c,h] = contour3(R_B, D, AB, [0.2:0.2:0.8]);\nh.LineColor = 'k';\nh.LineWidth = 4;\n\nend\n\nfunction plotData(data)\nif isempty(data)\n\treturn\nend\n[x,y,z,markerCol,markerSize] = convertDataIntoMarkers(data);\nplotMarkers(x, y, z, markerCol, markerSize)\nend\n\nfunction [x,y,z,markerCol,markerSize] = convertDataIntoMarkers(data)\n% find unique experimental designs\nD=[abs(data.R_A), abs(data.R_B), data.D_A, data.D_B];\n[C, ia, ic] = unique(D,'rows');\n% loop over unique designs (ic)\nfor n=1:max(ic)\n\t% binary set of which trials this design was used on\n\tmyset=ic==n;\n\t% markerSize = number of times this design has been run\n\tmarkerSize(n) = sum(myset);\n\t% Colour = proportion of times participant chose immediate for that design\n\tmarkerCol(n) = sum(data.R(myset)==0) ./ markerSize(n);\n\n\tx(n) = abs(data.R_B( ia(n) )); % �R_B\n\ty(n) = data.D_B( ia(n) ); % delay to get �R_B\n\t%z(n) = abs(data.R_A_over_R_B( ia(n) ).*data.R_B( ia(n) )) ./ abs(data.R_B( ia(n) ));\n\tz(n) = abs(data.R_A(ia(n))) ./ abs(data.R_B( ia(n)));\nend\nend\n\nfunction plotMarkers(x, y, z, markerCol, markerSize)\nhold on\nfor i=1:numel(x)\n\th = stem3(x(i), y(i), z(i));\n\th.Color='k';\n\th.MarkerFaceColor=[1 1 1] .* (1-markerCol(i));\n\th.MarkerSize = markerSize(i)+4;\n\thold on\nend\nend\n\nfunction formatAxes(data)\nxlabel('$|R^L|$', 'interpreter','latex')\nylabel('delay $D^b$', 'interpreter','latex')\nzlabel('discount factor (and $\\frac{R_A}{R_B}$)', 'interpreter','latex')\n\nopts = calc_opts(data);\nview([90+45, 20])\naxis vis3d\naxis tight\naxis square\nzlim([0 1])\nset(gca,...\n\t'XDir','reverse',...\n\t'XScale','log',...\n\t'XTick',logspace(1,opts.pow,opts.pow-1+1))\nset(gca,'ZTick',[0:0.2:1])\ncamproj('perspective')\nend\n\nfunction opts = calc_opts(data)\nif ~isempty(data)\n\topts.maxlogB\t= max( abs(data.R_B) );\n\topts.maxD\t\t= max( data.D_B );\nelse\n\topts.maxlogB\t= 1000;\n\topts.maxD\t\t= 365;\nend\n\n% what does this even do?\nopts.nIndifferenceLines = 10;\npow=1; while opts.maxlogB > 10^pow; pow=pow+1; end\nopts.pow = pow;\nend\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "generate_designs.m", "ext": ".m", "path": "darc-experiments-matlab-master/darc-experiments/response_error_types/@ChoiceFuncPsychometric/generate_designs.m", "size": 9159, "source_encoding": "utf_8", "md5": "76956e5e60901d47f17673051e41dc9a", "text": "function designs_allowed = generate_designs(obj, previous_designs, responses, thetas)\n%generate_designs\n%\n% Create a matrix of possible designs. These will be considered by our\n% optimization procedure.\n%\n% Inputs\n%\n% Outputs\n% designs_allowed: A matrix of designs. Each column is one component of the\n%\t\t\t\tdesign space. Each row is one design.\n%\n% Tom Rainforth 01/10/16\n\n%% Setup options and variables\n\nfree_design_fields = obj.design_variables(~obj.is_design_variable_fixed());\nfree_design_vals = struct;\nfor n=1:numel(free_design_fields)\n free_design_vals.(free_design_fields{n}) = obj.(free_design_fields{n});\nend\n\nfixed_design_fields = obj.design_variables(obj.is_design_variable_fixed());\nfixed_design_vals = struct;\nfor n=1:numel(fixed_design_fields)\n fixed_design_vals.(fixed_design_fields{n}) = obj.(fixed_design_fields{n});\nend\n\n% Load previous designs into the workspace\nobj.unpackDesigns(previous_designs);\n\nn_d = size(previous_designs,1);\nmod_h = mod(n_d,1/obj.heuristic_rate);\nb_use_heuristic = ~isnan(mod_h) && mod_h<0.9999; % Numerical stability\nif b_use_heuristic\n strategy = obj.heuristic_strategy;\nelse\n strategy = 'no_heuristic';\nend\n\n%% Read in designs\n\nif strcmpi(strategy,'random_no_replacement')\n % This is the old strategy that uses the heuristic order and then\n % randomly chooses all but the number. For this not all designs are\n % evaluated\n \n free_params = obj.params(~obj.is_theta_fixed());\n free_params = setdiff(free_params,{'alpha','epsilon'}); % Ignore alpha and epsilon\n n_design_allowed = numel(free_params);\n n_designs_to_set = numel(free_design_fields)-n_design_allowed;\n \n heuristic_counter = 1;\n \n for n=1:numel(obj.heuristic_order)\n if heuristic_counter > n_designs_to_set\n break\n end\n if any(strcmp(obj.heuristic_order{n},free_design_fields))\n eval(['heuristic_value = random_no_replacement(obj,' obj.heuristic_order{n} ',''' obj.heuristic_order{n} ''');']);\n free_design_vals = rmfield(free_design_vals,obj.heuristic_order{n});\n fixed_design_vals.(obj.heuristic_order{n}) = heuristic_value;\n heuristic_counter = heuristic_counter+1;\n end\n end\n designs_allowed = gen_designs(obj,free_design_vals,fixed_design_vals);\nelse\n % Other strategies start by laying out all the designs\n \n % First generate all the possible designs\n designs_allowed = gen_designs(obj,free_design_vals,fixed_design_vals);\nend\n\n%% Eliminate designs already tried of with no chance of being helpful\n\n% Eliminate designs already tried\nif ~isempty(previous_designs)\n designs_allowed = setdiff(designs_allowed,previous_designs,'rows');\nend\n\n% Eliminate designs whose response is effectively known using the point\n% estimate\n% Now make a point estimate for theta and use it to calculate the\n% sooner and later subjective values for all of these possible\n% designs\ntheta = point_estimate_theta(obj,thetas,'mean');\nalpha = [];\nobj.unpackTheta(theta);\n[VA, VB] = obj.subjective_values(theta,designs_allowed);\nVsum = VA+VB;\nVdiff = VB-VA;\n\n% Eliminate Vsum points where the response is effectively certain\n% such that these are clearly poor designs\np_raw = normcdf(Vdiff/alpha); % Prob response ignoring epsilon\nb_extreme = p_raw<0.005 | p_raw>0.995;\nn_not_extreme = sum(~b_extreme);\nif n_not_extreme<10\n % Cop out as we don't have a reasonable number of sensible\n % designs left, take the ten smallest differences (with some\n % noise to split ties randomly)\n [~,is] = sort(abs(Vdiff)+(1e-10)*rand(size(Vdiff)));\n n_take = min(10,numel(is));\n designs_allowed = designs_allowed(is(1:n_take),:);\n return\nend\nVsum = Vsum(~b_extreme);\np_raw = p_raw(~b_extreme);\ndesigns_allowed = designs_allowed(~b_extreme,:);\n\n%% Do further design elimination heuristics\n\nif any(strcmpi(strategy,{'no_heuristic','random_no_replacement'}))\n \n % For no_heuristic heuristic and random_no_replacement we are now done\n \nelseif strcmpi(strategy,'subjective_value_spreading')\n \n \n if size(previous_designs,1)<4 % Old was 2\n % Not enough previous designs. Let the experimental design\n % method do its magic\n return\n end\n \n % Use a kernel density estimator to get the distribution of\n % Vsum and evaluate at the Vsum points.\n [VSp,VLp] = obj.subjective_values(theta,previous_designs);\n Vpsum = VSp+VLp;\n Vpdiff = VLp-VSp;\n p_raw_p = normcdf(Vpdiff/alpha);\n b_p_extreme = p_raw_p<0.005 | p_raw_p>0.995;\n if sum(~b_p_extreme) > 3 % Old was 1\n % We don't care about even spacing with what turned out to\n % be useless questions. We want an even spacing of the\n % pertinent ones. Therefore we only look at distance to\n % helpful questions for choosing were to go.\n Vpsum = Vpsum(~b_p_extreme);\n Vpdiff = Vpdiff(~b_p_extreme);\n else\n % There are 3 or less useful questions remain so again don't\n % care about even space. Let the optimizer do its magic\n return\n end\n % Find the point in Vsum space that is further from previous\n % values using\n hard_coded_scale = 0.1;\n Vden = kernel_dist(Vsum,Vpsum,hard_coded_scale*(max(Vsum)-min(Vsum)));\n [~,imin] = min(Vden);\n \n % Now only look at points that are close to this in Vsum space.\n % What we will do is to chop up the p_raw space (i.e. bin the\n % output probabilities, ignoring epsilon) and then choose the\n % closest sample to Vsum(imin) in each bin. This gives a good\n % spread of probabilities while maintaining points close the target\n % Vsum.\n VsumDiff = Vsum-Vsum(imin);\n % Partitions are uneven as more likely to want to be near the\n % middle, for now will be even though\n bin_pos = 0:(1/obj.n_design_opt):1;\n %bin_pos = betacdf(0:(1/obj.n_design_opt):1,0.5,0.5); % Alternative\n %for uneven\n [~,i_bin] = histc(p_raw,bin_pos);\n % Sort first by bin then the absolute difference to target point.\n [i_p,i_s] = sortrows([i_bin,abs(VsumDiff)]);\n % Take the first of each type\n i_take = [1;1+find(diff(i_p(:,1))~=0)];\n prob_diffs_take = i_p(i_take,2)/(max(Vsum)-min(Vsum));\n % We want to eliminate any differences that are too high without\n % removing all of them\n hard_closeness_coded_threshold = 0.4/sqrt(size(previous_designs,1));\n b_too_far = prob_diffs_take>hard_closeness_coded_threshold;\n i_take = i_take(~b_too_far);\n designs_allowed = designs_allowed(i_s(i_take),:);\n \n % To see whats going on set below to true\n b_debug_plot = false;\n \n if b_debug_plot && size(previous_designs,1)>2 && size(previous_designs,1)>5 && mod(size(previous_designs,1),5)==0\n % First lets look at Vsum vs p_raw for the candidates (blue),\n % previous designs (red), and designes selected to be allowed\n % (green).\n figure;\n plot(VA+VB,normcdf((VB-VA)/alpha),'x');\n hold on;\n plot([Vsum(imin),Vsum(imin)],[0,1],'--g','LineWidth',2);\n plot(Vpsum,normcdf(Vpdiff/alpha),'rx','MarkerSize',6,'LineWidth',4);\n [VSdebug,VLdebug] = obj.subjective_values(theta,designs_allowed);\n plot(VSdebug+VLdebug,normcdf((VLdebug-VSdebug)/alpha),'gx','MarkerSize',6,'LineWidth',4);\n % Now lets look at the density of previously chosen Vrank's\n % along with their positions and the new allowed positions.\n figure;\n plot(Vsum,Vden,'x');\n hold on;\n plot(Vpsum,zeros(size(Vpsum)),'rx','MarkerSize',6,'LineWidth',4);\n plot(VSdebug+VLdebug,zeros(size(VSdebug)),'gx','MarkerSize',6,'LineWidth',4);\n % Pause to let us look\n keyboard;\n end\n \nend\n\nend\n\nfunction designs_allowed = gen_designs(obj,free_design_vals,fixed_design_vals)\n\nfree_design_fields = fields(free_design_vals);\n% Generates variables in this file for the previous design variables\n\ndesign_vars = fixed_design_vals;\nfor m=1:numel(free_design_fields)\n design_vars.(free_design_fields{m}) = free_design_vals.(free_design_fields{m});\nend\n\nnd_grid_string = '[';\nfor m=1:numel(obj.design_variables)\n nd_grid_string = [nd_grid_string, obj.design_variables{m} ','];\nend\nnd_grid_string = [nd_grid_string(1:end-1) '] = ndgrid('];\nfor m=1:numel(obj.design_variables)\n nd_grid_string = [nd_grid_string, 'design_vars.' obj.design_variables{m} ','];\nend\nnd_grid_string = [nd_grid_string(1:end-1) ');'];\neval(nd_grid_string);\n\ndesigns_allowed = [];\nfor m=1:numel(fields(design_vars))\n eval(['designs_allowed = [designs_allowed,' obj.design_variables{m} '(:)];']);\nend\n\nend\n\nfunction v = random_no_replacement(obj,previous_vals,var_name)\nallowed_vals = obj.(var_name);\nleft_vals = setdiff(allowed_vals,previous_vals);\nif isempty(left_vals)\n [~,i_int] = unique(previous_vals);\n i_left = setdiff(1:numel(previous_vals),i_int);\n twice_vals = previous_vals(i_left);\n if isempty(twice_vals)\n left_vals = previous_vals;\n else\n v = random_no_replacement(obj,twice_vals,var_name);\n return\n end\nend\nv = datasample(left_vals,1);\n\nend\n\nfunction d = kernel_dist(V1,V2,scale)\n\nd = mean(exp(-(bsxfun(@minus,V1,V2').^2)/scale^2),2);\n\nend"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "SCRIPT_logk_comparison_of_methods.m", "ext": ".m", "path": "darc-experiments-matlab-master/generate_figs_for_paper/SCRIPT_logk_comparison_of_methods.m", "size": 3145, "source_encoding": "utf_8", "md5": "e64012ec647f029f09c5a77568cecc0c", "text": "function SCRIPT_logk_comparison_of_methods()\n\naddpath('darc-experiments')\n\n\n%% Sort figure and subpanel arrangement\nfh = figure(56); clf, drawnow\nset(fh, 'WindowStyle','normal')\nnrows = 4;\nsubplot_handles = layout([1,2,3,4; 5,6,7,8; 9,10,11,12]');\ndrawnow\n\n\n%% Load data for the 3 example participants\nexamples = makeExamples();\nassert(numel(examples)==3, 'expecting 3 examples')\n\n\n%% Iterate over the 3 examples, plotting as we go\nfor n=1:numel(examples)\n\tfprintf('%d of %d\\n',n, numel(examples))\n\tind = nrows*(n-1)+1;\n\tprocess_this_example( examples(n), subplot_handles([ind:ind+(nrows-1)]))\nend\n\n\n% NOTE (x,y) position is in DATA units\n%% Add column titles (example name)\ntop_plots = subplot_handles([1, 5, 9]);\nfor n=1:numel(top_plots)\n\tsubplot(top_plots(n))\n\th = text(365/2, 1.25, examples(n).title);\n\th.HorizontalAlignment = 'center';\n\th.FontWeight = 'bold';\n\th.FontSize = 16;\nend\n\n\n%% Add row titles\nrow_title_labels = {'Kirby (2009)',...\n\t'Koffarnus & Bickel (2014)',...\n\t'Frye et al (2016)',...\n\t'our approach'};\ntop_plots = subplot_handles([1, 2, 3, 4]);\nfor n=1:numel(top_plots)\n\tsubplot(top_plots(n))\n\th = text(-100, 0.5, row_title_labels{n});\n\th.Rotation = 90;\n\th.HorizontalAlignment = 'center';\n\th.FontWeight = 'bold';\n\th.FontSize = 16;\nend\n\n% save data\nsave('figs/saved_data_logk_comparison_of_models')\n\n%% Export\nsetAllSubplotOptions(gcf, {'LineWidth', 1.5, 'FontSize',12})\nset(subplot_handles, 'PlotBoxAspectRatio',[1.5 1 1])\nset(gcf,'Position',[10 10 1200 1300])\nensureFolderExists('figs')\nsavefig('figs/logk_comparison_of_models')\n%export_fig('figs/logk_comparison_of_models', '-pdf')\nexport_fig('figs/logk_comparison_of_models', '-png', '-m6');\n\nend\n\n\n\nfunction process_this_example(example, subplot_handles)\n% Run models\ntrue_logk = example.true_theta;\n% [kirby_Model_to_plot, ktheta, kdata, ~,...\n% \tadaptive_Model_to_plot, adaptive_theta, adaptive_data, ~]...\n% \t= runKirbyAndAdaptive(true_logk);\n\ntrials = 27;\nMAX_DELAY = 365;\n\n%% Kirby example\n[model, theta, data, ~] = runKirby(true_logk, 27);\nsubplot(subplot_handles(1))\nmodel.plotDiscountFunction(theta(:,1),...\n\t'data', data,...\n\t'discounting_function_handle', @model.delayDiscountingFunction, ...\n\t'maxDelay', MAX_DELAY);\ndrawnow\n\n%% KoffarnusAndBickel\n[model, theta, data, ~] = runKoffarnusAndBickel(true_logk, 5);\nsubplot(subplot_handles(2))\nmodel.plotDiscountFunction(theta(:,1),...\n\t'data', data,...\n\t'discounting_function_handle', @model.delayDiscountingFunction, ...\n\t'maxDelay', MAX_DELAY);\ndrawnow\n\n%% Fry Et al\n[model, theta, data, ~] = runFryeEtAl(true_logk, 5*5);\nsubplot(subplot_handles(3))\nmodel.plotDiscountFunction(theta(:,1),...\n\t'data', data,...\n\t'discounting_function_handle', @model.delayDiscountingFunction, ...\n\t'maxDelay', MAX_DELAY);\ndrawnow\n\n%% Our method\n% override default delays with this\n%tempD_B = default_D_B(); D_B = tempD_B(tempD_B<=190);\nD_B = [1:7:MAX_DELAY];\n\n[model, theta, data, ~] = runAdaptiveLogK(true_logk, 30,...\n\t'D_B', D_B);\nsubplot(subplot_handles(4))\nmodel.plotDiscountFunction(theta(:,1),...\n\t'data', data,...\n\t'discounting_function_handle', @model.delayDiscountingFunction, ...\n\t'maxDelay', MAX_DELAY);\ndrawnow\n\nend\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "SCRIPT_logk_param_recovery_role_of_prior.m", "ext": ".m", "path": "darc-experiments-matlab-master/generate_figs_for_paper/SCRIPT_logk_param_recovery_role_of_prior.m", "size": 1364, "source_encoding": "utf_8", "md5": "8356fade05ebefc58e78eb445bb1ed3a", "text": "function SCRIPT_logk_param_recovery_role_of_prior()\n\n%% Setup\naddpath('darc-experiments')\nsave_path = fullfile(pwd,'data');\nlogk_list = [-8:0.05:-1];\n\n\n%% Run parameter sweeps\nresult_adaptive2\t\t= parameter_sweep(logk_list, @param_recovery_adaptive_logk, 2);\nresult_adaptive4\t\t= parameter_sweep(logk_list, @param_recovery_adaptive_logk, 4);\nresult_adaptive8\t\t= parameter_sweep(logk_list, @param_recovery_adaptive_logk, 8);\nresult_adaptive16\t\t= parameter_sweep(logk_list, @param_recovery_adaptive_logk, 16);\n\n\n%% PLOTTING\nfigure_handle = figure(3); clf\nset(figure_handle,'WindowStyle', 'Normal')\n\nsubplot(2,2,1)\nresult_adaptive2.plot_param_recovery(), title('2 trials')\naxis([-8.2 -0.8 -8 0])\n\nsubplot(2,2,2)\nresult_adaptive4.plot_param_recovery(), title('4 trials')\naxis([-8.2 -0.8 -8 0])\n\nsubplot(2,2,3)\nresult_adaptive8.plot_param_recovery(), title('8 trials')\naxis([-8.2 -0.8 -8 0])\n\nsubplot(2,2,4)\nresult_adaptive16.plot_param_recovery(), title('16 trials')\naxis([-8.2 -0.8 -8 0])\n\n\n%% Export\nsetAllSubplotOptions(gcf, {'LineWidth', 2, 'FontSize', 16})\nset(figure_handle, 'Position',[10 0 800 800])\nensureFolderExists('figs')\nexport_fig('figs/logk_param_recovery_role_of_prior.pdf', '-pdf')\nbeep\nend\n\n\nfunction logk_theta_record = param_recovery_adaptive_logk(true_logk, trials)\n[model, theta, data, logk_theta_record] = runAdaptiveLogK(true_logk, trials);\nend\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "SCRIPT_logk_param_recovery.m", "ext": ".m", "path": "darc-experiments-matlab-master/generate_figs_for_paper/SCRIPT_logk_param_recovery.m", "size": 1837, "source_encoding": "utf_8", "md5": "8cd207bb03305b7bd749d5315336357b", "text": "function SCRIPT_logk_param_recovery()\n\n%% Setup\naddpath('darc-experiments')\nsave_path = fullfile(pwd,'data');\nlogk_list = [-8:0.05:-1];\n\n\n%% Run parameter sweeps\nresult_kirby\t\t\t= parameter_sweep(logk_list, @param_recovery_kirby_logk, 27);\nresult_koffarnus\t\t= parameter_sweep(logk_list, @param_recovery_koffarnus, 5);\nresult_fry\t\t\t\t= parameter_sweep(logk_list, @param_recovery_frye, 5*4);\nresult_adaptive20\t\t= parameter_sweep(logk_list, @param_recovery_adaptive_logk, 20);\n\n\n%% PLOTTING\nfigure_handle = figure(3); clf\nset(figure_handle,'WindowStyle', 'Normal')\n\nsubplot(2,2,1)\nresult_kirby.plot_param_recovery(), title('Kirby (2009), 27 trials')\naxis([-8.2 -0.8 -8 0])\n\nsubplot(2,2,2)\nresult_koffarnus.plot_param_recovery(), title('Koffarnus & Bickel (2014), 5 trials')\naxis([-8.2 -0.8 -8 0])\n\nsubplot(2,2,3)\nresult_fry.plot_param_recovery(), title('Frye et al (2016), 20 trials')\naxis([-8.2 -0.8 -8 0])\n\nsubplot(2,2,4)\nresult_adaptive20.plot_param_recovery(), title('Our approach, 20 trials')\naxis([-8.2 -0.8 -8 0])\n\n\n%% Export\nsetAllSubplotOptions(gcf, {'LineWidth', 2, 'FontSize', 16})\nset(figure_handle, 'Position',[10 0 800 800])\nensureFolderExists('figs')\nexport_fig('figs/logk_param_recovery', '-pdf')\nbeep\nend\n\n\nfunction logk_theta_record = param_recovery_kirby_logk(true_logk, trials)\n[model, theta, data, logk_theta_record] = runKirby(true_logk, trials);\nend\n\nfunction logk_theta_record = param_recovery_frye(true_logk, trials)\n[model, theta, data, logk_theta_record] = runFryeEtAl(true_logk, trials);\nend\n\nfunction logk_theta_record = param_recovery_adaptive_logk(true_logk, trials)\n[model, theta, data, logk_theta_record] = runAdaptiveLogK(true_logk, trials);\nend\n\nfunction logk_theta_record = param_recovery_koffarnus(true_logk, trials)\n[model, theta, data, logk_theta_record] = runKoffarnusAndBickel(true_logk, trials);\nend\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "SCRIPT_models_parameter_recovery.m", "ext": ".m", "path": "darc-experiments-matlab-master/generate_figs_for_paper/SCRIPT_models_parameter_recovery.m", "size": 4615, "source_encoding": "utf_8", "md5": "1626fe0b1ac43a7f3a36ffd0fca2874a", "text": "function SCRIPT_models_parameter_recovery()\n\n\n%% Setup\naddpath('darc-experiments')\ntrials = 30; %30\n\nK = 51; % 51\n\n% CALCULATIONS: Do parameter recovery for all models ===========================\n\n%% Hyperbolic discounting of time (with magnitude effect)\ntrue_m_vec = linspace(-1, -0.5, K);\ntrue_c_vec = linspace(-0.5, -2.5, K);\n[m_array, c_array] = do_param_recovery_me(trials, true_m_vec, true_c_vec);\n\n\n%% Hyperbolic discounting of odds against\ntrue_h_vec = logspace(-1,1,K);\nh_array = do_param_recovery_h(trials, true_h_vec);\n\n\n%% Hyperbolic discounting of time AND odds against\ntrue_logk_vec = linspace(-8,-1,K);\ntrue_h_vec = logspace(-1,1,K);\n[TO_logk_array, TO_h_array] = do_param_recovery_time_and_odds(trials, true_logk_vec, true_h_vec);\n\nsave 'other_models_parameter_recovery.mat'\nbeep\n\n\n%% PLOTTING\nfigure_handle = figure(3); clf\nset(figure_handle, 'WindowStyle', 'Normal')\n\n[figure_handle, h_row_labels, h_col_labels, h_main] = ...\nmake_subplot_grid({ {'time discounting', '(with magnitude effect)'},...\n\t{'probability', 'discounting'},...\n\t{'time and probabilty', 'discounting'}},...\n\t{'',''});\n\nsubplot(h_main(1, 1)), m_array.plot_param_recovery(), title('m'), setTickIntervals(0.25, 0.25)\nsubplot(h_main(1, 2)), c_array.plot_param_recovery(), title('c'), setTickIntervals(0.5, 0.5)\n\nsubplot(h_main(2, 1)), h_array.plot_param_recovery(), title('h'), %setTickIntervals(2,2)\nset(gca,'XScale','log', 'YScale','log')\naxis([10^-1 10^1 10^-1 10^1])\nset(gca,'XTickLabel',{0.1, 1, 10},...\n 'YTickLabel',{0.1, 1, 10})\ndelete(h_main(2, 2))\n\nsubplot(h_main(3, 1)), TO_logk_array.plot_param_recovery(), title('log(k)'), setTickIntervals(2,2)\naxis([min(true_logk_vec) max(true_logk_vec) min(true_logk_vec) max(true_logk_vec)])\nsubplot(h_main(3, 2)), TO_h_array.plot_param_recovery(), title('h'), %setTickIntervals(2,2)\nset(gca,'XScale','log', 'YScale','log')\naxis([10^-1 10^1 10^-1 10^1])\nset(gca,'XTickLabel',{0.1, 1, 10},...\n 'YTickLabel',{0.1, 1, 10})\n\n%% Export\nfigure_handle.Units = 'pixels';\nset(figure_handle,'Position',[10 10 600 1000])\nensureFolderExists('figs')\nsavefig('figs/multiple_Model_param_recovery')\nexport_fig('figs/multiple_Model_param_recovery', '-pdf')\nbeep\nend\n\n\n\nfunction [m_array, c_array] = do_param_recovery_me(trials, true_m_vec, true_c_vec)\ndisplay('Hyperbolic discounting of time (with magnitude effect)')\n% Define parameters\n\n% Alpha and Epsilon are treated as fixed parameters\n[alpha, epsilon] = common_parameters();\n\nm_array = [];\nc_array = [];\nparfor n=1:numel(true_m_vec)\n\tfprintf('%d of %d\\n',n, numel(true_m_vec))\n\ttrue_m = true_m_vec(n);\n\ttrue_c = true_c_vec(n);\n\n\tmodel = Model_hyperbolic1ME_time(...\n\t\t'epsilon', epsilon);\n\n\texpt = Experiment(model,...\n\t\t'agent', 'simulated_agent',...\n\t\t'trials', trials,...\n\t\t'true_theta', struct('m', true_m, 'c', true_c, 'alpha', alpha),...\n\t\t'plotting','none');\n\n\texpt = expt.runTrials();\n\n\tm\t= expt.get_specific_theta_record_parameter('m');\n\tm_array = [m_array m];\n\n\tc\t= expt.get_specific_theta_record_parameter('c');\n\tc_array = [c_array c];\n\nend\nend\n\n\nfunction h_array = do_param_recovery_h(trials, true_h_vec)\ndisplay('Hyperbolic discounting of log odds')\n\n% Alpha and Epsilon are treated as fixed parameters\n[alpha, epsilon] = common_parameters();\n\nh_array = [];\nparfor n=1:numel(true_h_vec)\n\tfprintf('%d of %d\\n',n, numel(true_h_vec))\n\ttrue_h = true_h_vec(n);\n\n\tmodel = Model_hyperbolic1_prob(...\n\t\t'epsilon', epsilon,... % fixed value\n\t\t'R_B', 100);\n\n\texpt = Experiment(...\n\t\tmodel,...\n\t\t'agent', 'simulated_agent',...\n\t\t'trials', trials,...\n\t\t'true_theta', struct('h', true_h, 'alpha', alpha),...\n\t\t'plotting','none');\n\n\texpt = expt.runTrials();\n\n\th\t= expt.get_specific_theta_record_parameter('h');\n\th_array = [h_array h];\nend\n\n\nend\n\n\n\nfunction [logk_array, h_array] = do_param_recovery_time_and_odds(trials, true_logk_vec, true_h_vec);\ndisplay('Hyperbolic discounting of time AND log odds against')\n\n% Alpha and Epsilon are treated as fixed parameters\n[alpha, epsilon] = common_parameters();\n\nlogk_array = [];\nh_array = [];\nparfor n=1:numel(true_logk_vec)\n\tfprintf('%d of %d\\n',n, numel(true_logk_vec))\n\ttrue_logk = true_logk_vec(n);\n\ttrue_h = true_h_vec(n);\n\n\tmodel = Model_hyperbolic1_time_and_prob(...\n\t\t'epsilon', epsilon);\n\n\texpt = Experiment(...\n\t\tmodel,...\n\t\t'agent', 'simulated_agent',...\n\t\t'trials', trials,...\n\t\t'true_theta', struct('logk', true_logk, 'h', true_h, 'alpha', alpha),...\n\t\t'plotting','none');\n\n\texpt = expt.runTrials();\n\n\tlogk\t= expt.get_specific_theta_record_parameter('logk');\n\tlogk_array = [logk_array logk];\n\n\th\t= expt.get_specific_theta_record_parameter('h');\n\th_array = [h_array h];\n\nend\nend\n"} +{"plateform": "github", "repo_name": "drbenvincent/darc-experiments-matlab-master", "name": "fig_darc_schematic.m", "ext": ".m", "path": "darc-experiments-matlab-master/generate_figs_for_paper/fig_darc_schematic.m", "size": 3127, "source_encoding": "utf_8", "md5": "419ae13f8cc195dcb598b39ba7512225", "text": "% fig_darc_schematic\n% Create the basic structure of the figure to demonstrate the approaches:\n% - Expected Utility Theory\n% - Prospect Theory\n% - Discounting\n\nf = figure(1);\nclf\nh = layout([1, 2, 3; 4 5 6; 7 8 9]);\n\n\nreward = linspace(-10,10,100);\nprobability = linspace(0,1,1000);\ndelays = linspace(0,365, 3650);\nodds = (1-probability)./probability;\n\n\n%% EUT\n\n% linear utility\nsubplot(h(1))\n\np = plot(reward, reward, 'k-','Linewidth',2);\n\nh(1).XAxisLocation = 'origin';\nh(1).YAxisLocation = 'origin';\nxlabel('$R$', 'interpreter', 'latex')\nylabel('$u(R)$', 'interpreter', 'latex')\naxis equal\naxis square\nbox off\n\n\n% linear probability\nsubplot(h(2))\n\np = plot(probability, probability, 'k-','Linewidth',2);\nxlabel('$P$', 'interpreter', 'latex')\nylabel('$\\pi (P)$', 'interpreter', 'latex')\naxis equal\nbox off\naxis([0 1 0 1])\n\n\n% exponential discounting\nsubplot(h(3))\nplot(delays, exp(-0.005.*delays), 'k-','Linewidth',2);\nxlabel('$D$', 'interpreter', 'latex')\nylabel('$d(D)$', 'interpreter', 'latex')\nxlim([0, 365])\nbox off\naxis square\n\n\n\n\n\n%% prospect theory\n\n% value function\nsubplot(h(4))\n\nalpha = 0.6;\nbeta = 0.6;\nloss = 1.5;\np = plot(reward, pt_util_function(reward, alpha, beta, loss),...\n 'k-','Linewidth',2);\nxlabel('$R$', 'interpreter', 'latex')\nylabel('$u(R)$', 'interpreter', 'latex')\naxis equal\naxis square\nbox off\nh(4).XAxisLocation = 'origin';\nh(4).YAxisLocation = 'origin';\n\n% prospect theory weighting function\n% linear probability\nsubplot(h(5))\n\ndelta = 0.6;\ngamma = 0.4;\nwf = @(p) (delta.*p.^gamma) ./ ((delta.*p.^gamma) + (1-p).^gamma);\n\np = plot(probability, wf(probability), 'k-','Linewidth',2);\nhold on\nplot([0 1],[0 1], 'k-')\nxlabel('$P$', 'interpreter', 'latex')\nylabel('$\\pi (P)$', 'interpreter', 'latex')\naxis equal\naxis square\nbox off\naxis([0 1 0 1])\n\n\n\n% no time discounting\nsubplot(h(6))\nplot(delays, ones(size(delays)), 'k-','Linewidth',2);\nxlabel('$D$', 'interpreter', 'latex')\nylabel('$d(D)$', 'interpreter', 'latex')\nxlim([0, 365])\nylim([0 1.1])\nbox off\naxis square\n\n\n%% Discounting approaches\n\n% linear utility function\nsubplot(h(7))\n\np = plot(reward, reward, 'k-','Linewidth',2);\nxlabel('$R$', 'interpreter', 'latex')\nylabel('$u(R)$', 'interpreter', 'latex')\naxis equal\naxis square\nbox off\nh(6).XAxisLocation = 'origin';\nh(6).YAxisLocation = 'origin';\n\n% hyperbolic discounting of odds\nsubplot(h(8))\nplot(odds, 1./(1+1.*odds), 'k-','Linewidth',2);\nxlabel('$ odds = \\frac{1-P}{P}$', 'interpreter', 'latex')\nylabel('$ \\pi(\\frac{1-P}{P}) $', 'interpreter', 'latex')\nxlim([0, 10])\naxis square\nbox off\naddTextToFigure('BL',' risk averse', 12)\naddTextToFigure('TR','risk seeking', 12)\n\n% hyperbolic discounting of delay\nsubplot(h(9))\nplot(delays, 1./(1+exp(-3).*delays), 'k-','Linewidth',2);\nxlabel('$D$', 'interpreter', 'latex')\nylabel('$d(D)$', 'interpreter', 'latex')\nxlim([0, 365])\naxis square\nbox off\n\n\n%% Export\nset(gcf,'Position',[10 10 900 700])\nsavefig('figs/darc_schematic_raw')\nexport_fig('figs/darc_schematic_raw', '-pdf')\n\n\nfunction u = pt_util_function(reward, alpha, beta, loss)\nu(reward>=0) = reward(reward>=0).^alpha;\nu(reward<0) = -loss.*((-reward(reward<0)).^beta);\nend\n"} +{"plateform": "github", "repo_name": "ajit2704/underwater-image-enhancement-master", "name": "vanherk.m", "ext": ".m", "path": "underwater-image-enhancement-master/mat/vanherk.m", "size": 4841, "source_encoding": "utf_8", "md5": "5b0cf60c12e2432af9a978d4bad7ff3b", "text": "function Y = vanherk(X,N,TYPE,varargin)\r\n% VANHERK Fast max/min 1D filter\r\n%\r\n% Y = VANHERK(X,N,TYPE) performs the 1D max/min filtering of the row\r\n% vector X using a N-length filter.\r\n% The filtering type is defined by TYPE = 'max' or 'min'. This function\r\n% uses the van Herk algorithm for min/max filters that demands only 3\r\n% min/max calculations per element, independently of the filter size.\r\n%\r\n% If X is a 2D matrix, each row will be filtered separately.\r\n% \r\n% Y = VANHERK(...,'col') performs the filtering on the columns of X.\r\n% \r\n% Y = VANHERK(...,'shape') returns the subset of the filtering specified\r\n% by 'shape' :\r\n% 'full' - Returns the full filtering result,\r\n% 'same' - (default) Returns the central filter area that is the\r\n% same size as X,\r\n% 'valid' - Returns only the area where no filter elements are outside\r\n% the image.\r\n%\r\n% X can be uint8 or double. If X is uint8 the processing is quite faster, so\r\n% dont't use X as double, unless it is really necessary.\r\n%\r\n\r\n% Initialization\r\n[direc, shape] = parse_inputs(varargin{:});\r\nif strcmp(direc,'col')\r\n X = X';\r\nend\r\nif strcmp(TYPE,'max')\r\n maxfilt = 1;\r\nelseif strcmp(TYPE,'min')\r\n maxfilt = 0;\r\nelse\r\n error([ 'TYPE must be ' char(39) 'max' char(39) ' or ' char(39) 'min' char(39) '.'])\r\nend\r\n\r\n% Correcting X size\r\nfixsize = 0;\r\naddel = 0;\r\nif mod(size(X,2),N) ~= 0\r\n fixsize = 1;\r\n addel = N-mod(size(X,2),N);\r\n if maxfilt\r\n f = [ X zeros(size(X,1), addel) ];\r\n else\r\n f = [X repmat(X(:,end),1,addel)];\r\n end\r\nelse\r\n f = X;\r\nend\r\nlf = size(f,2);\r\nlx = size(X,2);\r\nclear X\r\n\r\n% Declaring aux. mat.\r\ng = f;\r\nh = g;\r\n\r\n% Filling g & h (aux. mat.)\r\nig = 1:N:size(f,2);\r\nih = ig + N - 1;\r\n\r\ng(:,ig) = f(:,ig);\r\nh(:,ih) = f(:,ih);\r\n\r\nif maxfilt\r\n for i = 2 : N\r\n igold = ig;\r\n ihold = ih;\r\n \r\n ig = ig + 1;\r\n ih = ih - 1;\r\n \r\n g(:,ig) = max(f(:,ig),g(:,igold));\r\n h(:,ih) = max(f(:,ih),h(:,ihold));\r\n end\r\nelse\r\n for i = 2 : N\r\n igold = ig;\r\n ihold = ih;\r\n \r\n ig = ig + 1;\r\n ih = ih - 1;\r\n \r\n g(:,ig) = min(f(:,ig),g(:,igold));\r\n h(:,ih) = min(f(:,ih),h(:,ihold));\r\n end\r\nend\r\nclear f\r\n\r\n% Comparing g & h\r\nif strcmp(shape,'full')\r\n ig = [ N : 1 : lf ];\r\n ih = [ 1 : 1 : lf-N+1 ];\r\n if fixsize\r\n if maxfilt\r\n Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ];\r\n else\r\n Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ];\r\n end\r\n else\r\n if maxfilt\r\n Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end) ];\r\n else\r\n Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end) ];\r\n end\r\n end\r\n \r\nelseif strcmp(shape,'same')\r\n if fixsize\r\n if addel > (N-1)/2\r\n disp('hoi')\r\n ig = [ N : 1 : lf - addel + floor((N-1)/2) ];\r\n ih = [ 1 : 1 : lf-N+1 - addel + floor((N-1)/2)];\r\n if maxfilt\r\n Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) ];\r\n else\r\n Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) ];\r\n end\r\n else \r\n ig = [ N : 1 : lf ];\r\n ih = [ 1 : 1 : lf-N+1 ];\r\n if maxfilt\r\n Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ];\r\n else\r\n Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ];\r\n end\r\n end \r\n else % not fixsize (addel=0, lf=lx) \r\n ig = [ N : 1 : lx ];\r\n ih = [ 1 : 1 : lx-N+1 ];\r\n if maxfilt\r\n Y = [ g(:,N-ceil((N-1)/2):N-1) max( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ];\r\n else\r\n Y = [ g(:,N-ceil((N-1)/2):N-1) min( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ];\r\n end\r\n end \r\n \r\nelseif strcmp(shape,'valid')\r\n ig = [ N : 1 : lx];\r\n ih = [ 1 : 1: lx-N+1];\r\n if maxfilt\r\n Y = [ max( g(:,ig), h(:,ih) ) ];\r\n else\r\n Y = [ min( g(:,ig), h(:,ih) ) ];\r\n end\r\nend\r\n\r\nif strcmp(direc,'col')\r\n Y = Y';\r\nend\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction [direc, shape] = parse_inputs(varargin)\r\ndirec = 'lin';\r\nshape = 'same';\r\nflag = [0 0]; % [dir shape]\r\n\r\nfor i = 1 : nargin\r\n t = varargin{i};\r\n if strcmp(t,'col') & flag(1) == 0\r\n direc = 'col';\r\n flag(1) = 1;\r\n elseif strcmp(t,'full') & flag(2) == 0\r\n shape = 'full';\r\n flag(2) = 1;\r\n elseif strcmp(t,'same') & flag(2) == 0\r\n shape = 'same';\r\n flag(2) = 1;\r\n elseif strcmp(t,'valid') & flag(2) == 0\r\n shape = 'valid';\r\n flag(2) = 1;\r\n else\r\n error(['Too many / Unkown parameter : ' t ])\r\n end\r\nend"} +{"plateform": "github", "repo_name": "ajit2704/underwater-image-enhancement-master", "name": "maxfilt2.m", "ext": ".m", "path": "underwater-image-enhancement-master/mat/maxfilt2.m", "size": 1849, "source_encoding": "utf_8", "md5": "45cc67fb2afee0dc77cfc7798629574f", "text": "function Y = maxfilt2(X,varargin)\r\n% MAXFILT2 Two-dimensional max filter\r\n%\r\n% Y = MAXFILT2(X,[M N]) performs two-dimensional maximum\r\n% filtering on the image X using an M-by-N window. The result\r\n% Y contains the maximun value in the M-by-N neighborhood around\r\n% each pixel in the original image. \r\n% This function uses the van Herk algorithm for max filters.\r\n%\r\n% Y = MAXFILT2(X,M) is the same as Y = MAXFILT2(X,[M M])\r\n%\r\n% Y = MAXFILT2(X) uses a 3-by-3 neighborhood.\r\n%\r\n% Y = MAXFILT2(..., 'shape') returns a subsection of the 2D\r\n% filtering specified by 'shape' :\r\n% 'full' - Returns the full filtering result,\r\n% 'same' - (default) Returns the central filter area that is the\r\n% same size as X,\r\n% 'valid' - Returns only the area where no filter elements are outside\r\n% the image.\r\n%\r\n% See also : MINFILT2, VANHERK\r\n%\r\n\r\n% Initialization\r\n[S, shape] = parse_inputs(varargin{:});\r\n\r\n% filtering\r\nY = vanherk(X,S(1),'max',shape);\r\nY = vanherk(Y,S(2),'max','col',shape);\r\n\r\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\nfunction [S, shape] = parse_inputs(varargin)\r\nshape = 'same';\r\nflag = [0 0]; % size shape\r\n\r\nfor i = 1 : nargin\r\n t = varargin{i};\r\n if strcmp(t,'full') & flag(2) == 0\r\n shape = 'full';\r\n flag(2) = 1;\r\n elseif strcmp(t,'same') & flag(2) == 0\r\n shape = 'same';\r\n flag(2) = 1;\r\n elseif strcmp(t,'valid') & flag(2) == 0\r\n shape = 'valid';\r\n flag(2) = 1;\r\n elseif flag(1) == 0\r\n S = t;\r\n flag(1) = 1;\r\n else\r\n error(['Too many / Unkown parameter : ' t ])\r\n end\r\nend\r\n\r\nif flag(1) == 0\r\n S = [3 3];\r\nend\r\nif length(S) == 1;\r\n S(2) = S(1);\r\nend\r\nif length(S) ~= 2\r\n error('Wrong window size parameter.')\r\nend\r\n\r\n"} +{"plateform": "github", "repo_name": "ajit2704/underwater-image-enhancement-master", "name": "bilateralFilter.m", "ext": ".m", "path": "underwater-image-enhancement-master/mat/bilateralFilter.m", "size": 6703, "source_encoding": "utf_8", "md5": "a76d6aab0840ad8b7e6e749526f36660", "text": "%\n% output = bilateralFilter( data, edge, ...\n% edgeMin, edgeMax, ...\n% sigmaSpatial, sigmaRange, ...\n% samplingSpatial, samplingRange )\n%\n% Bilateral and Cross-Bilateral Filter using the Bilateral Grid.\n%\n% Bilaterally filters the image 'data' using the edges in the image 'edge'.\n% If 'data' == 'edge', then it the standard bilateral filter.\n% Otherwise, it is the 'cross' or 'joint' bilateral filter.\n% For convenience, you can also pass in [] for 'edge' for the normal\n% bilateral filter.\n%\n% Note that for the cross bilateral filter, data does not need to be\n% defined everywhere. Undefined values can be set to 'NaN'. However, edge\n% *does* need to be defined everywhere.\n%\n% data and edge should be of the greyscale, double-precision floating point\n% matrices of the same size (i.e. they should be [ height x width ])\n%\n% data is the only required argument\n%\n% edgeMin and edgeMax specifies the min and max values of 'edge' (or 'data'\n% for the normal bilateral filter) and is useful when the input is in a\n% range that's not between 0 and 1. For instance, if you are filtering the\n% L channel of an image that ranges between 0 and 100, set edgeMin to 0 and\n% edgeMax to 100.\n% \n% edgeMin defaults to min( edge( : ) ) and edgeMax defaults to max( edge(:)).\n% This is probably *not* what you want, since the input may not span the\n% entire range.\n%\n% sigmaSpatial and sigmaRange specifies the standard deviation of the space\n% and range gaussians, respectively.\n% sigmaSpatial defaults to min( width, height ) / 16\n% sigmaRange defaults to ( edgeMax - edgeMin ) / 10.\n%\n% samplingSpatial and samplingRange specifies the amount of downsampling\n% used for the approximation. Higher values use less memory but are also\n% less accurate. The default and recommended values are:\n% \n% samplingSpatial = sigmaSpatial\n% samplingRange = sigmaRange\n%\n\nfunction output = bilateralFilter( data, edge, edgeMin, edgeMax,...\n sigmaSpatial, sigmaRange, samplingSpatial, samplingRange )\n\nif( ndims( data ) > 2 ),\n error( 'data must be a greyscale image with size [ height, width ]' );\nend\n\nif( ~isa( data, 'double' ) ),\n error( 'data must be of class \"double\"' );\nend\n\nif ~exist( 'edge', 'var' ),\n edge = data;\nelseif isempty( edge ),\n edge = data;\nend\n\nif( ndims( edge ) > 2 ),\n error( 'edge must be a greyscale image with size [ height, width ]' );\nend\n\nif( ~isa( edge, 'double' ) ),\n error( 'edge must be of class \"double\"' );\nend\n\ninputHeight = size( data, 1 );\ninputWidth = size( data, 2 );\n\nif ~exist( 'edgeMin', 'var' ),\n edgeMin = min( edge( : ) );\n %warning( 'edgeMin not set! Defaulting to: %f\\n', edgeMin );\nend\n\nif ~exist( 'edgeMax', 'var' ),\n edgeMax = max( edge( : ) );\n %warning( 'edgeMax not set! Defaulting to: %f\\n', edgeMax );\nend\n\nedgeDelta = edgeMax - edgeMin;\n\nif ~exist( 'sigmaSpatial', 'var' ),\n sigmaSpatial = min( inputWidth, inputHeight ) / 16;\n %fprintf( 'Using default sigmaSpatial of: %f\\n', sigmaSpatial );\nend\n\nif ~exist( 'sigmaRange', 'var' ),\n sigmaRange = 0.1 * edgeDelta;\n %fprintf( 'Using default sigmaRange of: %f\\n', sigmaRange );\nend\n\nif ~exist( 'samplingSpatial', 'var' ),\n samplingSpatial = sigmaSpatial;\nend\n\nif ~exist( 'samplingRange', 'var' ),\n samplingRange = sigmaRange;\nend\n\nif size( data ) ~= size( edge ),\n error( 'data and edge must be of the same size' );\nend\n\n% parameters\nderivedSigmaSpatial = sigmaSpatial / samplingSpatial;\nderivedSigmaRange = sigmaRange / samplingRange;\n\npaddingXY = floor( 2 * derivedSigmaSpatial ) + 1;\npaddingZ = floor( 2 * derivedSigmaRange ) + 1;\n\n% allocate 3D grid\ndownsampledWidth = floor( ( inputWidth - 1 ) / samplingSpatial )...\n + 1 + 2 * paddingXY;\ndownsampledHeight = floor( ( inputHeight - 1 ) / samplingSpatial )...\n + 1 + 2 * paddingXY;\ndownsampledDepth = floor( edgeDelta / samplingRange ) + 1 + 2 * paddingZ;\n\ngridData = zeros( downsampledHeight, downsampledWidth, downsampledDepth );\ngridWeights = zeros( downsampledHeight, downsampledWidth, downsampledDepth );\n\n% compute downsampled indices\n[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 );\n\n% ii =\n% 0 0 0 0 0\n% 1 1 1 1 1\n% 2 2 2 2 2\n\n% jj =\n% 0 1 2 3 4\n% 0 1 2 3 4\n% 0 1 2 3 4\n\n% so when iterating over ii( k ), jj( k )\n% get: ( 0, 0 ), ( 1, 0 ), ( 2, 0 ), ... (down columns first)\n\ndi = round( ii / samplingSpatial ) + paddingXY + 1;\ndj = round( jj / samplingSpatial ) + paddingXY + 1;\ndz = round( ( edge - edgeMin ) / samplingRange ) + paddingZ + 1;\n\n% perform scatter (there's probably a faster way than this)\n% normally would do downsampledWeights( di, dj, dk ) = 1, but we have to\n% perform a summation to do box downsampling\nfor k = 1 : numel( dz ),\n \n dataZ = data( k ); % traverses the image column wise, same as di( k )\n if ~isnan( dataZ ),\n \n dik = di( k );\n djk = dj( k );\n dzk = dz( k );\n\n gridData( dik, djk, dzk ) = gridData( dik, djk, dzk ) + dataZ;\n gridWeights( dik, djk, dzk ) = gridWeights( dik, djk, dzk ) + 1;\n \n end\nend\n\n% make gaussian kernel\nkernelWidth = 2 * derivedSigmaSpatial + 1;\nkernelHeight = kernelWidth;\nkernelDepth = 2 * derivedSigmaRange + 1;\n\nhalfKernelWidth = floor( kernelWidth / 2 );\nhalfKernelHeight = floor( kernelHeight / 2 );\nhalfKernelDepth = floor( kernelDepth / 2 );\n\n[gridX, gridY, gridZ] = meshgrid( 0 : kernelWidth - 1,...\n 0 : kernelHeight - 1, 0 : kernelDepth - 1 );\ngridX = gridX - halfKernelWidth;\ngridY = gridY - halfKernelHeight;\ngridZ = gridZ - halfKernelDepth;\ngridRSquared = ( gridX .* gridX + gridY .* gridY ) /...\n ( derivedSigmaSpatial * derivedSigmaSpatial ) +...\n ( gridZ .* gridZ ) / ( derivedSigmaRange * derivedSigmaRange );\nkernel = exp( -0.5 * gridRSquared );\n\n% convolve\nblurredGridData = convn( gridData, kernel, 'same' );\nblurredGridWeights = convn( gridWeights, kernel, 'same' );\n\n% divide\n% avoid divide by 0, won't read there anyway\nblurredGridWeights( blurredGridWeights == 0 ) = -2; \nnormalizedBlurredGrid = blurredGridData ./ blurredGridWeights;\n% put 0s where it's undefined\nnormalizedBlurredGrid( blurredGridWeights < -1 ) = 0; \n\n% for debugging\n% blurredGridWeights( blurredGridWeights < -1 ) = 0; % put zeros back\n\n% upsample\n% meshgrid does x, then y, so output arguments need to be reversed\n[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 ); \n% no rounding\ndi = ( ii / samplingSpatial ) + paddingXY + 1;\ndj = ( jj / samplingSpatial ) + paddingXY + 1;\ndz = ( edge - edgeMin ) / samplingRange + paddingZ + 1;\n\n% interpn takes rows, then cols, etc\n% i.e. size(v,1), then size(v,2), ...\noutput = interpn( normalizedBlurredGrid, di, dj, dz );"} +{"plateform": "github", "repo_name": "ajit2704/underwater-image-enhancement-master", "name": "autolevel.m", "ext": ".m", "path": "underwater-image-enhancement-master/mat/autolevel.m", "size": 2027, "source_encoding": "utf_8", "md5": "42c51c0ef7df19d0766b3376c3b1500b", "text": "function imDst = autolevel(varargin)\n[I,lowCut,highCut] =parse_inputs(varargin{:});\n[hei,wid,~] = size(I);\n\nPixelAmount = wid * hei;\nif size(I,3)==3\n\n [HistRed,~] = imhist(I(:,:,1));\n [HistGreen,~] = imhist(I(:,:,2));\n [HistBlue,~] = imhist(I(:,:,3));\n\n CumRed = cumsum(HistRed);\n CumGreen = cumsum(HistGreen);\n CumBlue = cumsum(HistBlue);\n\n minR =find(CumRed>=PixelAmount*lowCut,1,'first');\n minG = find(CumGreen>=PixelAmount*lowCut,1,'first');\n minB =find(CumBlue>=PixelAmount*lowCut,1,'first');\n\n maxR =find(CumRed>=PixelAmount*(1-highCut),1,'first');\n maxG =find(CumGreen>=PixelAmount*(1-highCut),1,'first');\n maxB = find(CumBlue>=PixelAmount*(1-highCut),1,'first');\n\n RedMap = linearmap(minR,maxR);\n GreenMap = linearmap(minG,maxG);\n BlueMap = linearmap(minB,maxB);\n\n imDst = zeros(hei,wid,3,'uint8');\n imDst(:,:,1) = RedMap (I(:,:,1)+1);\n imDst(:,:,2) = GreenMap(I(:,:,2)+1);\n imDst(:,:,3) = BlueMap(I(:,:,3)+1);\n\nelse\n HistGray = imhist(I(:,:));\n CumGray = cumsum(HistRed);\n minGray =find(CumGray>=PixelAmount*lowCut,1,'first');\n maxGray =find(CumGray>=PixelAmount*(1-highCut),1,'first');\n GrayMap = linearmap(minGray,maxGray);\n\n imDst = zeros(hei,wid,'uint8');\n imDst(:,:) = GrayMap (I(:,:)+1); \nend\n\n%--------------------------------------------------------------------\nfunction map = linearmap(low,high)\nmap = [0:1:255];\nfor i=0:255\n if(ihigh)\n map(i+1) = 255;\n else\n map(i+1) =uint8((i-low)/(high-low)*255);\n end\nend\n\n\n%-------------------------------------------------------------------\nfunction [I,lowCut,highCut] = parse_inputs(varargin)\nnarginchk(1,3)\nI = varargin{1};\nvalidateattributes(I,{'double','logical','uint8','uint16','int16','single'},{},...\n mfilename,'Image',1);\n\nif nargin == 1\n lowCut = 0.005;\n highCut = 0.005;\nelseif nargin == 3\n lowCut = varargin{2};\n highCut = varargin{3};\nelse\n error(message('images:im2double:invalidIndexedImage','single, or logical.'));\nend"} +{"plateform": "github", "repo_name": "ajit2704/underwater-image-enhancement-master", "name": "saliency_detection.m", "ext": ".m", "path": "underwater-image-enhancement-master/mat/saliency_detection.m", "size": 2484, "source_encoding": "utf_8", "md5": "d13d25afa6342e87bb05929451469b52", "text": "%---------------------------------------------------------\n% Copyright (c) 2009 Radhakrishna Achanta [EPFL]\n% Contact: firstname.lastname@epfl.ch\n%---------------------------------------------------------\n% Citation:\n% @InProceedings{LCAV-CONF-2009-012,\n% author = {Achanta, Radhakrishna and Hemami, Sheila and Estrada,\n% Francisco and S?strunk, Sabine},\n% booktitle = {{IEEE} {I}nternational {C}onference on {C}omputer\n% {V}ision and {P}attern {R}ecognition},\n% year = 2009\n% }\n%---------------------------------------------------------\n% Please note that the saliency maps generated using this\n% code may be slightly different from those of the paper.\n% This seems to be because the RGB to Lab conversion is\n% different from the one used for the results in the C++ code.\n% The C++ code is available on the same page as this matlab\n% code (http://ivrg.epfl.ch/supplementary_material/RK_CVPR09/index.html)\n% One should preferably use the C++ as reference and use\n% this matlab implementation mostly as proof of concept\n% demo code.\n%---------------------------------------------------------\nfunction sm = saliency_detection(img)\n%\n%---------------------------------------------------------\n% Read image and blur it with a 3x3 or 5x5 Gaussian filter\n%---------------------------------------------------------\n%img = imread('input_image.jpg');%Provide input image path\ngfrgb = imfilter(img, fspecial('gaussian', 3, 3), 'symmetric', 'conv');\n%---------------------------------------------------------\n% Perform sRGB to CIE Lab color space conversion (using D65)\n%---------------------------------------------------------\n%cform = makecform('srgb2lab', 'whitepoint', whitepoint('d65'));\ncform = makecform('srgb2lab');\nlab = applycform(gfrgb,cform);\n%---------------------------------------------------------\n% Compute Lab average values (note that in the paper this\n% average is found from the unblurred original image, but\n% the results are quite similar)\n%---------------------------------------------------------\nl = double(lab(:,:,1)); lm = mean(mean(l));\na = double(lab(:,:,2)); am = mean(mean(a));\nb = double(lab(:,:,3)); bm = mean(mean(b));\n%---------------------------------------------------------\n% Finally compute the saliency map and display it.\n%---------------------------------------------------------\nsm = (l-lm).^2 + (a-am).^2 + (b-bm).^2;\n%imshow(sm,[]);\n%---------------------------------------------------------"} +{"plateform": "github", "repo_name": "ajit2704/underwater-image-enhancement-master", "name": "white_balance.m", "ext": ".m", "path": "underwater-image-enhancement-master/mat/white_balance.m", "size": 2152, "source_encoding": "utf_8", "md5": "86ed46f043a7b9801c456cde675ebdda", "text": "%my own white-balance function, created by Qu Jingwei\r\nfunction new_image = white_balance3(src_image)\r\n[height,width,dim] = size(src_image);\r\ntemp = zeros(height,width);\r\n%transform the RGB color space to YCbCr color space \r\nycbcr_image = rgb2ycbcr(src_image);\r\nY = ycbcr_image(:,:,1);\r\nCb = ycbcr_image(:,:,2);\r\nCr = ycbcr_image(:,:,3);\r\n%calculate the average value of Cb,Cr\r\nCb_ave = mean(mean(Cb));\r\nCr_ave = mean(mean(Cr));\r\n%calculate the mean square error of Cb, Cr\r\nDb = sum(sum(abs(Cb-Cb_ave))) / (height*width);\r\nDr = sum(sum(abs(Cr-Cr_ave))) / (height*width);\r\n%find the candidate reference white point\r\n%if meeting the following requriments\r\n%then the point is a candidate reference white point\r\ntemp1 = abs(Cb - (Cb_ave + Db * sign(Cb_ave)));\r\ntemp2 = abs(Cb - (1.5 * Cr_ave + Dr * sign(Cr_ave)));\r\nidx_1 = find(temp1<1.5*Db);\r\nidx_2 = find(temp2<1.5*Dr);\r\nidx = intersect(idx_1,idx_2);\r\npoint = Y(idx);\r\ntemp(idx) = Y(idx);\r\ncount = length(point);\r\ncount = count - 1;\r\n%sort the candidate reference white point set with descend value of Y\r\ntemp_point = sort(point,'descend');\r\n%get the 10% points of the candidate reference white point set, which is\r\n%closer to the white region, as the reference white point set\r\nn = round(count/10);\r\nwhite_point(1:n) = temp_point(1:n);\r\ntemp_min = min(white_point);\r\nidx0 = find(temp=temp_min);\r\ntemp(idx1) = 1;\r\n%get the reference white points' R,G,B\r\nwhite_R = double(src_image(:,:,1)).*temp;\r\nwhite_G = double(src_image(:,:,2)).*temp;\r\nwhite_B = double(src_image(:,:,3)).*temp;\r\n%get the averange value of the reference white points' R,G,B\r\nwhite_R_ave = mean(mean(white_R));\r\nwhite_G_ave = mean(mean(white_G));\r\nwhite_B_ave = mean(mean(white_B));\r\n%the maximum Y value of the source image\r\nYmax = double(max(max(Y))) / 15;\r\n%calculate the white-balance gain\r\nR_gain = Ymax / white_R_ave;\r\nG_gain = Ymax / white_G_ave;\r\nB_gain = Ymax / white_B_ave;\r\n%white-balance correction\r\nnew_image(:,:,1) = R_gain * src_image(:,:,1);\r\nnew_image(:,:,2) = G_gain * src_image(:,:,2);\r\nnew_image(:,:,3) = B_gain * src_image(:,:,3);\r\nnew_image = uint8(new_image);\r\nend"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "svrlsmgui.m", "ext": ".m", "path": "svrlsmgui-master/svrlsmgui.m", "size": 62702, "source_encoding": "utf_8", "md5": "32070ab04e38ec6e5a30f181f8bf30c6", "text": "function varargout = svrlsmgui(varargin)\n% SVRLSMGUI MATLAB code for svrlsmgui.fig\n% SVRLSMGUI, by itself, creates a new SVRLSMGUI or raises the existing\n% singleton*.\n%\n% H = SVRLSMGUI returns the handle to a new SVRLSMGUI or the handle to\n% the existing singleton*.\n%\n% SVRLSMGUI('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SVRLSMGUI.M with the given input arguments.\n%\n% SVRLSMGUI('Property','Value',...) creates a new SVRLSMGUI or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before svrlsmgui_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to svrlsmgui_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help svrlsmgui\n\n% Last Modified by GUIDE v2.5 04-Nov-2019 12:48:03\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename,'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @svrlsmgui_OpeningFcn, 'gui_OutputFcn', @svrlsmgui_OutputFcn, ...\n 'gui_LayoutFcn', [] , 'gui_Callback', []);\n\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1}); \nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:}); \nend\n\n% End initialization code - DO NOT EDIT\n\n% --- Executes just before svrlsmgui is made visible.\nfunction svrlsmgui_OpeningFcn(hObject, eventdata, handles, varargin)\n handles.output = hObject; % Choose default command line output for svrlsmgui\n \n % Do we need to add the functions subdirectory to the path?\n pathCell = regexp(path, pathsep, 'split');\n myPath = fileparts(mfilename('fullpath'));\n if ~any(strcmp(myPath,pathCell))\n addpath(myPath)\n end\n \n functionsPath = fullfile(myPath,'functions');\n if ~any(strcmp(functionsPath,pathCell))\n addpath(functionsPath)\n end\n \n\n handles = ConfigureSVRLSMGUIOptions(handles);\n handles.details = CheckIfNecessaryFilesAreInstalled(handles);\n \n if handles.details.stats_toolbox && handles.details.spm && handles.details.libsvm\n handles = UpdateProgress(handles,'All necessary functions are available...',1);\n handles.parameters = GetDefaultParameters(handles);\n handles = PopulateGUIFromParameters(handles);\n elseif ~handles.details.spm \n handles = UpdateProgress(handles,'SPM12 functions not available. Download and/or add SPM12 to the MATLAB path and relaunch the SVRLSMGUI.',1);\n handles = DisableAll(handles);\n elseif ~handles.details.stats_toolbox && ~handles.details.libsvm\n handles = UpdateProgress(handles,'No SVR algorithm available. Install Statistics Toolbox in MATLAB or compile and install libSVM and relaunch the GUI.',1);\n handles = DisableAll(handles);\n elseif ~handles.details.stats_toolbox && handles.details.libsvm % yes stats toolbox, no libsvm\n handles = UpdateProgress(handles,'Only libSVM is available to compute images. MATLAB''s SVM will not be available.',1);\n handles.parameters = GetDefaultParameters(handles);\n handles = PopulateGUIFromParameters(handles);\n elseif handles.details.stats_toolbox && ~handles.details.libsvm % no stats toolbox, yes libsvm\n handles = UpdateProgress(handles,'Only MATLAB''s Stats Toolbox is available to compute images. libSVM will not be available.',1);\n handles.parameters = GetDefaultParameters(handles);\n handles = PopulateGUIFromParameters(handles);\n end\n\n handles.parameters.parallelize = handles.details.can_parallelize; % override default\n\n % 0.02 - trying to clean it up to run on a variety of systems - 4/24/17\n % 0.03 - first version to be used by other individuals officially - 5/1/17\n % 0.04 - 5/2/17\n % 0.05 - 7/26/17 - moved to the linux machine, working on improving stability and fixing bugs\n % 0.06 - August 2017 - added parallelization, continued development with paper\n % 0.07 - September 2017 - summary output, fixed bug in two tail thresholding, public release...\n % 0.08 - added diagnostic plot for behavioral nuisance model in summary\n % output file (corrplot); added custom support vector scaling\n % other than max of the map when backprojecting the analysis\n % hyperplane\n % 0.10 - January 2018 - fixing reported bugs\n % 0.15 - massive code refactoring and implementation of CFWER\n \n handles.parameters.gui_version = 0.15; % version of the the gui\n guidata(hObject, handles); % Update handles structure\n\nfunction handles = DisableAll(handles)\n set(get(handles.analysispreferencespanel,'children'),'enable','off')\n set(get(handles.covariatespanel,'children'),'enable','off')\n set(get(handles.permutationtestingpanel,'children'),'enable','off')\n set([handles.viewresultsbutton handles.interrupt_button handles.runanalysisbutton],'Enable','off') % handles.cancelanalysisbutton \n set(handles.optionsmenu,'enable','off') % since viewing this menu references parameters that may not be loaded. \n msgbox('One or more necessary component is missing from MATLAB''s path. Address the message in the SVRLSMgui window and restart this gui.')\n\nfunction handles = UpdateCurrentAnalysis(handles,hObject)\n changemade = true; % default\n\nswitch get(gcbo,'tag') % use gcbo to see what the cbo is and determine what field it goes to -- and to validate\n case 'no_map_crossvalidation' % turns off crossvalidation...\n handles.parameters.crossval.do_crossval = false;\n case 'kfold_map_crossvalidation'\n if handles.parameters.useLibSVM\n changemade=false;\n msgbox('Map crossvalidation not currently supported for libSVM - please switch implementation to MATLAB and try again.')\n return\n end\n answer = inputdlg(sprintf('Enter the numbers of folds for crossvalidation.'), ...\n 'Number of folds', 1,{num2str(handles.parameters.crossval.nfolds)});\n if isempty(answer), return; end % cancel pressed\n str = str2num(answer{1});\n if isempty(str) || str <= 0 || ~isint(str)\n changemade=false;\n warndlg('Input must be a positive integer.');\n else % update the parameter value.\n handles.parameters.crossval.do_crossval = true;\n handles.parameters.crossval.method = 'kfold';\n handles.parameters.crossval.nfolds = str;\n end\n case 'hyperparm_quality_report_options'\n set(handles.hyperparm_qual_n_folds,'Label',['Folds: ' num2str(handles.parameters.hyperparameter_quality.report.nfolds)])\n set(handles.repro_index_subset_percentage,'Label',['Subset %: ' num2str(handles.parameters.hyperparameter_quality.report.repro_ind_subset_pct)])\n set(handles.hyperparm_qual_n_replications,'Label',['Replications: ' num2str(handles.parameters.hyperparameter_quality.report.n_replications)])\n case 'hyperparm_qual_n_folds'\n answer = inputdlg(sprintf('Enter the number of folds for hyperparameter quality testing:'), ...\n 'Number of folds', 1,{num2str(handles.parameters.hyperparameter_quality.report.nfolds)});\n if isempty(answer), return; end % cancel pressed\n str = str2num(answer{1});\n if isempty(str) || str <= 1 || ~isint(str)\n changemade=false;\n warndlg('Input must be a positive integer greater than 1.');\n else % update the parameter value.\n handles.parameters.hyperparameter_quality.report.nfolds = str;\n end\n case 'repro_index_subset_percentage'\n answer = inputdlg('Enter the % of sample to use for computing w-map reproducibility index [0-1]:', ...\n 'Sample percent', 1,{num2str(handles.parameters.hyperparameter_quality.report.repro_ind_subset_pct)});\n if isempty(answer), return; end % cancel pressed\n str = str2num(answer{1});\n if isempty(str) || str <= 0 || str >= 1 % ~isint(str)\n changemade=false;\n warndlg('Input must be a value between 0 and 1 (i.e. 0 and 100%).');\n else % update the parameter value.\n handles.parameters.hyperparameter_quality.report.repro_ind_subset_pct = str;\n end\n case 'hyperparm_qual_n_replications'\n answer = inputdlg(sprintf('Enter the number of replications for hyperparameter quality testing:'), ...\n 'Number of replications', 1,{num2str(handles.parameters.hyperparameter_quality.report.n_replications)});\n if isempty(answer), return; end % cancel pressed\n str = str2num(answer{1});\n if isempty(str) || str <= 1 || ~isint(str)\n changemade=false;\n warndlg('Input must be a positive integer greater than 1.');\n else % update the parameter value.\n handles.parameters.hyperparameter_quality.report.n_replications = str;\n end\n case 'image_data_options_parent_menu'\n set(handles.do_binarize_data_menu_option,'Checked',myif(handles.parameters.imagedata.do_binarize,'on','off'))\n case 'do_binarize_data_menu_option'\n handles.parameters.imagedata.do_binarize = ~handles.parameters.imagedata.do_binarize;\n case 'set_resolution_parent_menu_option'\n set(handles.manual_analysis_resolution_menu,'Label',['Manual: ' num2str(handles.parameters.imagedata.resample_to) ' mm'], ...\n 'checked',myif(handles.parameters.imagedata.do_resample,'on','off'));\n set(handles.do_not_resample_images_menu,'Checked',myif(handles.parameters.imagedata.do_resample,'off','on'));\n %set(handles.manual_analysis_resolution_menu,'Enable','on') % Until we finish implementation.\n case 'do_not_resample_images_menu'\n handles.parameters.imagedata.do_resample = false; % turn resampling off.\n case 'manual_analysis_resolution_menu'\n answer = inputdlg(sprintf('Enter the size in mm for voxels to be resampled to.'), ...\n 'Resample size (mm)', 1,{num2str(handles.parameters.imagedata.resample_to)});\n if isempty(answer), return; end % cancel pressed\n str = str2num(answer{1});\n if isempty(str) || str <= 0 || ~isint(str)\n changemade=false;\n warndlg('Input must be a positive integer in millimeters.');\n else % update the parameter value.\n handles.parameters.imagedata.do_resample = true;\n handles.parameters.imagedata.resample_to = str;\n end\n case 'open_lesion_folder_button'\n OpenDirectoryInNativeWindow(handles.parameters.lesion_img_folder)\n case 'open_score_file_button'\n openFileInSystemViewer(handles.parameters.score_file)\n case 'open_output_folder_button'\n OpenDirectoryInNativeWindow(handles.parameters.analysis_out_path)\n case 'ica_lesion_decompose_option'\n handles.parameters.beta.do_ica_on_lesiondata = ~handles.parameters.beta.do_ica_on_lesiondata;\n case 'requirements_menu'\n case 'search_strategy_options'\n set(handles.optimization_iterations_menu_option,'Label',['Iterations: ' num2str(handles.parameters.optimization.iterations)])\n set(handles.griddivs_optimization_menu_option,'Label',['Grid Divs: ' num2str(handles.parameters.optimization.grid_divisions)])\n return\n\n case 'summary_prediction_menu'\n handles.parameters.summary.predictions = ~handles.parameters.summary.predictions;\n case 'lsm_method_parent_menu'\n set(get(handles.lsm_method_parent_menu,'children'),'checked','off')\n if handles.parameters.method.mass_univariate\n set(handles.mass_univariate_menu_option,'checked','on')\n set(handles.svr_parent_menu,'enable','off')\n else\n set(handles.multivariate_lsm_option,'checked','on')\n set(handles.svr_parent_menu,'enable','on')\n end\n \n if handles.details.libsvm || handles.details.stats_toolbox\n set(handles.multivariate_lsm_option,'enable','on')\n else\n handles.parameters.method.mass_univariate = true; % at least...\n set(handles.multivariate_lsm_option,'enable','off') \n end\n case 'mass_univariate_menu_option'\n handles.parameters.method.mass_univariate = true;\n case 'multivariate_lsm_option'\n handles.parameters.method.mass_univariate = false;\n case 'svr_parent_menu'\n case 'optimization_is_verbose_menu'\n handles.parameters.optimization.verbose_during_optimization = ~handles.parameters.optimization.verbose_during_optimization;\n case 'summary_lesionoverlap'\n handles.parameters.summary.lesion_overlap = ~handles.parameters.summary.lesion_overlap;\n case 'summary_paramoptimization'\n handles.parameters.summary.hyperparameter_optimization_record = ~handles.parameters.summary.hyperparameter_optimization_record;\n case 'summary_create_summary'\n handles.parameters.do_make_summary = ~handles.parameters.do_make_summary;\n case 'summary_narrative_summary'\n handles.parameters.summary.narrative = ~handles.parameters.summary.narrative;\n case 'summary_svrbetamap'\n handles.parameters.summary.beta_map = ~handles.parameters.summary.beta_map;\n case 'summary_voxelwise_thresholded'\n handles.parameters.summary.voxelwise_thresholded = ~handles.parameters.summary.voxelwise_thresholded;\n case 'summary_clusterwise_thresholded'\n handles.parameters.summary.clusterwise_thresholded = ~handles.parameters.summary.clusterwise_thresholded;\n case 'summary_cfwerdiagnostics'\n handles.parameters.summary.cfwer_diagnostics = ~handles.parameters.summary.cfwer_diagnostics;\n case 'model_variablediagnostics'\n handles.parameters.summary.variable_diagnostics = ~handles.parameters.summary.variable_diagnostics;\n case 'summary_clusterstability'\n handles.parameters.summary.cluster_stability = ~handles.parameters.summary.cluster_stability;\n case 'summary_parameterassessment'\n handles.parameters.summary.parameter_assessment = ~handles.parameters.summary.parameter_assessment;\n case 'do_use_cache_menu'\n handles.parameters.do_use_cache_when_available = ~handles.parameters.do_use_cache_when_available;\n case 'crossval_menu_option_none'\n handles.parameters.optimization.crossval.do_crossval = false; % disable crossvalidation.\n case 'crossval_menu_option_kfold'\n msg = sprintf('Enter the number of folds for cross-validation (default = %d):',handles.parameters.optimization.crossval.nfolds_default);\n answer = inputdlg(msg, ...\n 'Number of folds', 1,{num2str(handles.parameters.optimization.crossval.nfolds)});\n warning('bug here - if you click cancel it causes an error - in future, embed the str<=0 and isint within the isempty... and do that with other str2num(answer{1})''s as well')\n if isempty(answer), return; end % cancel pressed\n str = str2num(answer{1});\n if isempty(str) || str <= 0 || ~isint(str)\n changemade=false;\n warndlg('Input must be a positive integer.');\n else % update the parameter value.\n handles.parameters.optimization.crossval.do_crossval = true; % enable crossvalidation.\n handles.parameters.optimization.crossval.nfolds = str;\n end\n \n case 'do_repartition_menu_option' % flip this choice.\n handles.parameters.optimization.crossval.repartition = ~handles.parameters.optimization.crossval.repartition;\n case 'standardize_menu' % set the value to use if not optimization\n vals = {'true','false'};\n msg = sprintf('Standardize value (default = %s):',myif(handles.parameters.svr_defaults.standardize,'true','false'));\n s = listdlg('PromptString',msg,'SelectionMode','single', ...\n 'ListString',vals,'InitialValue',myif(handles.parameters.standardize,1,2), ...\n 'Name','Standardize Parameter','ListSize',[250 80]);\n \n if isempty(s)\n changemade=false; % cancelled...\n else\n handles.parameters.standardize = str2num(vals{s}); % myif(v==1,true,false); % new value.\n end\n \n case 'epsilon_menu' % set the value to use if not optimization\n msg = sprintf('Enter new value for epsilon (default = %0.2f):',handles.parameters.svr_defaults.epsilon);\n % add min and max range - dev1\n answer = inputdlg(msg,'Epsilon Parameter',1,{num2str(handles.parameters.epsilon)});\n if isempty(answer), return; end % cancel pressed\n numval = str2num(answer{1});\n if isnumeric(numval) && ~isempty(numval)\n handles.parameters.epsilon = numval;\n end\n\n % Whether to allow optimization of given hyperparameter\n case 'do_optimize_cost_menu'\n if ~handles.parameters.optimization.params_to_optimize.cost % then enabling it will prompt for new values...\n minmsg = sprintf('Minimum (default = %0.3f):',handles.parameters.optimization.params_to_optimize.cost_range_default(1));\n maxmsg = sprintf('Maximum (default = %0.2f):',handles.parameters.optimization.params_to_optimize.cost_range_default(2));\n msg = {minmsg,maxmsg};\n defaultans = {num2str(handles.parameters.optimization.params_to_optimize.cost_range(1)),num2str(handles.parameters.optimization.params_to_optimize.cost_range(2))};\n answer = inputdlg(msg,'Cost Range',1,defaultans);\n if isempty(answer), return; end % cancel pressed\n if any(cellfun(@isempty,answer)), warndlg('Invalid Cost range.'); return; end\n minval = str2num(answer{1}); maxval = str2num(answer{2});\n if ~all([isnumeric(minval) isnumeric(maxval)]), warndlg('Cost range values must be numbers.'); return; end\n if ~all([minval maxval] > 0), warndlg('Cost range values must be positive.'); return; end\n handles.parameters.optimization.params_to_optimize.cost_range = sort([minval maxval]);\n end\n \n handles.parameters.optimization.params_to_optimize.cost = ~handles.parameters.optimization.params_to_optimize.cost;\n case 'do_optimize_gamma_menu'\n if ~handles.parameters.optimization.params_to_optimize.sigma % then enabling it will prompt for new values...\n useLibSVM = handles.parameters.useLibSVM; % for convenience.\n parmname = myif(useLibSVM,'Gamma','Sigma'); % depending on what algorithm the user is using.\n defaultmin = handles.parameters.optimization.params_to_optimize.sigma_range_default(1);\n defaultmax = handles.parameters.optimization.params_to_optimize.sigma_range_default(2);\n minmsg = sprintf('Minimum (default = %0.3f):',myif(useLibSVM,sigma2gamma(defaultmin),defaultmin)); % convert to gamma if necessary\n maxmsg = sprintf('Maximum (default = %0.2f):',myif(useLibSVM,sigma2gamma(defaultmax),defaultmax)); % convert to gamma if necessary\n msg = {minmsg,maxmsg};\n oldmin = handles.parameters.optimization.params_to_optimize.sigma_range(1);\n oldmax = handles.parameters.optimization.params_to_optimize.sigma_range(2);\n defaultans = {num2str(myif(useLibSVM,sigma2gamma(oldmin),oldmin)),num2str(myif(useLibSVM,sigma2gamma(oldmax),oldmax))}; % convert to gamma if necessary\n answer = inputdlg(msg,[parmname ' Range'],1,defaultans); % display as gamma if necessary\n if isempty(answer), return; end % cancel pressed\n if any(cellfun(@isempty,answer)), warndlg(['Invalid ' parmname ' range.']); return; end\n minval = str2num(answer{1}); maxval = str2num(answer{2});\n if ~all([isnumeric(minval) isnumeric(maxval)]), warndlg([parmname ' range values must be numbers.']); return; end % display as gamma if necessary\n if ~all([minval maxval] > 0), warndlg([parmname ' range values must be positive.']); return; end % display as gamma if necessary\n handles.parameters.optimization.params_to_optimize.sigma_range = sort([myif(useLibSVM,sigma2gamma(minval),minval) myif(useLibSVM,sigma2gamma(maxval),maxval)]); % convert gamma back to sigma if necessary.\n end\n\n handles.parameters.optimization.params_to_optimize.sigma = ~handles.parameters.optimization.params_to_optimize.sigma;\n case 'do_optimize_epsilon_menu'\n if ~handles.parameters.optimization.params_to_optimize.epsilon % then enabling it will prompt for new values...\n minmsg = sprintf('Minimum (default = %0.3f):',handles.parameters.optimization.params_to_optimize.epsilon_range_default(1));\n maxmsg = sprintf('Maximum (default = %0.2f):',handles.parameters.optimization.params_to_optimize.epsilon_range_default(2));\n msg = {minmsg,maxmsg};\n defaultans = {num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(1)),num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(2))};\n answer = inputdlg(msg,'Epsilon Range',1,defaultans);\n if isempty(answer), return; end % cancel pressed\n if any(cellfun(@isempty,answer)), warndlg('Invalid Epsilon range.'); return; end\n minval = str2num(answer{1}); maxval = str2num(answer{2});\n if ~all([isnumeric(minval) isnumeric(maxval)]), warndlg('Epsilon range values must be numbers.'); return; end\n if ~all([minval maxval] > 0), warndlg('Epsilon range values must be positive.'); return; end\n handles.parameters.optimization.params_to_optimize.epsilon_range = sort([minval maxval]);\n end\n handles.parameters.optimization.params_to_optimize.epsilon = ~handles.parameters.optimization.params_to_optimize.epsilon;\n case 'do_optimize_standardize_menu'\n handles.parameters.optimization.params_to_optimize.standardize = ~handles.parameters.optimization.params_to_optimize.standardize;\n\n % Optimization misc choices\n case 'optimization_iterations_menu_option'\n answer = inputdlg('Enter a new number of iterations:','Number of optimization iterations',1,{num2str(handles.parameters.optimization.iterations)});\n if isempty(answer), return; end % cancel pressed\n str = str2num(answer{1});\n if isempty(str) || str <= 0 || ~isint(str)\n changemade=false;\n warndlg('Input must be a positive integer.');\n else % update the parameter value.\n handles.parameters.optimization.iterations = str;\n end\n case 'griddivs_optimization_menu_option'\n answer = inputdlg('Enter a new number of grid divisions:','Number of optimization grid divisions',1,{num2str(handles.parameters.optimization.grid_divisions)});\n if isempty(answer), return; end % cancel pressed\n str = str2num(answer{1});\n if isempty(str) || str <= 0 || ~isint(str)\n changemade=false;\n warndlg('Input must be a positive integer.');\n else % update the parameter value.\n handles.parameters.optimization.grid_divisions = str;\n end \n \n % Optimization search strategy choice\n case 'random_search_menu_option'\n handles.parameters.optimization.search_strategy = 'Random Search';\n case 'bayes_optimization_menu_choice'\n handles.parameters.optimization.search_strategy = 'Bayes Optimization';\n case 'gridsearch_option'\n handles.parameters.optimization.search_strategy = 'Grid Search'; \n\n % Optimization objective function choice\n case 'predictbehavior_optimize_menu_choice' % bayes opt predict behavior\n handles.parameters.optimization.objective_function = 'Predict Behavior';\n case 'correlation_optimize_menu_choice' % maximum correlation w behavior\n handles.parameters.optimization.objective_function = 'Maximum Correlation';\n case 'resubloss_optimize_menu_choice'\n handles.parameters.optimization.objective_function = 'Resubstitution Loss';\n % Whether or not to optimize hyperparameters\n case 'no_optimize_menu_choice'\n handles.parameters.optimization.do_optimize = false;\n case 'current_optimization_menu_option'\n handles.parameters.optimization.do_optimize = true; % will use whatever setting is configured.\n \n\t% Which SVR algorithm to use\n case 'use_lib_svm'\n handles.parameters.useLibSVM = 1;\n handles.parameters.crossval.do_crossval = false; % not currently supported for libsvm...\n case 'use_matlab_svr'\n handles.parameters.useLibSVM = 0; \n case 'save_pre_thresh'\n handles.parameters.SavePreThresholdedPermutations = ~handles.parameters.SavePreThresholdedPermutations;\n case 'retain_big_binary_file'\n handles.parameters.SavePermutationData = ~handles.parameters.SavePermutationData;\n case 'save_post_vox_thresh'\n handles.parameters.SavePostVoxelwiseThresholdedPermutations = ~handles.parameters.SavePostVoxelwiseThresholdedPermutations;\n case 'save_post_clusterwise_thresholded'\n handles.parameters.SavePostClusterwiseThresholdedPermutations= ~handles.parameters.SavePostClusterwiseThresholdedPermutations;\n case 'save_unthresholded_pmaps_cfwer'\n handles.parameters.SaveNullPMapsPreThresholding = ~handles.parameters.SaveNullPMapsPreThresholding;\n case 'save_thresholded_pmaps_cfwer'\n handles.parameters.SaveNullPMapsPostThresholding = ~handles.parameters.SaveNullPMapsPostThresholding;\n case 'retain_big_binary_pval_file'\n handles.parameters.SavePermutationPData = ~handles.parameters.SavePermutationPData;\n case 'parallelizemenu'\n handles.parameters.parallelize = ~handles.parameters.parallelize;\n case 'applycovariatestobehaviorcheckbox'\n handles.parameters.apply_covariates_to_behavior = get(gcbo,'value');\n case 'applycovariatestolesioncheckbox'\n handles.parameters.apply_covariates_to_lesion = get(gcbo,'value');\n case 'lesionvolumecorrectiondropdown'\n contents = get(handles.lesionvolumecorrectiondropdown,'string');\n newval = contents{get(handles.lesionvolumecorrectiondropdown,'value')};\n handles.parameters.lesionvolcorrection = newval;\n case 'hypodirectiondropdown'\n contents = get(handles.hypodirectiondropdown,'string');\n newval = contents{get(handles.hypodirectiondropdown,'value')};\n if find(strcmp(newval,handles.options.hypodirection)) == 3 % Disable two-tails from the GUI\n warndlg('Two-tailed hypothesis tests are not available in this version of SVRLSMGUI.')\n changemade = false;\n else\n handles.parameters.tails = newval;\n end\n case 'addcovariate'\n % first, what are we trying to add?\n contents = get(handles.potentialcovariateslist,'String'); \n newcovariate = contents{get(handles.potentialcovariateslist,'Value')};\n if strcmp(newcovariate,handles.parameters.score_name) % check if it's our main score name...\n warndlg('This variable is already chosen as the main outcome in the analysis. If you''d like to add it as a covariate, remove it from \"Score Name.\"')\n changemade = false;\n elseif any(strcmp(newcovariate,handles.parameters.control_variable_names)) % only if it's not on our list of covariates already.\n warndlg('This variable is already on the list of covariates. You may not add it twice.')\n changemade = false;\n else % it's new\n handles.parameters.control_variable_names{end+1} = newcovariate;\n end\n case 'removecovariate'\n contents = get(handles.potentialcovariateslist,'String'); % what are we trying to remove? \n newcovariate = contents{get(handles.potentialcovariateslist,'Value')};\n if any(strcmp(newcovariate,handles.parameters.control_variable_names)) % only if it IS on our list!\n index_to_remove = strcmp(newcovariate,handles.parameters.control_variable_names);\n handles.parameters.control_variable_names(index_to_remove) = [];\n else\n changemade = false;\n end\n case 'chooselesionfolderbutton'\n folder_name = uigetdir(handles.parameters.lesion_img_folder,'Choose a folder containing lesion files for this analysis.');\n if folder_name % if folder_name == 0 then cancel was clicked.\n [~,attribs] = fileattrib(folder_name); % we need read access from here.\n if attribs.UserRead\n handles.parameters.lesion_img_folder = folder_name;\n else\n warndlg('You do not have read access to the directory you selected for the lesion files. Adjust the permissions and try again.')\n changemade = false; \n end\n else\n changemade = false;\n end\n case 'choosescorefilebutton'\n [FileName,PathName] = uigetfile(fullfile(fileparts(handles.parameters.score_file),'*.csv'),'Select a file with behavioral scores.');\n if FileName\n scorefile_name = fullfile(PathName,FileName);\n handles.parameters.score_file = scorefile_name;\n handles.parameters.control_variable_names = {}; % also clear covariates... \n else % cancel was clicked.\n changemade = false;\n end\n case 'chooseoutputfolderbutton'\n folder_name = uigetdir(handles.parameters.analysis_out_path,'Choose a folder in which to save this analysis.');\n if folder_name\n [~,attribs] = fileattrib(folder_name); % we need read/write access from here.\n if attribs.UserRead && attribs.UserWrite\n handles.parameters.analysis_out_path = folder_name;\n else\n warndlg('You do not have read and write access to the directory you selected to save your output. Adjust the permissions and try again.')\n changemade = false; \n end\n else\n changemade = false;\n end\n case 'scorenamepopupmenu' % User has changed the one_score in question...\n contents = get(gcbo,'string');\n newval = contents{get(gcbo,'value')};\n if any(strcmp(newval,handles.parameters.control_variable_names))\n warndlg('This variable is already chosen as a covariate. If you''d like to use it as the outcome of interest, remove it as a covariate.')\n changemade = false;\n else\n handles.parameters.score_name = newval;\n end\n case 'analysisnameeditbox'\n handles.parameters.analysis_name = get(gcbo,'string');\n case 'lesionthresholdeditbox'\n str = str2num(get(gcbo,'string')); %TO ADD: also make sure this doesn''t exceed the number of lesions available in the data\n if isempty(str) || ~isint(str) \n warndlg('Input must be a positive integer.');\n changemade = false;\n else % update the parameter value.\n handles.parameters.lesion_thresh = str;\n end\n case 'computebetamapcheckbox'\n handles.parameters.beta_map = get(gcbo,'value');\n case 'computesensitivitymapcheckbox'\n handles.parameters.sensitivity_map = get(gcbo,'value');\n case 'cluster_voxelwise_p_editbox' \n str = str2num(get(gcbo,'string'));\n if isempty(str) || str <= 0 || str >= 1 \n changemade = false;\n warndlg('Input must be a number between 0 and 1.');\n else % update the parameter value.\n handles.parameters.voxelwise_p = str;\n end\n case 'clusterwisepeditbox'\n str = str2num(get(gcbo,'string'));\n if isempty(str) || str <= 0 || str >= 1\n warndlg('Input must be a number between 0 and 1.');\n changemade = false;\n else % update the parameter value.\n handles.parameters.clusterwise_p = str;\n end\n case 'sv_scaling_95th_percentile'\n handles.parameters.svscaling = 95;\n case 'sv_scaling_99th_percentile'\n handles.parameters.svscaling = 99;\n case 'maxsvscaling'\n handles.parameters.svscaling = 100; % default\n case 'npermutationseditbox' % This is voxelwise permutations\n str = str2num(get(gcbo,'string'));\n if isempty(str) || str<=0 || ~isint(str)\n changemade = false;\n warndlg('Input must be a positive integer.');\n else % update the parameter value.\n handles.parameters.PermNumVoxelwise = str;\n end\n case 'permutationtestingcheckbox' % enable/disable permutation testing.\n handles.parameters.DoPerformPermutationTesting = get(gcbo,'value');\n case 'do_cfwer_checkbox'\n handles.parameters.do_CFWER = get(gcbo,'value');\n case 'cfwer_v_value_editbox'\n str = str2num(get(gcbo,'string'));\n if isempty(str) || str <= 0 || ~isint(str)\n changemade=false;\n warndlg('Input must be a positive integer.');\n else % update the parameter value.\n handles.parameters.cfwer_v_value = str; % note that this is cubic millimeters and will later be converted into # voxels (in read_lesioned_images)\n end\n case 'cfwer_p_value_editbox'\n str = str2num(get(gcbo,'string'));\n if isempty(str) || str<=0 || str >= 1 % not a valid p value...\n changemade=false;\n warndlg('Input must be a positive number less than 1.');\n else % update the parameter value.\n handles.parameters.cfwer_p_value = str;\n end\n case 'analysismask_menu_option_parent'\n if strcmp(handles.parameters.analysis_mask_file,'')\n maskstring = 'Select mask...';\n else\n maskstring = handles.parameters.analysis_mask_file;\n end\n handles.datamask_to_use_menu_option.Text = maskstring;\n \n if handles.parameters.use_analysis_mask % then populate the menu item and set the checkbox...\n handles.do_not_apply_datamask_menu_option.Checked = false;\n handles.datamask_to_use_menu_option.Checked = true;\n else % don't use mask.\n handles.do_not_apply_datamask_menu_option.Checked = true;\n handles.datamask_to_use_menu_option.Checked = false;\n end\n \n case 'do_not_apply_datamask_menu_option'\n handles.parameters.use_analysis_mask = false;\n changemade = true;\n case 'datamask_to_use_menu_option'\n disp('a')\n handles.parameters.use_analysis_mask = true;\n [FileName,PathName] = uigetfile('*.nii','Select a mask file within which to run the analysis.');\n filepath = fullfile(PathName,FileName);\n if ~exist(filepath,'file'), return; end\n handles.parameters.analysis_mask_file = filepath; \n changemade = true;\n otherwise\n warndlg(['Unknown callback object ' get(gcbo,'tag') ' - has someone modified the code?'])\nend\n\n if changemade % then set to not saved...\n handles.parameters.is_saved = 0;\n end\n\n if ~handles.parameters.is_saved % then the analysis configuration was modified, so it hasn't been completed in its current state.\n handles.parameters.analysis_is_completed = 0; % set \"is completed\" to 0 (in its current state) so the user can click run button, and cannot click show output button.\n handles = PopulateGUIFromParameters(handles);\n end\n\n guidata(hObject, handles); % Update handles structure\n UpdateTitleBar(handles); % update title bar to show if we have any changes made.\n\nfunction doignore = IgnoreUnsavedChanges(handles)\n if ~isfield(handles,'parameters') % something bad probably happened with gui initiation.\n \tdoignore = 1; \n elseif isfield(handles.parameters,'is_saved') && ~handles.parameters.is_saved % then prompt if the user wants to continue or cancel.\n choice = questdlg('If you continue you will lose unsaved changes to this analysis configuration.', 'Unsaved Changes', 'Continue Anyway','Cancel','Cancel');\n switch choice\n case 'Continue Anyway', doignore = 1;\n case 'Cancel', doignore = 0;\n end\n else % don't hang \n doignore = 1;\n end\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = svrlsmgui_OutputFcn(hObject, eventdata, handles) \nvarargout{1} = handles.output;\n\nfunction newmenu_Callback(hObject, eventdata, handles) %#ok<*DEFNU>\n if IgnoreUnsavedChanges(handles)\n handles.parameters = GetDefaultParameters(handles);\n handles = PopulateGUIFromParameters(handles);\n end\n\nfunction openmenu_Callback(hObject, eventdata, handles)\n if IgnoreUnsavedChanges(handles)\n [FileName,PathName] = uigetfile('*.mat','Select an SVRLSMGUI parameters file.');\n filepath = fullfile(PathName,FileName);\n if ~exist(filepath,'file'), return; end\n handles = LoadParametersFromSVRLSMFile(handles,hObject,filepath);\n end\n\nfunction closemenu_Callback(hObject, eventdata, handles)\n if IgnoreUnsavedChanges(handles)\n delete(gcf)\n end\n\nfunction savemenu_Callback(hObject, eventdata, handles)\n if exist(handles.parameters.parameter_file_name,'file')\n handles = SaveSVRLSMGUIFile(handles,hObject); % do the actual save.\n else\n saveasmenu_Callback(hObject, eventdata, handles)\n end\n \nfunction saveasmenu_Callback(hObject, eventdata, handles)\n if exist(handles.parameters.parameter_file_name,'file')\n defaultsavename = handles.parameters.parameter_file_name; % fileparts(handles.parameters.parameter_file_name);\n else\n defaultsavename = fullfile(pwd,'Unnamed.mat');\n end\n [file,path] = uiputfile('*.mat','Save SVRLSM GUI parameter file as...',defaultsavename);\n if file == 0 % then cancel was pressed\n return;\n end\n\n handles.parameters.parameter_file_name = fullfile(path,file);\n handles = SaveSVRLSMGUIFile(handles,hObject); % do the actual save.\n\nfunction quitmenu_Callback(hObject, eventdata, handles)\n close(gcf) % to trigger close request fcn which handles unsaved changes...\n \nfunction onlinehelpmenu_Callback(hObject, eventdata, handles)\nweb('https://github.com/atdemarco/svrlsmgui/wiki')\n\nfunction figure1_CreateFcn(hObject, eventdata, handles)\n\nfunction aboutmenu_Callback(hObject, eventdata, handles)\n helpstr = ['SVRLSM GUI ' num2str(handles.parameters.gui_version) ', Andrew DeMarco 2017-2018, based on Zhang et al. (2014)'];\n helpdlg(helpstr,'About');\n\nfunction runanalysisbutton_Callback(hObject, eventdata, handles)\n [success,handles] = RunAnalysis(hObject,eventdata,handles); % now returns handles 10/26/17\n\n set(handles.runanalysisbutton,'Enable','on') %set(handles.cancelanalysisbutton,'visible','off')\n\n % Re-enable interface...\n set(get(handles.permutationtestingpanel,'children'),'enable','on')\n set(get(handles.analysispreferencespanel,'children'),'enable','on')\n set(get(handles.covariatespanel,'children'),'enable','on')\n \n switch success\n case 1 % success\n handles.parameters.analysis_is_completed = 1; % Completed...\n handles = UpdateProgress(handles,'Analysis has completed successfully.',1);\n case 0 % failure\n handles.parameters.analysis_is_completed = 2; % Error...\n handles = UpdateProgress(handles,'Analysis encountered an error and did not complete...',1);\n set(handles.interrupt_button,'enable','off') % disable.\n rethrow(handles.error)\n case 2 % interrupted\n handles.parameters.analysis_is_completed = 2; % Error...\n handles = UpdateProgress(handles,'Analysis was interrupted by user...',1); \n end\n \n guidata(hObject, handles); % Update handles structure\n handles = PopulateGUIFromParameters(handles); % refresh gui so we can enable/disable control variable as necessary.\n\n% Select in the dropdown list the selected item.\nfunction realcovariateslistbox_Callback(hObject, eventdata, handles)\n if isempty(get(hObject,'String')), return; end % hack for error\n contents = cellstr(get(hObject,'String'));\n val = contents{get(hObject,'Value')};\n dropdownoptions = get(handles.potentialcovariateslist,'string');\n set(handles.potentialcovariateslist,'value',find(strcmp(val,dropdownoptions)))\n\nfunction optionsmenu_Callback(hObject, eventdata, handles)\n yn = {'off','on'};\n set(handles.parallelizemenu,'Checked',yn{1+handles.parameters.parallelize}) % is parallelization selected by user?\n set(handles.parallelizemenu,'Enable',yn{1+handles.details.can_parallelize}) % can we parallelize on this platform?\n\nfunction SVscalingmenu_Callback(hObject, eventdata, handles)\n children = get(handles.SVscalingmenu,'children');\n set(children,'Checked','off')\n\n switch handles.parameters.svscaling\n case 100 % these are ordered \"backward\" seeming, so 3rd is top in list\n set(children(3),'Checked','on')\n case 99\n set(children(2),'Checked','on')\n case 95\n set(children(1),'Checked','on')\n end\n\nfunction save_perm_data_Callback(hObject, eventdata, handles) % update the subitems with checkboxes\n yn = {'off','on'};\n set(handles.save_post_clusterwise_thresholded,'Checked',yn{1+handles.parameters.SavePostClusterwiseThresholdedPermutations})\n set(handles.save_post_vox_thresh,'Checked',yn{1+handles.parameters.SavePostVoxelwiseThresholdedPermutations})\n set(handles.save_pre_thresh,'Checked',yn{1+handles.parameters.SavePreThresholdedPermutations})\n % the cfwer files...\n set(handles.save_unthresholded_pmaps_cfwer,'Checked',yn{1+handles.parameters.SaveNullPMapsPreThresholding})\n set(handles.save_thresholded_pmaps_cfwer,'Checked',yn{1+handles.parameters.SaveNullPMapsPostThresholding})\n\nfunction svrmenu_Callback(hObject, eventdata, handles)\nif handles.parameters.useLibSVM\n set(handles.use_lib_svm,'checked','on')\n set(handles.use_matlab_svr,'checked','off')\nelse\n set(handles.use_lib_svm,'checked','off')\n set(handles.use_matlab_svr,'checked','on')\nend\nif handles.details.stats_toolbox\n set(handles.use_matlab_svr,'enable','on')\nelse\n set(handles.use_matlab_svr,'enable','off')\nend\nif handles.details.libsvm\n set(handles.use_lib_svm,'enable','on')\nelse\n set(handles.use_lib_svm,'enable','off')\nend\n\nfunction cost_menu_Callback(hObject, eventdata, handles)\n msg = sprintf('Enter new parameter value for Cost/BoxConstraint (default = %0.1f)',handles.parameters.svr_defaults.cost);\n answer = inputdlg(msg,'Cost Parameter',1,{num2str(handles.parameters.cost)});\n if isempty(answer), return; end % cancel pressed\n numval = str2num(answer{1}); %#ok<*ST2NM>\n if isnumeric(numval) && ~isempty(numval)\n handles.parameters.cost = numval;\n handles.parameters.is_saved = 0;\n guidata(hObject, handles);\n handles = PopulateGUIFromParameters(handles);\n end\n \nfunction gamma_menu_Callback(hObject, eventdata, handles)\n useLibSVM = handles.parameters.useLibSVM; % for convenience.\n parmname = myif(useLibSVM,'Gamma','Sigma'); % depending on what algorithm the user is using.\n defaultval = handles.parameters.svr_defaults.sigma; \n msg = sprintf('Enter new parameter value for %s (default = %0.1f)',parmname,myif(useLibSVM,sigma2gamma(defaultval),defaultval)); % convert to gamma if necessary\n oldval = handles.parameters.sigma;\n answer = inputdlg(msg,[parmname ' Parameter'],1,{num2str(myif(useLibSVM,sigma2gamma(oldval),oldval))}); % convert to gamma if necessary\n if isempty(answer), return; end % cancel pressed\n numval = str2num(answer{1});\n if isnumeric(numval) && ~isempty(numval)\n handles.parameters.sigma = myif(useLibSVM,gamma2sigma(numval),numval); % store as sigma, so convert input gamma to sigma if necessary...\n handles.parameters.is_saved = 0;\n guidata(hObject, handles);\n handles = PopulateGUIFromParameters(handles);\n end\n \nfunction open_batch_job_Callback(hObject, eventdata, handles)\n folder_name = uigetdir(pwd,'Choose a folder containing .mat config files of your analyses.');\n if ~folder_name, return; end % if folder_name == 0 then cancel was clicked.\n files = dir(fullfile(folder_name,'*.mat'));\n fname = {files.name};\n [s,v] = listdlg('PromptString','Choose the analyses to run:','SelectionMode','multi','ListString',fname);\n if ~v, return; end % cancelled..\n for f = 1:numel(s)\n curs=s(f);\n curfname = fname{curs};\n curfile = fullfile(folder_name,curfname);\n% try % so one or more can fail without stopping them all.\n handles = UpdateProgress(handles,['Batch: Starting file ' curfname '...'],1);\n [success,handles] = RunAnalysisNoGUI(curfile,handles); % second parm, handles, allows access to gui elements, etc.\n handles = UpdateProgress(handles,['Batch: Finished file ' curfname '.'],1);\n \n switch success\n case 1 % success\n handles.parameters.analysis_is_completed = 1; % Completed...\n handles = UpdateProgress(handles,['Batch: Finished file successfully ' curfname '.'],1);\n case 0 % failure\n handles.parameters.analysis_is_completed = 2; % Error...\n %handles = UpdateProgress(handles,'Analysis encountered an error and did not complete...',1);\n handles = UpdateProgress(handles,['Batch: Analysis encountered an error and did not complete: ' curfname '.'],1);\n if isfield(handles,'interrupt_button')\n set(handles.interrupt_button,'enable','off') % disable.\n end\n rethrow(handles.error)\n end\n\n% catch\n% disp('return from open_batch_job in svrlsmgui() with error')\n% msg = ['A batch job specified by file ' fname{curs} ' encountered an error and was aborted.'];\n% warning(msg)\n% end\n end\n \n handles = UpdateProgress(handles,'Batch: All batch jobs done.',1); \n\nfunction figure1_CloseRequestFcn(hObject, eventdata, handles)\n if IgnoreUnsavedChanges(handles), delete(hObject); end\n\nfunction checkforupdates_Callback(hObject, eventdata, handles)\n update_available = check_for_updates;\n if ~update_available\n msgbox('There are no updates available.')\n return\n end\n choice = questdlg('New updates are available, would you like to download them?','Update SVRLSMGUI','Not now','Update now','Update now');\n if strcmp(choice,'Not now'), return, end\n get_new_version(handles)\n\n%% callbacks -- replace these in the future.\nfunction controlvariablepopupmenu_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\n\nfunction computebetamapcheckbox_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\nfunction computesensitivitymapcheckbox_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\nfunction analysisnameeditbox_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\n\nfunction permutation_unthresholded_checkbox_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\nfunction permutation_voxelwise_checkbox_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\nfunction permutation_largest_cluster_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\nfunction progresslistbox_Callback(hObject, eventdata, handles)\nfunction maxsvscaling_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\nfunction potentialcovariateslist_Callback(hObject, eventdata, handles)\n\nfunction viewresultsbutton_Callback(hObject, eventdata, handles)\n LaunchResultsDirectory(hObject,eventdata,handles);\nfunction npermutationsclustereditbox_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\n\nfunction parallelizemenu_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\nfunction sv_scaling_99th_percentile_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\nfunction sv_scaling_95th_percentile_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\nfunction debug_menu_Callback(hObject, eventdata, handles)\n\nfunction use_lib_svm_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\nfunction use_matlab_svr_Callback(hObject, eventdata, handles)\nhandles = UpdateCurrentAnalysis(handles,hObject);\n\nfunction interrupt_button_Callback(hObject, eventdata, handles) % attempt to interrupt an ongoing analysis\n set(hObject,'enable','off') % so user doesn't click a bunch...\n% poolobj = gcp('nocreate'); % < this doesn't stop, it just relaunches the parpool...\n% delete(poolobj); % try to stop what's happening if there's parallelization happening\n set(gcf,'userdata','cancel')\n guidata(hObject, handles); % Update handles structure so it saves...\n\nfunction no_optimize_menu_choice_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\n\nfunction correlation_optimize_menu_choice_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\n \nfunction resubloss_optimize_menu_choice_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\n\nfunction predictbehavior_optimize_menu_choice_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\n\nfunction optimize_menu_Callback(hObject, eventdata, handles)\n set(get(hObject,'Children'),'Checked','off') % uncheck all child menus\n cur_optim_string = CurrentOptimString(handles.parameters);\n set(handles.current_optimization_menu_option,'Label',cur_optim_string)\n opts = [handles.parameters_to_optimize_menu handles.search_strategy_menu_option handles.objective_function_menu_option handles.crossvalidation_parent_menu handles.optimization_is_verbose_menu];\n if ~handles.parameters.optimization.do_optimize % then no optimization...\n set(handles.no_optimize_menu_choice,'Checked','on')\n set(opts,'enable','off') % Visual cue that these don't apply when optimization is off\n else \n set(handles.current_optimization_menu_option,'Checked','on')\n set(opts,'enable','on') % Visual cue that these don't apply when optimization is off\n end\n if handles.parameters.optimization.verbose_during_optimization \n set(handles.optimization_is_verbose_menu,'Checked','on')\n end\n\nfunction current_optimization_menu_option_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\n\nfunction parameters_menu_Callback(hObject, eventdata, handles)\n do_opt = handles.parameters.optimization.do_optimize; % for convenience\n\n if do_opt && handles.parameters.optimization.params_to_optimize.cost\n label = ['Cost: optimize (' num2str(handles.parameters.optimization.params_to_optimize.cost_range(1)) ' - ' num2str(handles.parameters.optimization.params_to_optimize.cost_range(2)) ')'];\n set(handles.cost_menu,'label',label,'enable','off');\n else\n set(handles.cost_menu,'label',['Cost: ' num2str(handles.parameters.cost) myif(handles.parameters.svr_defaults.cost == handles.parameters.cost,' (default)','')],'enable','on');\n end\n\n useLibSVM = handles.parameters.useLibSVM; % for convenience.\n parmname = myif(useLibSVM,'Gamma','Sigma'); % depending on what algorithm the user is using.\n if do_opt && handles.parameters.optimization.params_to_optimize.sigma\n oldmin = handles.parameters.optimization.params_to_optimize.sigma_range(1);\n oldmax = handles.parameters.optimization.params_to_optimize.sigma_range(2);\n label = [parmname ': optimize (' num2str(myif(useLibSVM,sigma2gamma(oldmin),oldmin)) ' - ' num2str(myif(useLibSVM,sigma2gamma(oldmax),oldmax)) ')'];\n set(handles.gamma_menu,'label',label,'enable','off');\n else \n cursigma = handles.parameters.sigma; % Display as gamma if use libSVM\n cursigma = myif(useLibSVM,sigma2gamma(cursigma),cursigma); % Display as gamma if use libSVM\n set(handles.gamma_menu,'label',[parmname ': ' num2str(cursigma) myif(handles.parameters.svr_defaults.sigma == handles.parameters.sigma,' (default)','')],'enable','on'); % Display as gamma if use libSVM\n end\n \n if do_opt && handles.parameters.optimization.params_to_optimize.epsilon\n label = ['Epsilon: optimize (' num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(1)) ' - ' num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(2)) ')'];\n set(handles.epsilon_menu,'label',label,'enable','off');\n else\n set(handles.epsilon_menu,'label',['Epsilon: ' num2str(handles.parameters.epsilon) myif(handles.parameters.svr_defaults.epsilon == handles.parameters.epsilon,' (default)','')],'enable','on'); \n end\n\n if do_opt && handles.parameters.optimization.params_to_optimize.standardize\n set(handles.standardize_menu,'label','Standardize: optimize (yes/no)','enable','off');\n else\n set(handles.standardize_menu,'label',['Standardize: ' myif(handles.parameters.standardize,'true','false') myif(handles.parameters.svr_defaults.standardize == handles.parameters.standardize,' (default)','')],'enable','on');\n end\n \nfunction epsilon_menu_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\n \nfunction standardize_menu_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\n \n%% Objective function...\nfunction objective_function_menu_option_Callback(hObject, eventdata, handles)\n set(get(hObject,'Children'),'Checked','off') % uncheck all child menus\n set([handles.predictbehavior_optimize_menu_choice handles.correlation_optimize_menu_choice],'enable','off')\n switch handles.parameters.optimization.objective_function\n case 'Predict Behavior'\n set(handles.predictbehavior_optimize_menu_choice,'Checked','on')\n case 'Maximum Correlation'\n set(handles.correlation_optimize_menu_choice,'Checked','on')\n case 'Resubstitution Loss'\n set(handles.resubloss_optimize_menu_choice,'Checked','on')\n otherwise\n error('Unknown optimization objective function.')\n end\n \n%% Search strategy ...\nfunction search_strategy_menu_option_Callback(hObject, eventdata, handles)\n set(get(hObject,'Children'),'Checked','off') % uncheck all child menus\n switch handles.parameters.optimization.search_strategy\n case 'Bayes Optimization'\n set(handles.bayes_optimization_menu_choice,'Checked','on')\n case 'Grid Search'\n set(handles.gridsearch_option,'Checked','on')\n case 'Random Search'\n set(handles.random_search_menu_option,'Checked','on')\n otherwise\n error('Unknown optimization objective function.')\n end\n\nfunction parameters_to_optimize_menu_Callback(hObject, eventdata, handles)\n set(get(hObject,'children'),'checked','off')\n \n if handles.parameters.optimization.params_to_optimize.cost\n label = ['Cost (' num2str(handles.parameters.optimization.params_to_optimize.cost_range(1)) ' - ' num2str(handles.parameters.optimization.params_to_optimize.cost_range(2)) ')'];\n set(handles.do_optimize_cost_menu,'label',label,'checked','on')\n end\n \n useLibSVM = handles.parameters.useLibSVM; % for convenience.\n parmname = myif(useLibSVM,'Gamma','Sigma'); % depending on what algorithm the user is using, show gamma vs sigma...\n curmin = handles.parameters.optimization.params_to_optimize.sigma_range(1); % convert to sigma if necessary...\n curmax = handles.parameters.optimization.params_to_optimize.sigma_range(2); % convert to sigma if necessary...\n label = [parmname ' (' num2str(myif(useLibSVM,sigma2gamma(curmin),curmin)) ' - ' num2str(myif(useLibSVM,sigma2gamma(curmax),curmax)) ')']; % convert to sigma if necessary...\n set(handles.do_optimize_gamma_menu,'label',label,'checked',myif(handles.parameters.optimization.params_to_optimize.sigma,'on','off'))\n \n if handles.parameters.optimization.params_to_optimize.epsilon\n label = ['Epsilon (' num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(1)) ' - ' num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(2)) ')'];\n set(handles.do_optimize_epsilon_menu,'label',label,'checked','on')\n end\n \n if handles.parameters.optimization.params_to_optimize.standardize\n label = 'Standardize (yes/no)';\n set(handles.do_optimize_standardize_menu,'label',label,'checked','on')\n end\n \n %set(handles.do_optimize_epsilon_menu,'enable','on')\n \n %dev1\n %set(handles.do_optimize_standardize_menu,'enable','on') % there's a problem passing 'Standardize' hyperopt range to bayesopt... so don't allow optimization of it.\n \n %set(get(hObject,'children'),'enable','on')\n\nfunction crossvalidation_parent_menu_Callback(hObject, eventdata, handles)\n set(get(hObject,'children'),'checked','off')\n set(handles.crossval_menu_option_kfold,'label',['K-Fold: ' num2str(handles.parameters.optimization.crossval.nfolds) ' folds' myif(handles.parameters.optimization.crossval.nfolds == handles.parameters.optimization.crossval.nfolds_default,' (default)','')])\n if ~handles.parameters.optimization.crossval.do_crossval\n set(handles.crossval_menu_option_none,'checked','on')\n set(handles.do_repartition_menu_option,'enable','off')\n else\n if handles.parameters.optimization.crossval.repartition \n set(handles.do_repartition_menu_option,'checked','on','enable','on')\n end\n if strcmp(handles.parameters.optimization.crossval.method,'kfold')\n set(handles.crossval_menu_option_kfold,'checked','on')\n else\n error('Unknown crossvalidation option string.')\n end\n end\n \nfunction parent_cache_menu_Callback(hObject, eventdata, handles)\n yn = {'off','on'};\n set(handles.do_use_cache_menu,'Checked',yn{1+handles.parameters.do_use_cache_when_available})\n set(handles.retain_big_binary_file,'Checked',yn{1+handles.parameters.SavePermutationData})\n set(handles.retain_big_binary_pval_file,'Checked',yn{1+handles.parameters.SavePermutationPData})\n\n\nfunction output_summary_menu_Callback(hObject, eventdata, handles)\n yn = {'off','on'};\n set(handles.summary_create_summary,'checked',yn{1+handles.parameters.do_make_summary});\n set(handles.summary_narrative_summary,'checked',yn{1+handles.parameters.summary.narrative});\n set(handles.summary_svrbetamap,'checked',yn{1+handles.parameters.summary.beta_map});\n set(handles.summary_voxelwise_thresholded,'checked',yn{1+handles.parameters.summary.voxelwise_thresholded});\n set(handles.summary_clusterwise_thresholded,'checked',yn{1+handles.parameters.summary.clusterwise_thresholded});\n set(handles.summary_cfwerdiagnostics,'checked',yn{1+handles.parameters.summary.cfwer_diagnostics});\n set(handles.model_variablediagnostics,'checked',yn{1+handles.parameters.summary.variable_diagnostics});\n set(handles.summary_clusterstability,'checked',yn{1+handles.parameters.summary.cluster_stability});\n set(handles.summary_parameterassessment,'checked',yn{1+handles.parameters.summary.parameter_assessment});\n set(handles.summary_paramoptimization,'checked',yn{1+handles.parameters.summary.hyperparameter_optimization_record});\n set(handles.summary_lesionoverlap,'checked',yn{1+handles.parameters.summary.lesion_overlap});\n set(handles.summary_prediction_menu,'checked',yn{1+handles.parameters.summary.predictions});\n if handles.parameters.do_make_summary\n set(get(hObject,'children'),'enable','on')\n else\n set(get(hObject,'children'),'enable','off')\n set(handles.summary_create_summary,'enable','on')\n end\n disabled_objs = [handles.summary_paramoptimization handles.summary_prediction_menu];\n set(disabled_objs,'checked','off','enable','off') % since this is disabled in this first release \n \n\nfunction requirements_menu_Callback(hObject, eventdata, handles)\n%set(get(handles.requirements_menu,'children'),'checked',false)\nset(handles.spm12_installed_menu,'checked',myif(handles.details.spm,'on','off')) % this will not specifically detect spm12 though!\nset(handles.libsvm_installed_menu,'checked',myif(handles.details.libsvm,'on','off'))\nset(handles.parcomp_toolbox_installed_menu,'checked',myif(handles.details.can_parallelize,'on','off'))\nset(handles.stats_toolbox_installed_menu,'checked',myif(handles.details.stats_toolbox,'on','off'))\nset(handles.matlab_version_installed_menu,'checked','on') % what's the requirement?\nset(get(handles.requirements_menu,'children'),'enable','off')\n\nfunction beta_options_menu_Callback(hObject, eventdata, handles)\nset(handles.ica_lesion_decompose_option,'checked',myif(handles.parameters.beta.do_ica_on_lesiondata,'on','off'))\n\nfunction crossvalidate_map_parent_menu_Callback(hObject, eventdata, handles)\n set(get(hObject,'children'),'checked','off')\n% parameters.crossval.do_crossval = false; % by default do not do crossvalidated output...\n% parameters.crossval.method = 'kfold';\n% parameters.crossval.nfolds = 5;\n% parameters.crossval.nfolds_default = parameters.crossval.nfolds;\n set(handles.kfold_map_crossvalidation,'label',['K-Fold: ' num2str(handles.parameters.crossval.nfolds) ' folds' myif(handles.parameters.optimization.crossval.nfolds == handles.parameters.crossval.nfolds_default,' (default)','')])\n if ~handles.parameters.crossval.do_crossval\n set(handles.no_map_crossvalidation,'checked','on')\n %set(handles.do_repartition_menu_option,'enable','off')\n else\n% if handles.parameters.optimization.crossval.repartition \n% set(handles.do_repartition_menu_option,'checked','on','enable','on')\n% end\n if strcmp(handles.parameters.crossval.method,'kfold')\n set(handles.kfold_map_crossvalidation,'checked','on')\n else\n error('Unknown crossvalidation option string.')\n end\n end\n\nfunction no_map_crossvalidation_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\n\nfunction kfold_map_crossvalidation_Callback(hObject, eventdata, handles)\n handles = UpdateCurrentAnalysis(handles,hObject);\n"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "lm2table.m", "ext": ".m", "path": "svrlsmgui-master/functions/lm2table.m", "size": 6711, "source_encoding": "utf_8", "md5": "91866ec8af0be9264d12a99b61a74344", "text": "function html = lm2table(mdl,caption)\n\n%% Pretty css ...\n% table { \n% color: #333;\n% font-family: Helvetica, Arial, sans-serif;\n% width: 640px;\n% /* Table reset stuff */\n% border-collapse: collapse; border-spacing: 0; \n% }\n% \t\t\n% td, th { border: 0 none; height: 30px; }\n% \t\t\t\n% th {\n% /* Gradient Background */\n% \tbackground: linear-gradient(#333 0%,#444 100%);\n% \tcolor: #FFF; font-weight: bold;\n% \theight: 40px;\n% }\n% \t\t\n% td { background: #FAFAFA; text-align: center; }\n% \n% /* Zebra Stripe Rows */\n% \t\t\n% tr:nth-child(even) td { background: #EEE; } \n% tr:nth-child(odd) td { background: #FDFDFD; }\n% \n% /* First-child blank cells! */\n% tr td:first-child, tr th:first-child { \n% \tbackground: none; \n% \tfont-style: italic;\n% \tfont-weight: bold;\n% \tfont-size: 14px;\n% \ttext-align: right;\n% \tpadding-right: 10px;\n% \twidth: 80px; \n% }\n% \n% /* Add border-radius to specific cells! */\n% tr:first-child th:nth-child(2) { \n% border-radius: 5px 0 0 0; \n% } \n% \n% tr:first-child th:last-child { \n% border-radius: 0 5px 0 0; \n% }\n% \n% \n\n% f=figure;a=axes(f);\n% mdl.plot('parent',a)\n\n% can we pass a model title in the model object?\n% the goal here is to imitate something like Mdl.display in html format...\n\nhtml = createheaders({'Term','Estimate','SE','T Stat','P Value'});\nhtml = add_coefficient_data(html,mdl);\nhtml = add_gen_lm_info(html,mdl);\n\nhtml = wrap_w_table_html(html,caption);% finish this off...\n\nfunction rout = nice_r(rho) \n rout = strrep(sprintf('r = %.2f', rho),'0.','.'); % enforce no leading unnecessary 0 \n \nfunction rout = nice_r_nolet(rho) \n rout = strrep(sprintf('%.2f', rho),'0.','.'); % enforce no leading unnecessary 0 \n\nfunction pout= nice_p(pval) \n pout= myif(pval < .001,'P < .001',strrep(sprintf('P = %.2f', pval),' 0.',' .')); % enforce no leading unnecessary 0 \n\nfunction pout= nice_p_nolet(pval) % ie no p = or p < ...\n pout= strrep(myif(pval < .001,'<.001',sprintf('%.3f', pval)),'0.','.'); % enforce no leading unnecessary 0 \n\nfunction html = add_gen_lm_info(html,mdl)\n % Add in the num obs, err df, rmse, rsquared, adj rsquared, f--stat ...\n\n [fstat_vs_constant_pval,fstat_vs_constant_fval] = coefTest(mdl);\n [dw_P,dw_DW] = mdl.dwtest;\n \n % new rows to add in this cell array...\n rows = {add_col(5,'',sprintf('Number of observation: %d, Error degrees freedom: %d',mdl.NumObservations,mdl.DFE)), ...\n add_col(5,'',sprintf('Root Mean Square Error: %0.2f',mdl.RMSE)), ...\n add_col(5,'',sprintf('R²: %s, Adjusted R²: %s',nice_r_nolet(mdl.Rsquared.Ordinary),nice_r_nolet(mdl.Rsquared.Adjusted))), ...\n add_col(5,'',sprintf('F-statistic vs. constant model: %0.2f, %s',fstat_vs_constant_fval,nice_p(fstat_vs_constant_pval))), ...\n add_col(5,'',sprintf('Durbin-Watson test for corr. resids, DW = %0.2f, %s',dw_DW,nice_p(dw_P)))};\n \n for r = 1 : numel(rows) % go through and append each...\n newrow = rows{r};\n %newrow = ['' newrow ''];\n html = [html wrap_w_row_html(newrow)]; % add the row wrapper.\n end\n \n % Add in the durbin watson test - info from http://www.statisticshowto.com/durbin-watson-test-coefficient/\n % The Hypotheses for the Durbin Watson test are:\n % H0 = no first order autocorrelation.\n % H1 = first order correlation exists.\n % (For a first order correlation, the lag is one time unit).\n %\n % Assumptions are:\n % That the errors are normally distributed with a mean of 0.\n % The errors are stationary.\n % \n % The Durbin Watson test reports a test statistic, with a value from 0 to 4, where:\n % \n % 2 is no autocorrelation.\n % 0 to <2 is positive autocorrelation (common in time series data).\n % >2 to 4 is negative autocorrelation (less common in time series data).\n\n\nfunction html = add_coefficient_data(html,mdl)\n ncoeffs = numel(mdl.CoefficientNames);\n for c = 1 : ncoeffs\n newrow = [];\n newrow = add_col(1,newrow,mdl.CoefficientNames{c}); % Coefficient name\n newrow = add_col(1,newrow,mdl.Coefficients.Estimate(c)); % Estimate\n newrow = add_col(1,newrow,mdl.Coefficients.SE(c)); % SE\n newrow = add_col(1,newrow,mdl.Coefficients.tStat(c)); % tStat\n newrow = add_col(1,newrow,nice_p_nolet(mdl.Coefficients.pValue(c))); % pValue\n html = [html wrap_w_row_html(newrow)]; % add the row wrapper.\n end\n\nfunction rowdat = add_col(span,rowdat,newval)\n if span > 1 % e.g., %colspan=\"2\"\n spanstring = [' colspan=\"' num2str(span) '\"'];\n else\n spanstring ='';\n end\n \n switch class(newval)\n case 'double'\n htmladd = sprintf('%0.3f',spanstring,newval); % insert span here as necessary\n case 'char'\n htmladd = sprintf('%s',spanstring,newval); % insert span here as necessary\n otherwise\n error('unknown data class')\n end\n rowdat = [rowdat htmladd]; % concat and return\n\n% {'(Intercept)'} {'x1'} {'x2'} {'x3'} {'x4'} {'x5'}\n%mdl.anova\n% SumSq DF MeanSq F pValue \n% ______ __ ______ ______ __________\n% \n% x1 116.77 1 116.77 108.57 2.3674e-17\n% x2 490.59 1 490.59 456.14 7.7393e-38\n% x3 728.86 1 728.86 677.67 9.3215e-45\n% x4 1189 1 1189 1105.5 9.0239e-54\n% x5 1832.2 1 1832.2 1703.5 4.9317e-62\n% Error 101.1 94 1.0755 \n\n% addTerms dwtest plotEffects random \n% anova feval plotInteraction removeTerms \n% coefCI plot plotPartialDependence step \n% coefTest plotAdded plotResiduals \n% compact plotAdjustedResponse plotSlice \n% disp plotDiagnostics predict \n\nfunction html = createheaders(headers)\n html = [];\n for h = 1 : numel(headers)\n curheader = headers{h}; % {'Coefficient','Estimate','SE','tStat','pValue'};\n html = [html '' curheader ''];\n end\n html = wrap_w_row_html(html);\n\nfunction wrapped = wrap_w_row_html(html)\n wrapped = [newline '' newline html newline ''];\n\nfunction wrapped = wrap_w_table_html(html,caption)\n cap = [newline '' caption '' newline];\n wrapped = ['
' cap html '
'];"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "step2_parallel.m", "ext": ".m", "path": "svrlsmgui-master/functions/step2_parallel.m", "size": 7925, "source_encoding": "utf_8", "md5": "122e2f4b9e8fd73099f44977fe49aaaa", "text": "function [parameters,variables,thresholds] = step2_parallel(handles,parameters,variables,thresholds,all_perm_data)\n handles = UpdateProgress(handles,'Sorting null betas for each lesioned voxel in the dataset (parallelized).',1);\n L = length(variables.m_idx);\n tail = parameters.tailshort; % so not a broadcast variable.\n\n ori_beta_vals = variables.ori_beta_vals; % for parfor...\n do_CFWER = parameters.do_CFWER; % for parfor...\n total_cols = length(variables.m_idx); % note this must be m_idx since the data in our giant file is stored in frames of length m_idx not length l_idx.\n nperms = parameters.PermNumVoxelwise;\n outpath = variables.output_folder.clusterwise;\n\n pos_thresh_index = thresholds.pos_thresh_index;\n neg_thresh_index = thresholds.neg_thresh_index;\n onetail_thresh_index = thresholds.onetail_cutoff_index; % for use with compare_real_beta() \n \n % two_tailed_thresh_index = thresholds.two_tailed_thresh_index;\n % two_tailed_thresh_index_neg = thresholds.two_tailed_thresh_index_neg;\n\n %% Begin parfeval code \n batch_job_size = 500; % this is going to be optimal for different systems/#cores/jobs\n njobs = ceil(total_cols/batch_job_size); % gotta round up to capture all indices\n\n %% Schedule the jobs...\n p = gcp(); % get current parallel pool\n for j = 1 : njobs\n this_job_start_index = ((j-1)*batch_job_size) + 1;\n this_job_end_index = min(this_job_start_index + batch_job_size-1,total_cols); % need min so we don't go past valid indices\n job_indices = this_job_start_index:this_job_end_index;\n f(j) = parfeval(p,@parallel_step2_batch_fcn,2,job_indices,all_perm_data,total_cols,tail,ori_beta_vals,onetail_thresh_index,L,nperms,do_CFWER,outpath,neg_thresh_index,pos_thresh_index);\n end\n \n alphas = cell(1,njobs); %reserve space - note we want to accumulate in a row here\n betamapcutoff = cell(1,njobs); %reserve space - note we want to accumulate in a row here\n \n %% Monitor job progress...\n msg = 'Sorting null betas for each lesioned voxel in the dataset (parallelized).';\n svrlsm_waitbar(parameters.waitbar,0,msg) % update waitbar progress...\n for j = 1 : njobs\n check_for_interrupt(parameters) % allow user to interrupt\n [idx, jobalphas,jobbetamapcutoffs] = fetchNext(f);\n alphas{idx} = jobalphas; % combine these cells afterward\n betamapcutoff{idx} = jobbetamapcutoffs; % combine these cells afterward\n svrlsm_waitbar(parameters.waitbar,j/njobs) % update waitbar progress...\n end\n\n alphas = cell2mat(alphas); % combine afterward\n betamapcutoff = cell2mat(betamapcutoff); % combine afterward\n\n %% Now compute beta cutoff values and a pvalue map for the observed betas.\n % ...we do this now since we can't index into fields of the 'thresholds'variable in a parfor loop\n switch tail\n case 'pos' % pos - high scores bad\n thresholds.one_tail_pos_alphas = alphas;\n thresholds.pos_beta_map_cutoff = betamapcutoff;\n case 'neg' % neg - high scores good\n thresholds.one_tail_neg_alphas = alphas;\n thresholds.neg_beta_map_cutoff = betamapcutoff;\n% case 'two' % two-tailed\n% thresholds.two_tailed_beta_map_cutoff_pos =two_tailed_beta_map_cutoff_pos;\n% thresholds.two_tailed_beta_map_cutoff_neg =two_tailed_beta_map_cutoff_neg;\n% thresholds.twotails_alphas = twotails_alphas;\n end\n \n %% Now, since we're parallelized, like in step 1, get all those individual files into one big file that we can memmap\n if do_CFWER \n svrlsm_waitbar(parameters.waitbar,0,'Consolidating null p-map files...');\n parameters.outfname_big_p = fullfile(variables.output_folder.clusterwise,['pmu_p_maps_N_' num2str(total_cols) '.bin']);\n fileID = fopen(parameters.outfname_big_p,'w');\n % this data is output such that each numel(variables.m_idx) contiguous sequential values refer to a voxel across all permutations: [P1V1, P2V1, P3V1, P4V1, ..., npermutations]\n for col = 1 : total_cols % can't parallelize this since we need order to be right.\n if ~mod(500,col) % to reduce num of calls...\n check_for_interrupt(parameters)\n svrlsm_waitbar(parameters.waitbar,col/total_cols);\n end\n curpermfilepath = fullfile(outpath,['pmu_p_map_' num2str(col) '_of_' num2str(total_cols) '.bin']);\n cur_perm_data = memmapfile(curpermfilepath,'Format','single');\n fwrite(fileID, cur_perm_data.Data,'single');\n clear cur_perm_data; % remove memmap from memory.\n delete(curpermfilepath); % delete it since we don't want the data hanging around...\n end\n fclose(fileID); % close big file\n svrlsm_waitbar(parameters.waitbar,0,'');\n end\n \n%% For each voxel, calculate the beta cutoff and p-value based on our permutation data - also, convert to pvalue volumes if CFWER is requested.\nfunction [alphas,betamapcutoffs] = parallel_step2_batch_fcn(this_job_cols,all_perm_data,total_cols,tail,ori_beta_vals,onetail_thresh_index,L,nperms,do_CFWER,outpath,neg_thresh_index,pos_thresh_index)\n alphas = nan(1,numel(this_job_cols)); % pre-allocate spac\n betamapcutoffs = nan(1,numel(this_job_cols)); % pre-allocate spac\n for jobcolind = 1:numel(this_job_cols) % this is for each voxel in the brain, cutting across permutations\n col = this_job_cols(jobcolind);\n curcol = extractSlice(all_perm_data,col,L);\n observed_beta = ori_beta_vals(col); % original observed beta value.\n curcol_sorted = sort(curcol); % Smallest values at the left/top\n \n %% Calculate P values for the single *observed beta map* relative to the null permutation beta volumes.\n switch tail\n case {'pos','neg'}\n [alphas(jobcolind),betamapcutoffs(jobcolind)] = compare_real_beta(observed_beta,curcol,tail,onetail_thresh_index); % we can do both tails without the switch as long as it's one-tailed.\n% case 'pos' % high scores bad\n% % 'ascend' is the default assort behavior.\n% alphas(jobcolind) = sum(observed_beta < curcol_sorted)/nperms;\n% %[alphas(jobcolind),betamapcutoffs(jobcolind)] = compare_real_beta(observed_beta,curcol,tail,onetail_thresh_index);\n% betamapcutoffs(jobcolind) = curcol_sorted(pos_thresh_index); % so the 9500th at p of 0.05 on 10,000 permutations\n% case 'neg' % high scores good\n% alphas(jobcolind) = sum(observed_beta > curcol_sorted)/nperms;\n% %[alphas(jobcolind),betamapcutoffs(jobcolind)] = compare_real_beta(observed_beta,curcol,tail,onetail_thresh_index);\n% betamapcutoffs(jobcolind) = curcol_sorted(neg_thresh_index); % so the 500th at p of 0.05 on 10,000 permutations\n case 'two' % two-tailed...\n warning('Check that these tails are right after code refactor') % ad 2/14/18\n% % two_tailed_beta_map_cutoff_pos(col) = curcol_sorted(two_tailed_thresh_index); % 250...\n% % two_tailed_beta_map_cutoff_neg(col) = curcol_sorted(two_tailed_thresh_index_neg); % 9750...\n% % twotails_alphas(col) = sum(abs(observed_beta) > abs(curcol_sorted))/numel(curcol_sorted); % percent of values observed_beta is greater than.\n end\n \n % Save this permutation as p values.\n if do_CFWER % then we need to make a billion files and combine them like in parallelized step 1...\n p_vec = betas2pvals(curcol,tail); % each of these files corresponds to the p values for all the permutations of a single voxel\n fileID = fopen(fullfile(outpath,['pmu_p_map_' num2str(col) '_of_' num2str(total_cols) '.bin']),'w');\n fwrite(fileID, p_vec,'single');\n fclose(fileID);\n end\n end"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "generic_hyperopts.m", "ext": ".m", "path": "svrlsmgui-master/functions/generic_hyperopts.m", "size": 4224, "source_encoding": "utf_8", "md5": "cb65bf7a69325a21821ec0c7ce414ec8", "text": "function results = generic_hyperopts(parameters,variables)\n % This attempts to optimize using matlab's default hyperparameter optimization options ... \n % because it doesn't use bayesopt, it cannot update the progress bar (not output function)\n \n % For clarity...\n lesiondata = variables.lesion_dat;\n behavdata = variables.one_score;\n\n %% Configure hyperparam options\n params = hyperparameters('fitrsvm',lesiondata,behavdata); \n \n % Turn optimize off for all hyperparams by default\n for N = 1:numel(params)\n params(N).Optimize = false;\n end\n \n % Then turn them on as necessary, and set their ranges from the user analysis config\n if parameters.optimization.params_to_optimize.sigma\n params(strcmp({params.Name},'KernelScale')).Optimize = true;\n params(strcmp({params.Name},'KernelScale')).Range = [parameters.optimization.params_to_optimize.sigma_range];\n end\n \n if parameters.optimization.params_to_optimize.cost\n params(strcmp({params.Name},'BoxConstraint')).Optimize = true;\n params(strcmp({params.Name},'BoxConstraint')).Range = [parameters.optimization.params_to_optimize.cost_range];\n end\n \n if parameters.optimization.params_to_optimize.epsilon\n params(strcmp({params.Name},'Epsilon')).Optimize = true;\n params(strcmp({params.Name},'Epsilon')).Range = [parameters.optimization.params_to_optimize.epsilon_range];\n end\n \n if parameters.optimization.params_to_optimize.standardize\n params(strcmp({params.Name},'Standardize')).Optimize = true;\n end\n \n optimizeropts = resolveoptimizeropts(parameters);\n \n hyperoptoptions = struct('AcquisitionFunctionName','expected-improvement-plus', optimizeropts{:});\n% 'Optimizer', resolveoptimizer(parameters)\n% 'MaxObjectiveEvaluations',parameters.optimization.iterations, ...\n% 'UseParallel',parameters.parallelize, ...\n% 'Repartition',parameters.optimization.crossval.repartition, ...\n% 'KFold',parameters.optimization.crossval.nfolds, ... %'PlotFcn',[], ...\n% 'Verbose',myif(parameters.optimization.verbose_during_optimization,2,0));\n \n % 'OutputFcn',@optim_outputfun); % verbose is either 0 or 2...\n \n% disp('OptimizeHyperparameters')\n% params\n% disp('HyperparameterOptimizationOptions')\n% hyperoptoptions\n Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf', 'OptimizeHyperparameters',params, 'HyperparameterOptimizationOptions', hyperoptoptions);\n\n results = Mdl.HyperparameterOptimizationResults;\n% \n% assignin('base','results',results)\n% assignin('base','Mdl',Mdl)\n% \n% \nfunction optimizeropts = resolveoptimizeropts(parameters)\n\n switch parameters.optimization.search_strategy \n case 'Bayes Optimization'\n optimchoice = 'bayesopt';\n case 'Grid Search' \n optimchoice = 'gridsearch';\n case 'Random Search'\n optimchoice = 'randomsearch';\n end\n \n% parameters.optimization.crossval.do_crossval = true\n% warning('forcing repartinioning on for testing')\n \n repartitionopt = myif(parameters.optimization.crossval.do_crossval, ...\n {'Repartition',parameters.optimization.crossval.repartition},{});\n \n itersornumdivsstr = myif(strcmp(optimchoice,'gridsearch'),'NumGridDivisions','MaxObjectiveEvaluations'); % do we need grid divs or do we need max objective evaluations...?\n itersornumdivs = myif(strcmp(optimchoice,'gridsearch'),parameters.optimization.grid_divisions,parameters.optimization.iterations);\n parameters.optimization.crossval.do_crossval = true;\n nfolds = myif(parameters.optimization.crossval.do_crossval,parameters.optimization.crossval.nfolds,1);\n if nfolds == 1 % we'll throw an error... switch back to 5.\n nfolds = 5;\n warning('Crossvalidation set to on for hyperparam opt.')\n end\n \n optimizeropts = {'Optimizer', optimchoice, ...\n itersornumdivsstr,itersornumdivs, ...\n 'UseParallel',parameters.parallelize, ...\n repartitionopt{:}, ...\n 'KFold', nfolds, ...\n 'Verbose',myif(parameters.optimization.verbose_during_optimization,2,0), ...\n 'ShowPlots',false};\n\n %optimizeropts{:}"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "svrlsm_prepare_ica.m", "ext": ".m", "path": "svrlsmgui-master/functions/svrlsm_prepare_ica.m", "size": 7989, "source_encoding": "utf_8", "md5": "1731883379f898e0e583d4ca6325a72e", "text": "function [parameters,variables] = svrlsm_prepare_ica(parameters,variables)\n% We'll decompose the lesion data into ICs... and use percent damage to those ROIs as the lesion data values...\n\n % Reread in each subject in the analysis, the mask, and make concatenated ICA file for fsl\nfor ni= 1 : variables.SubNum % numel(variables.SubjectID)\n fname = [variables.SubjectID{ni}, '.nii'];\n fullfname = fullfile(parameters.lesion_img_folder, fname);\n svrlsm_waitbar(parameters.waitbar,ni / length(variables.SubjectID),sprintf('Rereading lesion file %s...',fname));\n %vo = spm_vol(fullfname); % The true voxel intensities of the jth image are given by: val*V.pinfo(1,j) + V.pinfo(2,j)\n %tmp = spm_read_vols(vo);\n [hdr,tmp]=read_nifti(fullfname); % cause i dunn how to output 4d files from the spm's header.\n tmp(isnan(tmp)) = 0; % Denan the image.\n tmp = tmp > 0; % Binarize\n Ldat(:,:,:,ni) = uint8(tmp);\n check_for_interrupt(parameters)\nend\n\n% Make the ica output directory..\nmkdir(variables.output_folder.ica)\n\n% Write a 3D mask of ANY lesions!\nfname = fullfile(variables.output_folder.ica,'3DAnyLesionMask.nii');\nwrite_nifti(hdr,double(sum(Ldat,4)>0),fname); % double so it's not booleans.\nvariables.files_created.ica_3D_any_lesion_mask = fname; % so we know we made this file.\n\n% Write out the 4D concatted lesions we'll need for FSL to run melodic...\nhdr.dim(1) = 4;\nhdr.dim(5) = variables.SubNum;\nfname = fullfile(variables.output_folder.ica,'4DConcattedLesionMasks.nii');\nwrite_nifti(hdr,Ldat,fname);\nvariables.files_created.ica_4d_all_lesions = fname; % so we know we made this file.\n\nvariables.output_folder.ica_icadata = fullfile(variables.output_folder.ica,'data.ica');\n\nsetup_ica % add the right stuff to the path...\n\nwd=pwd;\n\ncd(variables.output_folder.ica)\n\n[~,cattedfroot]=fileparts(variables.files_created.ica_4d_all_lesions); % ica_concat_file); % -d or --dim should be the number of components, but adding it to the end of the call just causes it to fail and come back...\n[~,outmaskfroot]=fileparts(variables.files_created.ica_3D_any_lesion_mask);\n\n%% Compute the ICA decomposition...!\nncomps = 35; % variables.SubNum - 5; % cause nsubs is too many, and nsubs-1 is too many too. will a different \"method\" allow more components to be deflated?\nunix(sprintf(['melodic -i \"' cattedfroot '\" -v -d ' num2str(ncomps) ' -m \"' outmaskfroot '\" -a concat --Oall --nobet --report']));\n\n% Write out the component overlaps in 3D...\n[max_prob_ic_map_inds,max_prob_ic_map_vals] = write_max_ics(variables.output_folder.ica);\nvariables.files_created.ica_max_prob_ic_map_inds = max_prob_ic_map_inds;\nvariables.files_created.ica_max_prob_ic_map_vals = max_prob_ic_map_vals;\n\ncd(wd); % go back to wd...\n\n% now build our ica components - ica has already been run at this point.\n%[~,cattedfroot]=fileparts(ica_concat_file);\n%icadir = [cattedfroot '.ica'];\n\nbuildComponentType = 2;\ndisp(['Building ICA component type ' num2str(buildComponentType) '.'])\nswitch buildComponentType\n case 1\n %% read in the component loadings for each subject\n% reports = dir(fullfile(ica_path,icadir,'report','t*.txt'));\n% componentData=[];\n% for c = 1 : numel(reports)\n% tmp =readtable(fullfile(reports(c).folder,reports(c).name));\n% componentData(:,c) = tmp.Var1; % first column...\n% end\n case 2\n [~,alllesiondata] = read_nifti(variables.files_created.ica_4d_all_lesions); % ica_concat_file); % check for percent overlap with this...\n \n %% or write_max_ics() output ...\n %[~,componentimg]=read_nifti(fullfile(pwd,icadir,'stats','maxprob_ic_map_inds.nii'));\n %[~,componentimg]=read_nifti('maxprob_ic_map_inds.nii');\n \n [~,componentimg]=read_nifti(variables.files_created.ica_max_prob_ic_map_inds); % 'maxprob_ic_map_inds.nii');\n \n for s = 1:size(alllesiondata,4)\n curlesion = alllesiondata(:,:,:,s);\n for component = 1 : max(componentimg(:))\n curcomponentmask = componentimg==component;\n curcomponent_nvox = sum(curcomponentmask(:));\n curlesion_overlap_w_curcomp = curlesion&curcomponentmask;\n n_curlesion_overlap_w_curcomp = sum(curlesion_overlap_w_curcomp(:));\n tmp = n_curlesion_overlap_w_curcomp / curcomponent_nvox;\n% if isnan(tmp)\n% variables.SubjectID{s}\n% component\n% n_curlesion_overlap_w_curcomp \n% curcomponent_nvox\n% disp('---')\n% end\n componentData(s,component) = tmp; %#ok\n end\n end\n case 3 % multiply out the probabilities...\n% [~,alllesiondata] = read_nifti(ica_concat_file); % check for percent overlap with this...\n% componentData=[];\n% reports = dir(fullfile(ica_path,icadir,'report','t*.txt'));\n% ncomps = numel(reports);\n% for c = 1 : ncomps\n% [~,curcomponent] = read_nifti(fullfile(ica_path,icadir,'stats',['probmap_' num2str(c) '.nii']));\n% curcomponent_maxprob = sum(curcomponent(:)); % let the probabilities sum up without binarizing.\n% \n% for s = 1 : size(alllesiondata,4)\n% curlesion = alllesiondata(:,:,:,s);\n% multoutprob = curcomponent(curlesion>0); % just add up the probability values...\n% componentData(s,c) = 100 * (sum(multoutprob(:)) / curcomponent_maxprob); % percent damage to this component prob map....\n% end\n% end\nend\n\n % now that we've collected our component data, replace the lesion data matrix...\n variables.lesion_dat_voxelwise = variables.lesion_dat;\n \n variables.lesion_dat = componentData; % these are percent damage per component!\n variables.l_idx_voxelwise = variables.l_idx;\n variables.m_idx_voxelwise = variables.m_idx;\n \n variables.l_idx = variables.l_idx_voxelwise(1:ncomps); % We'll put these back later!\n variables.m_idx = variables.l_idx_voxelwise(1:ncomps); % We'll put these back later!\n \n %assignin('base','variables',variables)\n %assignin('base','parameters',parameters)\n\n % size(componentData)\n % tmp = readtable(lesion_text_file);\n % data.lesion_vol = tmp.lesion_vol;\n \nfunction [max_prob_ic_map_inds,max_prob_ic_map_vals] = write_max_ics(ica_path)\n disp('Writing max IC maps')\n %wd = '/home/crl/Documents/Projects/svrica/concat_lesions_N=48.ica/stats';\n \n wd = fullfile(ica_path,'4DConcattedLesionMasks.ica','stats');\n cd(wd); % gotta go there cause the spaces and stuff in the folder names...\n \n files=dir('prob*.nii');\n \n if numel(files) < 10 % probably need to unzip them...\n unix('gunzip *.nii.gz')\n files=dir('prob*.nii');\n end\n \n for f = 1 : numel(files)\n curf = fullfile(files(f).folder,['probmap_' num2str(f) '.nii']);\n [hdr,img]=read_nifti(curf);\n allimgs(:,:,:,f) = img; %#ok\n end\n \n outimg = zeros(size(img));\n outimg2 = zeros(size(img));\n \n for x = 1 : size(allimgs,1)\n for y = 1 : size(allimgs,2)\n for z = 1 : size(allimgs,3)\n curvec = squeeze(allimgs(x,y,z,:));\n if any(curvec)\n [val,ind] = max(curvec);\n outimg(x,y,z) = ind;\n outimg2(x,y,z) = val;\n end\n end\n end\n end\n max_prob_ic_map_inds = fullfile(ica_path,'maxprob_ic_map_inds.nii');\n write_nifti(hdr,outimg,max_prob_ic_map_inds)\n max_prob_ic_map_vals = fullfile(ica_path,'maxprob_ic_map_vals.nii');\n write_nifti(hdr,outimg2,max_prob_ic_map_vals)\n\nfunction setup_ica\n setenv('PATH', [getenv('PATH') ':/usr/share/fsl/5.0/bin:/usr/lib/fsl/5.0']);\n setenv('LD_LIBRARY_PATH',[getenv('LD_LIBRARY_PATH') ':/usr/lib/fsl/5.0/'])\n setenv('FSLOUTPUTTYPE','NIFTI_GZ')\n setenv('FSLDIR','/usr/share/fsl/5.0') "} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "step1_notparallel_old.m", "ext": ".m", "path": "svrlsmgui-master/functions/step1_notparallel_old.m", "size": 5199, "source_encoding": "utf_8", "md5": "ab0fe65d23076e5b40c6aac94ecc66fd", "text": "function [handles,parameters] = step1_notparallel(handles,parameters,variables)\n % This is where we'll save our GBs of permutation data output...\n parameters.outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);\n \n %% Try to use cache to skip this step by relying on cached permutation data\n if can_skip_generating_beta_perms(parameters,variables)\n warndlg('Relying on cached data not fully supported/reliable yet.')\n error('This is not supported')\n handles = UpdateProgress(handles,'Using cached beta map permutation data...',1);\n return\n else\n handles = UpdateProgress(handles,'Computing beta map permutations (not parallelized)...',1);\n svrlsm_waitbar(parameters.waitbar,0,'Computing beta permutations...');\n end\n \n %% If we got here then we need to generate the permutation data\n \n fileID = fopen(parameters.outfname_big,'w');\n \n for PermIdx=1:parameters.PermNumVoxelwise\n check_for_interrupt(parameters)\n\n % random permute subjects order for this permutation.\n trial_score = variables.one_score(randperm(length(variables.one_score)));\n\n % Which package to use to compute SVM solution\n if parameters.useLibSVM % then use libSVM ...\n% box = myif(parameters.optimization.do_optimize & parameters.optimization.params_to_optimize.cost, parameters.optimization.best.cost, parameters.cost);\n% gamma = myif(parameters.optimization.do_optimize & parameters.optimization.params_to_optimize.sigma, sigma2gamma(parameters.optimization.best.sigma), sigma2gamma(parameters.sigma)); % now derive from sigma...\n% epsilon = myif(parameters.optimization.do_optimize & parameters.optimization.params_to_optimize.epsilon, parameters.optimization.best.epsilon, parameters.epsilon);\n% libsvmstring = get_libsvm_spec(box,gamma,epsilon);\n hyperparms = hyperparmstruct(parameters);\n libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % Standardization is already applied.\n m = svmtrain(trial_score,sparse(variables.lesion_dat),libsvmstring); %#ok\n else % otherwise use MATLAB...\n if PermIdx == 1\n variables.orig_one_score = variables.one_score; % store this.\n end\n \n variables.one_score = trial_score; % this is so we can use the same ComputeMatlabSVRLSM function :)\n [m,~,~] = ComputeMatlabSVRLSM(parameters,variables); % ComputeMatlabSVRLSM will utilize our optimized parameters if available...\n \n if PermIdx == parameters.PermNumVoxelwise % put it back after we've done all permutations...\n variables.one_score = variables.orig_one_score; % restore this.\n end\n end\n\n % Compute the beta map\n% if parameters.useLibSVM\n% alpha = m.sv_coef';\n% SVs = m.SVs;\n% else % MATLAB's version.\n% alpha = m.Alpha';\n% SVs = m.SupportVectors;\n% end\n% \n % Compute the beta map\n alpha = m.(myif(parameters.useLibSVM,'sv_coef','Alpha'))'; % note dynamic field reference\n SVs = m.(myif(parameters.useLibSVM,'SVs','SupportVectors')); % note dynamic field reference\n \n pmu_beta_map = variables.beta_scale * alpha * SVs;\n\n tmp_map = zeros(variables.vo.dim(1:3)); % make a zeros template.... \n tmp_map(variables.l_idx) = pmu_beta_map;\n pmu_beta_map = tmp_map(variables.m_idx).';\n\n % Save this permutation to our single giant file.\n fwrite(fileID, pmu_beta_map,'single'); \n\n if ~mod(PermIdx,20) % update every 20 indices... \n % Display progress.\n% elapsed_time = toc;\n% remain_time = round(elapsed_time * (parameters.PermNumVoxelwise - PermIdx)/(PermIdx));\n% remain_time_h = floor(remain_time/3600);\n% remain_time_m = floor((remain_time - remain_time_h*3600)/60);\n% remain_time_s = floor(remain_time - remain_time_h*3600 - remain_time_m*60);\n% prompt_str = sprintf('Permutation %d/%d: Est. remaining time: %dh %dh %ds', PermIdx, parameters.PermNumVoxelwise, remain_time_h, remain_time_m,remain_time_s);\n prompt_str = get_step1_prog_string(PermIdx,parameters);\n svrlsm_waitbar(parameters.waitbar,PermIdx/parameters.PermNumVoxelwise,prompt_str);\n end\n end\n svrlsm_waitbar(parameters.waitbar,0,''); % clear\n fclose(fileID); % close the pmu data output file.\n\nfunction prompt_str = get_step1_prog_string(PermIdx,parameters)\n elapsed_time = toc;\n remain_time = round(elapsed_time * (parameters.PermNumVoxelwise - PermIdx)/(PermIdx));\n remain_time_h = floor(remain_time/3600);\n remain_time_m = floor((remain_time - remain_time_h*3600)/60);\n remain_time_s = floor(remain_time - remain_time_h*3600 - remain_time_m*60);\n prompt_str = sprintf('Permutation %d/%d: Est. remaining time: %dh %dh %ds', PermIdx, parameters.PermNumVoxelwise, remain_time_h, remain_time_m,remain_time_s);"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "step1_notparallel.m", "ext": ".m", "path": "svrlsmgui-master/functions/step1_notparallel.m", "size": 5174, "source_encoding": "utf_8", "md5": "f2d672f41a6a70b48e3d7ed78b5b812a", "text": "function [handles,parameters] = step1_notparallel(handles,parameters,variables)\n % This is where we'll save our GBs of permutation data output...\n parameters.outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);\n \n %% Try to use cache to skip this step by relying on cached permutation data\n if can_skip_generating_beta_perms(parameters,variables)\n warndlg('Relying on cached data not fully supported/reliable yet. Aborting.')\n error('This is not supported')\n handles = UpdateProgress(handles,'Using cached beta map permutation data...',1);\n return\n else\n handles = UpdateProgress(handles,'Computing beta map permutations (not parallelized)...',1);\n svrlsm_waitbar(parameters.waitbar,0,['Computing beta permutations (' myif(parameters.method.mass_univariate,'mass univariate','multivariate') ')...']);\n end\n \n %% If we got here then we need to generate the permutation data\n fileID = fopen(parameters.outfname_big,'w');\n \n for PermIdx=1:parameters.PermNumVoxelwise\n % Random permute subjects order for this permutation.\n trial_score = variables.one_score(randperm(length(variables.one_score)));\n if parameters.method.mass_univariate % Estimate via mass-univariate\n pmu_beta_map = nan(size(variables.lesion_dat,2),1); % reserve space\n for vox = 1 : size(variables.lesion_dat,2)\n [Q, R] = qr(trial_score, 0); % use the householder transformations to compute the qr factorization of an n by p matrix x.\n y = double(variables.lesion_dat(:,vox));% / 10000; % why divide by 10,000?\n %betas(vox) = R \\ (Q' * y); % equivalent to fitlm's output: lm.Coefficients.Estimate\n pmu_beta_map(vox) = R \\ (Q' * y); % equivalent to fitlm's output: lm.Coefficients.Estimate\n end\n else % Estimate via multivariate svr\n % Which package to use to compute SVR solution\n if parameters.useLibSVM % then use libSVM\n hyperparms = hyperparmstruct(parameters);\n libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % Standardization is already applied.\n m = svmtrain(trial_score,sparse(variables.lesion_dat),libsvmstring); %#ok\n else % use MATLAB\n if PermIdx == 1, variables.orig_one_score = variables.one_score; end % store this\n variables.one_score = trial_score; % this is so we can use the same ComputeMatlabSVRLSM function :)\n [m,w,~] = ComputeMatlabSVRLSM(parameters,variables); % ComputeMatlabSVRLSM will utilize our optimized parameters if available...\n if PermIdx == parameters.PermNumVoxelwise, variables.one_score = variables.orig_one_score; end % restore this once we're done all our permutations\n end\n\n % Compute the beta map here (but only if we didn't already compute it already by necessity via crossvalidation)\n if ~parameters.crossval.do_crossval % conditional added to support crossvalidated betamap option in June 2019\n alpha = m.(myif(parameters.useLibSVM,'sv_coef','Alpha'))'; % note dynamic field reference\n SVs = m.(myif(parameters.useLibSVM,'SVs','SupportVectors')); % note dynamic field reference\n pmu_beta_map = variables.beta_scale * alpha * SVs;\n else % use pre-computed (and averaged) beta map(s) -- this should only be available with svr in matlab specifically (not mass univariate, and not libsvm right now)\n pmu_beta_map = w; % here contains an average of the crossvalidated fold models' beta values, so we don't have to scale or do anything here, it's already all done in the ComputeMatlabSVRLSM() function\n end\n end\n\n tmp_map = zeros(variables.vo.dim(1:3)); % make a zeros template.... \n tmp_map(variables.l_idx) = pmu_beta_map;\n pmu_beta_map = tmp_map(variables.m_idx).';\n\n % Save this permutation to our single giant file.\n fwrite(fileID, pmu_beta_map,'single'); \n\n check_for_interrupt(parameters)\n if ~mod(PermIdx,20) % update every 20 indices - Display progress.\n prompt_str = get_step1_prog_string(PermIdx,parameters);\n svrlsm_waitbar(parameters.waitbar,PermIdx/parameters.PermNumVoxelwise,prompt_str);\n end\n end\n svrlsm_waitbar(parameters.waitbar,0,''); % clear\n fclose(fileID); % close the pmu data output file.\n\n% The string we print saying the progress.\nfunction prompt_str = get_step1_prog_string(PermIdx,parameters)\n elapsed_time = toc;\n remain_time = round(elapsed_time * (parameters.PermNumVoxelwise - PermIdx)/(PermIdx));\n remain_time_h = floor(remain_time/3600);\n remain_time_m = floor((remain_time - remain_time_h*3600)/60);\n remain_time_s = floor(remain_time - remain_time_h*3600 - remain_time_m*60);\n prompt_str = sprintf('Permutation %d/%d: Est. remaining time: %dh %dm %ds', PermIdx, parameters.PermNumVoxelwise, remain_time_h, remain_time_m,remain_time_s);"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "build_and_write_pmaps.m", "ext": ".m", "path": "svrlsmgui-master/functions/build_and_write_pmaps.m", "size": 10054, "source_encoding": "utf_8", "md5": "a98d12f50beab6567543d822657e3661", "text": "function [thresholded,variables] = build_and_write_pmaps(options,parameters,variables,thresholds)\n switch parameters.tailshort % parameters.tails\n case 'pos' % options.hypodirection{1} % One-tailed positive tail... high scores BAD\n [thresholded,variables] = write_p_maps_pos_tail(parameters,variables,thresholds);\n case 'neg' % options.hypodirection{2} % One-tailed negative tail... high scores GOOD\n [thresholded,variables] = write_p_maps_neg_tail(parameters,variables,thresholds);\n case 'two' % options.hypodirection{3} % Both tails..\n [thresholded,variables] = write_p_maps_two_tailed(parameters,variables,thresholds);\n end\n\nfunction [thresholded,variables] = write_p_maps_pos_tail(parameters,variables,thresholds)\n if parameters.do_CFWER % note that the parameters struct isn't returned by this function so nothing changes outside this function scope\n parameters.voxelwise_p = variables.cfwerinfo.cfwer_single_pval_answer;\n end\n\n write_z = true;\n \n %% Create and write the un-inverted versions...\n thresholded.thresholded_pos = zeros(variables.vo.dim(1:3)); % make a zeros template....\n thresholded.thresholded_pos(variables.m_idx) = thresholds.one_tail_pos_alphas;\n \n % Write unthresholded P-map for the positive tail\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P map.nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);\n variables.files_created.unthresholded_pmap = variables.vo.fname;\n\n % % Calculate z map\n %zmap = p2z(thresholded.thresholded_pos); % note the call to p2z() here\n \n % calculate z map\n zmap = zeros(variables.vo.dim(1:3));\n \n if write_z \n zmap(variables.m_idx) = p2z(thresholds.one_tail_pos_alphas); % so we don't try to convert 0 values in the rest of the brain volume...\n\n % write out unthresholded positive Z map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded Z map.nii');\n svrlsmgui_write_vol(variables.vo, zmap);\n variables.files_created.unthresholded_zmap = variables.vo.fname;\n end\n \n % Now write out the thresholded P-map for the positive tail\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded P map.nii');\n zero_these_vox = thresholded.thresholded_pos > parameters.voxelwise_p;\n thresholded.thresholded_pos(zero_these_vox) = 0; % zero out voxels whose values are greater than p\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);\n variables.files_created.thresholded_pmap = variables.vo.fname;\n \n if write_z \n % write out thresholded positive Z map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded Z map.nii');\n zmap(zero_these_vox) = 0; % apply the mask we calculated like 20 lines ago\n svrlsmgui_write_vol(variables.vo, zmap);\n variables.files_created.thresholded_zmap = variables.vo.fname;\n end\n \n %% Create and write the inverted versions.\n thresholded.thresholded_pos = zeros(variables.vo.dim(1:3)); % make a zeros template....\n thresholded.thresholded_pos(variables.m_idx) = 1 - thresholds.one_tail_pos_alphas;\n\n % Write unthresholded P-map for the positive tail\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P map (inv).nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);\n variables.files_created.unthresholded_pmap_inv = variables.vo.fname;\n\n % Now write out the thresholded P-map for the positive tail\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded P map (inv).nii');\n thresholded.thresholded_pos(thresholded.thresholded_pos < (1-parameters.voxelwise_p)) = 0; % zero out sub-threshold p value voxels (note the 1-p)\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);\n variables.files_created.thresholded_pmap_inv = variables.vo.fname;\n\n\nfunction [thresholded,variables] = write_p_maps_neg_tail(parameters,variables,thresholds)\n if parameters.do_CFWER % note that the parameters struct isn't returned by this function so nothing changes outside this function scope\n parameters.voxelwise_p = variables.cfwerinfo.cfwer_single_pval_answer;\n end\n \n write_z = true;\n \n %% Create and write the non-inverted versions.\n thresholded.thresholded_neg = zeros(variables.vo.dim(1:3)); % make a zeros template.... \n thresholded.thresholded_neg(variables.m_idx) = thresholds.one_tail_neg_alphas;\n \n % write out unthresholded negative p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P map.nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);\n variables.files_created.unthresholded_pmap = variables.vo.fname;\n\n % calculate z map\n zmap = zeros(variables.vo.dim(1:3));\n \n if write_z \n zmap(variables.m_idx) = p2z(thresholds.one_tail_neg_alphas); % so we don't try to convert 0 values in the rest of the brain volume...\n\n % write out unthresholded negative Z map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded Z map.nii');\n svrlsmgui_write_vol(variables.vo, zmap);\n variables.files_created.unthresholded_zmap = variables.vo.fname;\n end\n \n % write out thresholded negative p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded P map.nii');\n zero_these_vox = thresholded.thresholded_neg > parameters.voxelwise_p;\n thresholded.thresholded_neg(zero_these_vox) = 0; % zero out voxels whose values are greater than p\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);\n variables.files_created.thresholded_pmap = variables.vo.fname;\n\n if write_z \n % write out thresholded negative Z map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded Z map.nii');\n zmap(zero_these_vox) = 0; % apply the mask we calculated like 20 lines ago\n svrlsmgui_write_vol(variables.vo, zmap);\n variables.files_created.thresholded_zmap = variables.vo.fname;\n end\n \n %% Create and write the inverted versions (P maps, not Z maps)\n thresholded.thresholded_neg = zeros(variables.vo.dim(1:3)); % make a zeros template.... \n thresholded.thresholded_neg(variables.m_idx) = 1 - thresholds.one_tail_neg_alphas;\n \n % write out unthresholded negative p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P map (inv).nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);\n variables.files_created.unthresholded_pmap_inv = variables.vo.fname;\n \n % write out thresholded negative p map\n thresholded.thresholded_neg(thresholded.thresholded_neg < (1-parameters.voxelwise_p)) = 0; % zero out subthreshold p value voxels (note 1-p)\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded P map (inv).nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);\n variables.files_created.thresholded_pmap_inv = variables.vo.fname;\n\nfunction [thresholded,variables] = write_p_maps_two_tailed(parameters,variables,thresholds)\n error('There should be an abs() around here but there isn''t, make sure this works right, especially with CFWER')\n if parameters.do_CFWER % note that the parameters struct isn't returned by this function so nothing changes outside this function scope\n parameters.voxelwise_p = variables.cfwerinfo.cfwer_single_pval_answer.onetail.pos;\n end\n\n thresholded.thresholded_twotails = zeros(variables.vo.dim(1:3)); % make a zeros template.... \n if parameters.invert_p_map_flag % it's already inverted...\n thresholded.thresholded_twotails(variables.m_idx) = thresholds.twotails_alphas;\n % write out unthresholded p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values (inv).nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotails);\n % variables.files_created.unthresholded_pmap{1} = variables.vo.fname;\n % variables.files_created.unthresholded_pmap{2} = variables.vo.fname;\n \n % write out thresholded p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');\n thresholded.thresholded_twotails(thresholded.thresholded_twotails < (1-(parameters.voxelwise_p/2))) = 0; % zero out subthreshold p value voxels (note 1-p)\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotails);\n % variables.files_created.unthresholded_pmap{1} = variables.vo.fname;\n % variables.files_created.unthresholded_pmap{2} = variables.vo.fname;\n \n warning('add writing z map thresholded and unthresholded here')\n else\n thresholded.thresholded_twotails(variables.m_idx) = 1 - thresholds.twotails_alphas;\n % write out unthresholded p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values.nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotails);\n % variables.files_created.unthresholded_pmap{1} = variables.vo.fname;\n % variables.files_created.unthresholded_pmap{2} = variables.vo.fname;\n\n warning('add writing z map thresholded and unthresholded here')\n \n % write out thresholded p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');\n thresholded.thresholded_twotails(thresholded.thresholded_twotails > (parameters.voxelwise_p/2)) = 0; % zero out supra-alpha p value voxels\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotails);\n % variables.files_created.unthresholded_pmap{1} = variables.vo.fname;\n % variables.files_created.unthresholded_pmap{2} = variables.vo.fname;\n end"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "svrlsm_bayesopt.m", "ext": ".m", "path": "svrlsmgui-master/functions/svrlsm_bayesopt.m", "size": 15549, "source_encoding": "utf_8", "md5": "2215a0e43cc0ed243fb6b154de1f8378", "text": "function results = svrlsm_bayesopt(parameters,variables)\n % For clarity...\n lesiondata = variables.lesion_dat;\n behavdata = variables.one_score;\n\n %% Which parameters to optimize and ranges to optim over\n params = hyperparameters('fitrsvm',lesiondata,behavdata);\n standrange = params(strcmp('Standardize',{params.Name})).Range;\n \n sigma = optimizableVariable('sigma',parameters.optimization.params_to_optimize.sigma_range,'Transform','log','optimize',parameters.optimization.params_to_optimize.sigma); % gamma ~ sigma...\n box = optimizableVariable('box',parameters.optimization.params_to_optimize.cost_range,'Transform','log','optimize',parameters.optimization.params_to_optimize.cost); % cost == boxconstraint\n epsilon = optimizableVariable('epsilon',parameters.optimization.params_to_optimize.epsilon_range,'Transform','none','optimize',parameters.optimization.params_to_optimize.epsilon);\n %standardize = optimizableVariable('standardize',standrange,'Transform','none','Type','categorical','optimize',parameters.optimization.params_to_optimize.standardize);\n %standrange = [0 1]; % [true false]; % {categorical(true), categorical(false)}; % ?!\n standardize = optimizableVariable('standardize',standrange,'Transform','none','Type','categorical','optimize',parameters.optimization.params_to_optimize.standardize);\n svrlsm_waitbar(parameters.waitbar,0,['Hyperparameter optimization (bayesopt: ' parameters.optimization.objective_function ')...'])\n \n % Has the user requested cross-validation or not?\n% if parameters.optimization.crossval.do_crossval\n% % Switch definition of anonymous function for objective function for optimization\n% switch parameters.optimization.objective_function\n% case 'Predict Behavior'\n% minfn = @(x) predict_behavior_w_crossval(x,lesiondata,behavdata,parameters);\n% case 'Maximum Correlation'\n% minfn = @(x) max_correlation_w_crossval(x,lesiondata,behavdata,parameters);\n% case 'Resubstitution Loss'\n% minfn = @(x) resubstitution_loss_w_crossval(x,lesiondata,behavdata,parameters);\n% otherwise\n% error(['Unknown objective function string: ' parameters.optimization.objective_function])\n% end\n% \n% % Start with this partition -- it will be replaced each call to the objective function if Repartition is 'true'\n% parameters.initialPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);\n% \n% %results = bayesopt(minfn,[sigma,box], ...\n% results = bayesopt(minfn,[gamma,box,epsilon,standardize], ...\n% 'IsObjectiveDeterministic',false,'AcquisitionFunctionName','expected-improvement-plus', ...\n% 'MaxObjectiveEvaluations',parameters.optimization.iterations, 'UseParallel',parameters.parallelize, ...\n% 'PlotFcn',[],'Verbose',0);\n% \n% else % No cross-validation was requested, so run these without cross-validation...\n% \n% % Switch definition of anonymous function for objective function for optimization\n% switch parameters.optimization.objective_function\n% case 'Predict Behavior'\n% minfn = @(x) predict_behavior(x,lesiondata,behavdata,parameters);\n% %minfn = @(x)sqrt(sum((behavdata - resubPredict(fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.box,'KernelScale',x.sigma,'Epsilon',parameters.epsilon,'Standardize',false,'true')))).^2);\n% case 'Maximum Correlation'\n% minfn = @(x) max_correlation(x,lesiondata,behavdata,parameters);\n% case 'Resubstitution Loss'\n% minfn = @(x) resubstitution_loss(x,lesiondata,behavdata,parameters);\n% otherwise \n% error(['Unknown objective function string: ' parameters.optimization.objective_function])\n% end\n% \n% results = bayesopt(minfn,[sigma,box], ... % ,epsilon,standardize], ... % the parameters we're going to try to optimize\n% 'IsObjectiveDeterministic',true,'AcquisitionFunctionName','expected-improvement-plus', ...\n% 'MaxObjectiveEvaluations',parameters.optimization.iterations, 'UseParallel',parameters.parallelize, ...\n% 'PlotFcn',[],'Verbose',0,'OutputFcn',@optim_outputfun);\n% \n% end\n\n%%\n\n% % Start with this partition -- it will be replaced each call to the objective function if Repartition is 'true'\n parameters.initialPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);\n \n % assignin('base','lesiondata',lesiondata)\n % error('s')\n \n minfn = @(x)combined_bayesopt_objective_functions3(x,sparse(lesiondata),behavdata,parameters);\n\n results = bayesopt(minfn,[sigma box epsilon standardize], ... \n 'IsObjectiveDeterministic',false, ... % parameters.optimization.crossval.do_crossval, ...\n 'AcquisitionFunctionName','expected-improvement-plus', ... % 'ExplorationRatio', 0.7, ... % 0.5 default\n 'MaxObjectiveEvaluations',parameters.optimization.iterations, ...\n 'UseParallel',parameters.parallelize, ...\n 'NumCoupledConstraints', 1, 'AreCoupledConstraintsDeterministic', false, ... % ~parameters.optimization.crossval.do_crossval, ... % if crossval, then it's not deterministic.\n 'PlotFcn',[],'OutputFcn',@optim_outputfun, ...\n 'Verbose',myif(parameters.optimization.verbose_during_optimization,2,0)); % verbose is either 0 or 2...\n\n svrlsm_waitbar(parameters.waitbar,0,''); % clear this.\n\n% %% Objective function: Maximum correlation - no cross-validation\n% function objective = max_correlation(x,lesiondata,behavdata,parameters)\n% svrtype = myif(parameters.useLibSVM,'libSVM','MATLAB');\n% switch svrtype\n% case 'libSVM'\n% error('transform gamma to sigma here?')\n% m = svmtrain(behavdata,sparse(lesiondata),get_libsvm_spec(x.cost,x.gamma,parameters.epsilon));% note get_libsvm_spec() function\n% predicted = svmpredict(behavdata, sparse(lesiondata), m, '-q');\n% case 'MATLAB' % since we take care of standardization in preprocessing\n% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.box,'KernelScale',x.sigma,'Epsilon',parameters.epsilon,'Standardize',false);\n% predicted = predict(Mdl,lesiondata);\n% end\n% corrvals = corrcoef(predicted,behavdata); % compute the correlation...\n% objective = -1 * corrvals(2,1); % grab the r. --- and multiply by negative one since we want to maximize the value...\n% \n% %% Objective function: Predict behavior - no cross-validation\nfunction objective = predict_behavior(x,lesiondata,behavdata,parameters)\n% svrtype = myif(parameters.useLibSVM,'libSVM','MATLAB');\n% switch svrtype\n% case 'libSVM'\n% error('transform gamma to sigma here?')\n% m = svmtrain(behavdata,sparse(lesiondata),get_libsvm_spec(x.cost,x.gamma,parameters.epsilon));% note get_libsvm_spec() function\n% predicted = svmpredict(behavdata, sparse(lesiondata), m, '-q');\n% case 'MATLAB' % since we take care of standardization in preprocessing\n% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on\n% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.sigma,'Standardize',touse.standardize,'Epsilon',touse.epsilon);\n Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.cost,'KernelScale',x.sigma,'Standardize',false,'Epsilon',parameters.epsilon);\n predicted = predict(Mdl,lesiondata);\n% end\n difference = behavdata(:) - predicted(:);\n mean_abs_diff = mean(abs(difference));\n objective = mean_abs_diff; % we want to minimize this value.\n% \n% %% Objective function: Resubstitution loss - no cross-validation\n% function objective = resubstitution_loss(x,lesiondata,behavdata,parameters)\n% \n% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on\n% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.gamma,'Standardize',touse.standardize,'Epsilon',touse.epsilon);\n% %\t Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.box,'KernelScale',x.sigma,'Epsilon',parameters.epsilon,'Standardize',false);\n% objective = resubLoss(Mdl);\n% \n% %% Objective function: Resubstitution loss - with K-fold cross-validation\n% function objective = resubstitution_loss_w_crossval(x,lesiondata,behavdata,parameters)\n% if parameters.optimization.crossval.repartition\n% curPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);\n% else\n% curPartition = parameters.initialPartition;\n% end\n% \n% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on\n% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.gamma,'Standardize',touse.standardize,'Epsilon',touse.epsilon,'CVPartition',curPartition);\n% \n% % Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.box,'KernelScale',x.sigma,'Standardize',false,'Epsilon',parameters.epsilon,'CVPartition', curPartition);\n% % myif(parameters.optimization.crossval.repartition,partition,partition.repartition)); \n% \n% objective = kfoldLoss(Mdl);\n% \n% %% Objective function: Predict behavior - with K-fold cross-validation\n% function objective = predict_behavior_w_crossval(x,lesiondata,behavdata,parameters)\n% % svrtype = myif(parameters.useLibSVM,'libSVM','MATLAB');\n% % switch svrtype\n% % case 'libSVM'\n% % error('transform gamma to sigma here?')\n% % m = svmtrain(behavdata,sparse(lesiondata),get_libsvm_spec(x.cost,x.gamma,parameters.epsilon));% note get_libsvm_spec() function\n% % predicted = svmpredict(behavdata, sparse(lesiondata), m, '-q');\n% % case 'MATLAB' % since we take care of standardization in preprocessing\n% \n% if parameters.optimization.crossval.repartition\n% curPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);\n% else\n% curPartition = parameters.initialPartition;\n% end\n% \n% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on\n% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.gamma,'Standardize',touse.standardize,'Epsilon',touse.epsilon,'CVPartition',curPartition);\n% predicted = kfoldPredict(Mdl);\n% % end\n% difference = behavdata(:) - predicted(:);\n% mean_abs_diff = mean(abs(difference));\n% objective = mean_abs_diff; % we want to minimize this value.\n% \n% \n% %% Objective function: Maximum correlation - with K-fold cross-validation\n% function objective = max_correlation_w_crossval(x,lesiondata,behavdata,parameters)\n% % svrtype = myif(parameters.useLibSVM,'libSVM','MATLAB');\n% % switch svrtype\n% % case 'libSVM'\n% % error('transform gamma to sigma here?')\n% % m = svmtrain(behavdata,sparse(lesiondata),get_libsvm_spec(x.cost,x.gamma,parameters.epsilon));% note get_libsvm_spec() function\n% % predicted = svmpredict(behavdata, sparse(lesiondata), m, '-q');\n% % case 'MATLAB' % since we take care of standardization in preprocessing\n% if parameters.optimization.crossval.repartition\n% curPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);\n% else\n% curPartition = parameters.initialPartition.repartition;\n% end\n% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on\n% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.gamma,'Standardize',touse.standardize,'Epsilon',touse.epsilon,'CVPartition',curPartition);\n% \n% predicted = kfoldPredict(Mdl);\n% %end\n% corrvals = corrcoef(predicted,behavdata); % compute the correlation...\n% objective = -1 * corrvals(2,1); % grab the r. --- and multiply by negative one since we want to maximize the value...\n% \n\n% function objective = combined_bayesopt_objective_functions(x,lesiondata,behavdata,parameters)\n% \n% % hyperparameter values to use for this iteration\n% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on\n% \n% % add in cross-validation parameters dynamically as necessary...\n% crossvalparms = {}; % default\n% if parameters.optimization.crossval.do_crossval\n% if parameters.optimization.crossval.repartition\n% curPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);\n% else\n% curPartition = parameters.initialPartition.repartition;\n% end\n% crossvalparms ={'CVPartition',curPartition};\n% end\n% \n% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.sigma,'Standardize',touse.standardize,'Epsilon',touse.epsilon,crossvalparms{:}); % 'CVPartition',curPartition);\n% \n% switch parameters.optimization.objective_function\n% case 'Predict Behavior' % embedded conditional of whether we predict or kfoldpredict\n% if parameters.optimization.crossval.do_crossval\n% predicted = kfoldPredict(Mdl);\n% else\n% predicted = predict(Mdl,lesiondata);\n% end\n% \n% difference = behavdata(:) - predicted(:);\n% mean_abs_diff = mean(abs(difference));\n% objective = mean_abs_diff; % we want to minimize this value.\n% \n% case 'Maximum Correlation' % embedded conditional of whether we predict or kfoldpredict\n% if parameters.optimization.crossval.do_crossval\n% predicted = kfoldPredict(Mdl);\n% else\n% predicted = predict(Mdl,lesiondata);\n% end\n% \n% corrvals = corrcoef(predicted,behavdata); % compute the correlation...\n% objective = -1 * corrvals(2,1); % grab the r. --- and multiply by negative one since we want to maximize the value...\n% \n% case 'Resubstitution Loss'\n% if parameters.optimization.crossval.do_crossval\n% objective = kfoldLoss(Mdl);\n% else\n% objective = resubLoss(Mdl);\n% end\n% otherwise\n% error(['Unknown objective function string: ' parameters.optimization.objective_function])\n% end\n% \n% function touse = get_cur_optim_iter_parms(x,parameters)\n% parms = {'cost','sigma','epsilon','standardize'};\n% for f = parms\n% if isfield(x,f{1}) % then we're asked to optimize it so return:\n% touse.(f{1}) = x.(f{1}); % the dynamic value for each iteration\n% else\n% touse.(f{1}) = parameters.(f{1}); % or the constant supplied by the user\n% end\n% end"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "svrlsm_waitbar.m", "ext": ".m", "path": "svrlsmgui-master/functions/svrlsm_waitbar.m", "size": 726, "source_encoding": "utf_8", "md5": "5732f213c7d380dbecbb6ffa4179a9d8", "text": "function svrlsm_waitbar(waitbar_handles,newval,message)\n if isempty(waitbar_handles)\n return\n end\n% if numel(waitbar_handles) ~= 2 % < caused by multiple svrlsmgui's open at once\n% error('Too many handles in input array')\n% end\n set_progress_percent(waitbar_handles(1),newval)\n if nargin > 2\n set_progress_text(waitbar_handles(2),message)\n end\n drawnow\n\n% update percent progress\nfunction set_progress_percent(rectangle_handle,newval)\n pos = get(rectangle_handle,'position');\n pos(3) = 100*newval; %update the width parameter....\n set(rectangle_handle,'position',pos)\n\n% update message\nfunction set_progress_text(txt_handle,message)\n set(txt_handle,'string',message)"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "step1_parallel.m", "ext": ".m", "path": "svrlsmgui-master/functions/step1_parallel.m", "size": 8340, "source_encoding": "utf_8", "md5": "9ce154f0ddd002dfff3717ec0effd46d", "text": "function [handles,parameters] = step1_parallel(handles,parameters,variables)\n % This is where we'll save our GBs of permutation data output...\n parameters.outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);\n\n %% Try to use cache to skip this step by relying on cached permutation data\n if can_skip_generating_beta_perms(parameters,variables)\n error('caching disabled, cause it''s not completely supported')\n handles = UpdateProgress(handles,'Using cached beta map permutation data...',1); return\n else\n handles = UpdateProgress(handles,'Computing beta map permutations (parallelized)...',1);\n svrlsm_waitbar(parameters.waitbar,0,'Computing beta permutations (parallelized)...');\n end\n \n %% If we got here then we need to generate the permutation data\n \n %% Cute way to create the permuted behavioral data... each column is one permutation.\n permdata = variables.one_score(cell2mat(cellfun(@(x) randperm(x)',repmat({numel(variables.one_score)},1,parameters.PermNumVoxelwise),'uni',false)));\n outpath = variables.output_folder.clusterwise;\n totalperms = parameters.PermNumVoxelwise;\n hyperparms = hyperparmstruct(parameters);\n \n %% Figure out what parameters we'll be using:\n if parameters.useLibSVM\n parameters.step1.libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % Standardization is already applied.\n tmp.libsvmstring = parameters.step1.libsvmstring;\n else % use matlab's -- note the cell array we're creating - it's fancy since later we'll parameters.step1.matlab_svr_parms{:}\n parameters.step1.matlab_svr_parms = [{'BoxConstraint', hyperparms.cost, ...\n 'KernelScale', hyperparms.sigma, ...\n 'Standardize', hyperparms.standardize, ...\n 'Epsilon', hyperparms.epsilon} ...\n myif(parameters.crossval.do_crossval,{'KFold',parameters.crossval.nfolds},[])]; % this is for the crossvalidation option...\n tmp.matlab_svr_parms = parameters.step1.matlab_svr_parms;\n tmp.do_crossval = parameters.crossval.do_crossval; % also save this here too.\n end\n\n %% parfeval code\n batch_job_size = 100; % this is going to be optimal for different systems/#cores/jobs - set this through gui?\n nperms = parameters.PermNumVoxelwise;\n njobs = ceil(nperms/batch_job_size); % gotta round up to capture all indices\n\n %% to reduce overhead transfering data to workers...\n tmp.dims = variables.vo.dim(1:3);\n tmp.lesiondata = sparse(variables.lesion_dat); % full() it on the other end - does that save time with transfer to worker overhead?!\n tmp.outpath = variables.output_folder.clusterwise;\n \n if ~parameters.method.mass_univariate % then we need to save beta_scale as well...\n tmp.beta_scale = variables.beta_scale;\n end\n \n tmp.m_idx = variables.m_idx;\n tmp.l_idx = variables.l_idx;\n tmp.totalperms = totalperms;\n tmp.permdata = permdata;\n tmp.useLibSVM = parameters.useLibSVM;\n tmp.use_mass_univariate = parameters.method.mass_univariate;\n\n %% Schedule the jobs...\n p = gcp(); % get current parallel pool\n for j = 1 : njobs\n this_job_start_index = ((j-1)*batch_job_size) + 1;\n this_job_end_index = min(this_job_start_index + batch_job_size-1,nperms); % need min so we don't go past valid indices\n this_job_perm_indices = this_job_start_index:this_job_end_index;\n tmp.this_job_perm_indices = this_job_perm_indices; % update for each set of jobs...\n f(j) = parfeval(p,@parallel_step1_batch_fcn_lessoverhead,0,tmp);\n end\n \n %% Monitor job progress and allow user to bail, hopefully...\n for j = 1 : njobs\n check_for_interrupt(parameters) % allow user to interrupt\n idx = fetchNext(f);\n svrlsm_waitbar(parameters.waitbar,j/njobs) % update waitbar progress...\n end\n \n %% Now assemble all those individual files from each parfored permutation into one big file that we can memmap\n handles = UpdateProgress(handles,'Consolidating beta map permutation data...',1);\n svrlsm_waitbar(parameters.waitbar,0,'Consolidating beta map permutation data...');\n fileID = fopen(parameters.outfname_big,'w');\n for PermIdx=1:parameters.PermNumVoxelwise\n if ~mod(PermIdx,100)\n svrlsm_waitbar(parameters.waitbar,PermIdx/parameters.PermNumVoxelwise); % update user on progress\n check_for_interrupt(parameters)\n end \n curpermfilepath = fullfile(outpath,['pmu_beta_map_' num2str(PermIdx) '_of_' num2str(totalperms) '.bin']);\n cur_perm_data = memmapfile(curpermfilepath,'Format','single');\n fwrite(fileID, cur_perm_data.Data,'single');\n clear cur_perm_data; % remove memmap from memory.\n delete(curpermfilepath); % delete it since we don't want the data hanging around...\n end\n svrlsm_waitbar(parameters.waitbar,0,''); % reset.\n fclose(fileID); % close big file\n\nfunction parallel_step1_batch_fcn_lessoverhead(tmp)\n if ~tmp.useLibSVM || tmp.use_mass_univariate, tmp.lesiondata = full(tmp.lesiondata); end % we transfer it as sparse... so we need to full() it for all non-libSVM methods\n \n for PermIdx = tmp.this_job_perm_indices % each loop iteration will compute one whole-brain permutation result (regardless of LSM method)\n trial_score = tmp.permdata(:,PermIdx); % extract the row of permuted data.\n if tmp.use_mass_univariate % solve whole-brain permutation PermIdx on a voxel-by-voxel basis.\n pmu_beta_map = nan(size(tmp.lesiondata,2),1); % reserve space -- are these dims right?\n for vox = 1 : size(tmp.lesiondata,2)\n [Q, R] = qr(trial_score, 0); % use the householder transformations to compute the qr factorization of an n by p matrix x.\n y = double(tmp.lesiondata(:,vox));% / 10000; % why divide by 10,000? %betas(vox) = R \\ (Q' * y); % equivalent to fitlm's output: lm.Coefficients.Estimate\n pmu_beta_map(vox) = R \\ (Q' * y); % equivalent to fitlm's output: lm.Coefficients.Estimate\n end\n else % use an SVR method\n if tmp.useLibSVM\n m = svmtrain(trial_score,tmp.lesiondata,tmp.libsvmstring); %#ok % alpha = m.sv_coef'; % SVs = m.SVs;\n else % use matlab's...\n m = fitrsvm(tmp.lesiondata,trial_score,'KernelFunction','rbf', tmp.matlab_svr_parms{:});\n end\n \n if ~tmp.do_crossval % then compute the beta map as usual...\n pmu_beta_map = tmp.beta_scale * m.(myif(tmp.useLibSVM,'sv_coef','Alpha'))' * m.(myif(tmp.useLibSVM,'SVs','SupportVectors'));\n else % we don't need to do any computations since w should already contain a scaled/averaged model\n ws = []; % we'll accumulate in here\n for mm = 1 : numel(m.Trained)\n curMdl = m.Trained{mm};\n w = curMdl.Alpha.'*curMdl.SupportVectors;\n beta_scale = 10/max(abs(w));\n w = w.'*beta_scale;\n ws(1:numel(w),mm) = w; % accumulate here...\n end\n w = mean(ws,2);\n pmu_beta_map = w; % here contains an average of the crossvalidated fold models' beta values\n end\n end\n \n tmp_map = zeros(tmp.dims); % make a zeros template.... \n tmp_map(tmp.l_idx) = pmu_beta_map; % return the lesion data to their lidx indices...\n pmu_beta_map = tmp_map(tmp.m_idx).'; % extract only the midx indices, since these are the only voxels that will be output in the results -- midx contains only voxels that exceed the lesion threshold\n\n % Save this permutation (PermIdx)....\n fileID = fopen(fullfile(tmp.outpath,['pmu_beta_map_' num2str(PermIdx) '_of_' num2str(tmp.totalperms) '.bin']),'w');\n fwrite(fileID, pmu_beta_map,'single');\n fclose(fileID);\n end\n \nfunction [Bouts,lesiondataout] = parallel_step1_batch_muvlsm(lesiondata,modelspec)\n for vox = 1 : size(lesiondata,2) % run of the mill loop now...\n [B,~,resids] = regress(lesiondata(:,vox),modelspec);\n lesiondataout(:,vox) = resids + repmat(B(1),size(resids));\n Bouts(:,vox) = B;\n end\n"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "build_and_write_beta_cutoffs.m", "ext": ".m", "path": "svrlsmgui-master/functions/build_and_write_beta_cutoffs.m", "size": 3366, "source_encoding": "utf_8", "md5": "f724334d6a434ee45dc9f8b9b64c223f", "text": "function [thresholded,variables] = build_and_write_beta_cutoffs(options,parameters,variables,thresholds,thresholded)\n switch parameters.tailshort % parameters.tails\n case 'pos' % One-tailed positive tail... high scores bad \n [thresholded,variables] = write_beta_cutoff_pos_tail(variables,thresholds,thresholded);\n case 'neg' % One-tailed negative tail... high scores good\n [thresholded,variables] = write_beta_cutoff_neg_tail(variables,thresholds,thresholded);\n case 'two' % Both tails..\n warning('not enabled at the moment...')\n [thresholded,variables] = write_beta_cutoff_two_tailed(variables,thresholds,thresholded);\n end\n\nfunction [thresholded,variables] = write_beta_cutoff_pos_tail(variables,thresholds,thresholded)\n % Now write out beta cutoff map.\n thresholded.thresholded_pos = zeros(variables.vo.dim(1:3)); % make a zeros template....\n thresholded.thresholded_pos(variables.m_idx) = thresholds.pos_beta_map_cutoff; % put the 95th percentil beta values back into the lesion indices in a full volume\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (positive tail).nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);\n variables.files_created.betamask = variables.vo.fname;\n\nfunction [thresholded,variables] = write_beta_cutoff_neg_tail(variables,thresholds,thresholded)\n % Now beta cutoff map for one-taled negative tail...\n thresholded.thresholded_neg = zeros(variables.vo.dim(1:3)); % make a zeros template.... \n thresholded.thresholded_neg(variables.m_idx) = thresholds.neg_beta_map_cutoff; % put the 5th percentil beta values back into the lesion indices in a full volume\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (negative tail).nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);\n variables.files_created.betamask = variables.vo.fname;\n\nfunction [thresholded,variables] = write_beta_cutoff_two_tailed(variables,thresholds,thresholded)\n warning('make sure these tails are right after code refactor') % ad 2/14/18\n % Two-tailed upper tail\n thresholded.thresholded_twotail_upper = zeros(variables.vo.dim(1:3)); % make a zeros template.... \n thresholded.thresholded_twotail_upper(variables.m_idx) = thresholds.two_tailed_beta_map_cutoff_pos; % put the 2.5th percentil beta values back into the lesion indices in a full volume\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (two tail, upper).nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotail_upper);\n variables.files_created.betamask{1} = variables.vo.fname;\n \n % Two-tailed lower tail\n thresholded.thresholded_twotail_lower = zeros(variables.vo.dim(1:3)); % make a zeros template.... \n thresholded.thresholded_twotail_lower(variables.m_idx) = thresholds.two_tailed_beta_map_cutoff_neg; % put the 2.5th percentil beta values back into the lesion indices in a full volume\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (two tail, lower).nii');\n svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotail_lower);\n variables.files_created.betamask{2} = variables.vo.fname; % note second cell index"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "svrinteract.m", "ext": ".m", "path": "svrlsmgui-master/functions/svrinteract.m", "size": 10295, "source_encoding": "utf_8", "md5": "844fdc5833c36244c16ecf3dc90d0faf", "text": "function varargout = svrinteract(varargin)\n% SVRINTERACT MATLAB code for svrinteract.fig\n% SVRINTERACT, by itself, creates a new SVRINTERACT or raises the existing\n% singleton*.\n%\n% H = SVRINTERACT returns the handle to a new SVRINTERACT or the handle to\n% the existing singleton*.\n%\n% SVRINTERACT('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in SVRINTERACT.M with the given input arguments.\n%\n% SVRINTERACT('Property','Value',...) creates a new SVRINTERACT or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before svrinteract_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to svrinteract_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help svrinteract\n\n% Last Modified by GUIDE v2.5 19-Mar-2018 12:55:56\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @svrinteract_OpeningFcn, ...\n 'gui_OutputFcn', @svrinteract_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before svrinteract is made visible.\nfunction svrinteract_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to svrinteract (see VARARGIN)\n\n% Choose default command line output for svrinteract\nhandles.output = hObject;\nhandles.variables = varargin{1};\nhandles.opts.stand = false;\nhandles.opts.ep = .1;\nhandles.opts.box = 30;\nhandles.opts.ks = 2;\nhandles.opts.nfolds = 1; % nfolds = 1 is no crossval\nhandles.opts.zslice = 25;\n\ntmp = 10 .* randn(handles.variables.vo.dim(1:3));\n\nif (numel(handles.variables.vo.dim) > 3) && (handles.variables.vo.dim(4) > 1) % then it's 4D % handles.variables.vo.dim(4) > 1 % then it's 4d...\n handles.ndims = 4;\nelse\n handles.ndims = 3;\nend\n\nif handles.ndims == 4\n handles.I = imagesc(tmp(:,:,20),'parent',handles.axes1,[-50 50]);\nelse % it's 3d...\n handles.I = imagesc(tmp(:,:,20),'parent',handles.axes1,[-10 10]);\nend\n\nhandles.montage_zslices = 5:10:(size(tmp,3)-1);\n\nif handles.ndims == 4\n montage(tmp, 'Indices',handles.montage_zslices,'DisplayRange', [-50 50],'parent',handles.axes1);\nelse\n montage(tmp, 'Indices',handles.montage_zslices,'DisplayRange', [-10 10],'parent',handles.axes1);\nend\n colormap jet;\n colorbar(handles.axes1)\n\nrealdata=handles.variables.one_score;\nhandles.real = plot(1:numel(handles.variables.one_score),realdata,'sg-','parent',handles.axes2);\nhold on;\nset(gca,'ylim',[min(realdata)-.1*min(realdata) max(realdata)+.1*max(realdata)])\nhold on;\nhandles.pred = plot(1:numel(handles.variables.one_score),zeros(1,numel(handles.variables.one_score)),'rx-','parent',handles.axes2);\n\n% Update handles structure\nguidata(hObject, handles);\n\npaint_current(hObject,handles)\n\n% UIWAIT makes svrinteract wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\nfunction paint_current(hObject,handles)\n set(handles.standardize_toggle,'value',handles.opts.stand)\n set(handles.epsilon_editbox,'string',num2str(handles.opts.ep)); \n set(handles.cost_editbox,'string',num2str(handles.opts.box)); \n set(handles.kenelscale_editbox,'string',num2str(handles.opts.ks)); \n set(handles.zslice,'string',num2str(handles.opts.zslice)); \n set(handles.crossval_nfolds_editbox,'string',num2str(handles.opts.nfolds)); \n \n if handles.ndims == 4 % then use linear kernel\n Mdl = fitrsvm(handles.variables.lesion_dat,handles.variables.one_score,'KernelFunction','linear',... % 'rbf', ...\n 'KernelScale',handles.opts.ks,'BoxConstraint',handles.opts.box,'Standardize', ...\n handles.opts.stand,'Epsilon',handles.opts.ep);\n else % rbf\n Mdl = fitrsvm(handles.variables.lesion_dat,handles.variables.one_score,'KernelFunction','rbf', ...\n 'KernelScale',handles.opts.ks,'BoxConstraint',handles.opts.box,'Standardize', ...\n handles.opts.stand,'Epsilon',handles.opts.ep);\n end\n w = Mdl.Alpha.'*Mdl.SupportVectors;\n handles.variables.beta_scale = 10/max(abs(w));\n \n if handles.ndims == 4\n disp('4D data input...')\n tmp = zeros(handles.variables.vo.dim(1:4)); % THIS IS DIFFERENT FOR 4D DATA\n beta_map = tmp;\n tmp(handles.variables.l_idx) = w'*handles.variables.beta_scale; % return all lesion data to its l_idx indices.\n beta_map(handles.variables.m_idx) = tmp(handles.variables.m_idx); % m_idx -> m_idx\n \n beta_map = sum(beta_map,4); % THIS IS DIFFERENT FOR 4D DATA\n beta_map_bin = beta_map~=0;\n\n relslices = find(squeeze(sum(squeeze(sum(beta_map_bin,1)),1)));\n handles.montage_zslices = min(relslices):2:max(relslices);\n montage(beta_map,'indices',handles.montage_zslices, 'DisplayRange', [-20 20],'parent',handles.axes1);\n else\n disp('3D data input...')\n tmp = zeros(handles.variables.vo.dim(1:3));\n beta_map = tmp;\n\n tmp(handles.variables.l_idx) = w'*handles.variables.beta_scale; % return all lesion data to its l_idx indices.\n beta_map(handles.variables.m_idx) = tmp(handles.variables.m_idx); % m_idx -> m_idx\n\n %set(handles.I,'cdata',beta_map(:,:,handles.opts.zslice));\n %montage(beta_map, 'Indices',handles.montage_zslices,'DisplayRange', [-10 10],'parent',handles.axes1);\n\n %handles.montage_zslices = 5:10:(size(tmp,3)-1);\n %handles.variables.lesion_dat\n\n beta_map_bin = beta_map~=0;\n\n relslices = find(squeeze(sum(squeeze(sum(beta_map_bin,1)),1)));\n handles.montage_zslices = min(relslices):2:max(relslices);\n montage(beta_map,'indices',handles.montage_zslices, 'DisplayRange', [-10 10],'parent',handles.axes1);\n\n end\n\n\n colormap jet;\n colorbar(handles.axes1)\n\n disp(['Proportion is support vectors = ' num2str(sum(Mdl.IsSupportVector)/numel(Mdl.IsSupportVector))])\n\n if handles.opts.nfolds == 1 % no crossval\n predicted = Mdl.predict(handles.variables.lesion_dat);\n else\n XVMdl = crossval(Mdl,'KFold',handles.opts.nfolds);\n predicted = XVMdl.kfoldPredict; \n end\n\n\n set(handles.pred,'ydata',predicted)\n hold on;\n set(handles.real,'ydata',handles.variables.one_score)\n% \n% realdata=handles.variables.one_score;\n% handles.real = plot(1:numel(handles.variables.one_score),realdata,'sg-','parent',handles.axes2);\n% hold on;\n% set(handles.axes2,'ylim',[min(realdata)-.1*min(realdata) max(realdata)+.1*max(realdata)])\n% preddata = Mdl.predict(handles.variables.lesion_dat);\n% handles.pred = plot(1:numel(handles.variables.one_score),preddata,'rx-','parent',handles.axes2);\n guidata(hObject, handles);\n\n\nfunction varargout = svrinteract_OutputFcn(hObject, eventdata, handles) \nvarargout{1} = handles.output;\n\nfunction epsilon_editbox_Callback(hObject, eventdata, handles)\n handles.opts.ep = str2double(get(hObject,'String'));\n paint_current(hObject,handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction epsilon_editbox_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nfunction cost_editbox_Callback(hObject, eventdata, handles)\n handles.opts.box = str2double(get(hObject,'String'));\n paint_current(hObject,handles)\n\n\n% --- Executes during object creation, after setting all properties.\nfunction cost_editbox_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\nfunction kenelscale_editbox_Callback(hObject, eventdata, handles)\n handles.opts.ks = str2double(get(hObject,'String'));\n paint_current(hObject,handles)\n\n\n% --- Executes during object creation, after setting all properties.\nfunction kenelscale_editbox_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\n% --- Executes on button press in standardize_toggle.\nfunction standardize_toggle_Callback(hObject, eventdata, handles)\n handles.opts.stand = ~handles.opts.stand;\n paint_current(hObject,handles)\n\n\n% --- Executes on button press in pushbutton2refre.\nfunction pushbutton2refre_Callback(hObject, eventdata, handles)\n% hObject handle to pushbutton2refre (see GCBO)\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n\n\nfunction zslice_Callback(hObject, eventdata, handles)\n handles.opts.zslice = str2double(get(hObject,'String'));\n paint_current(hObject,handles)\n\n\n\n% --- Executes during object creation, after setting all properties.\nfunction zslice_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n\n\nfunction crossval_nfolds_editbox_Callback(hObject, eventdata, handles)\n handles.opts.nfolds = str2double(get(hObject,'String'));\n paint_current(hObject,handles)\n\n% --- Executes during object creation, after setting all properties.\nfunction crossval_nfolds_editbox_CreateFcn(hObject, eventdata, handles)\nif ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))\n set(hObject,'BackgroundColor','white');\nend\n"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "optimalParameterReport.m", "ext": ".m", "path": "svrlsmgui-master/functions/optimalParameterReport.m", "size": 10418, "source_encoding": "utf_8", "md5": "f029005bdb9ec73ef901438e0e2fcdf8", "text": "function variables = optimalParameterReport(parameters,variables)\n mkdir(variables.output_folder.hyperparameterinfo)\n %variables = optimalParameterReport(parameters,variables);\n %variables.files_created.cfwerinfo = fullcfwerout;\n\n % based on Zhang et al (2014)\n % returns results for two measures of hyper parameter optimality:\n\n % 1. reproducibility index and\n % 2. prediction accuracy\n % 3. mean absolute difference...\n\n [hyperparameter_quality.pred_accuracy, ...\n hyperparameter_quality.mean_abs_diff] = computePredictionAccuracy(parameters,variables);\n \n hyperparameter_quality.repro_index = computeReproducibilityIndex(parameters,variables);\n hyperparameter_quality.behavioral_predictions = computerBehavioralPrediction(parameters,variables); % this will be used for our WritePredictBehaviorReport in summary output.\n \n %% Save the results so we can use them later\n fname = 'hyperparameter_quality.mat';\n fpath = fullfile(variables.output_folder.hyperparameterinfo,fname); \n save(fpath,'hyperparameter_quality','-v7.3') % if it's bigger than 2 GB we need v7.3 anyway...\n variables.files_created.hyperparameter_quality = fpath;\n variables.hyperparameter_quality = hyperparameter_quality;\n \nfunction behavioral_predictions = computerBehavioralPrediction(parameters,variables)\n behavdata = variables.one_score; % for clarity extract these.\n lesiondata = variables.lesion_dat;\n\n %nfolds = 5; % Zhang et al., 2014\n nfolds = parameters.hyperparameter_quality.report.nfolds;\n\n hyperparms = hyperparmstruct(parameters);\n \n svrlsm_waitbar(parameters.waitbar,0,'Hyperparameter optimization: Storing behavioral predictions.');\n if parameters.useLibSVM\n libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % we may need to re-apply standardization...?\n crossvalinds = crossvalind('KFold', variables.SubNum, nfolds);\n lesiondata=sparse(lesiondata);\n m = svmtrain(behavdata, lesiondata, libsvmstring); %#ok -- use all data\n behavioral_predictions.Mdl = m;\n for curfold=1:nfolds\n infold = crossvalinds == curfold;\n outoffold = crossvalinds ~= curfold;\n m = svmtrain(behavdata(outoffold), lesiondata(outoffold,:), libsvmstring); %#ok\n behavioral_predictions.XVMdl_predicted(infold) = svmpredict(behavdata(infold), lesiondata(infold,:), m, '-q'); % predict OOF observations based on cur fold data.\n end\n behavioral_predictions.XVMdl = [];\n \n else % Run with MATLAB machinery.\n Mdl = fitrsvm(lesiondata,behavdata,'ObservationsIn','rows','KernelFunction','rbf', 'KernelScale',hyperparms.sigma,'BoxConstraint',hyperparms.cost,'Standardize',hyperparms.standardize,'Epsilon',hyperparms.epsilon);\n XVMdl = crossval(Mdl,'KFold',nfolds); % this is a 5-fold\n\n behavioral_predictions.Mdl = Mdl;\n behavioral_predictions.XVMdl = XVMdl;\n behavioral_predictions.XVMdl_predicted = kfoldPredict(XVMdl);\n end\n svrlsm_waitbar(parameters.waitbar,0,'');\n \n% 1. reproducibility index\n% - solve the SVRLSM N times for a random subset of 80% of subjects (Zhang et al used 85 of 106 pts for each rerun)\n% - compute pairwise correlations between all the resulting SVR-B maps\n% - mean of the correlation coefficients is the REPRODUCIBILITY INDEX\n\nfunction repro_index = computeReproducibilityIndex(parameters,variables)\n % For clarity extract these.\n behavdata = variables.one_score;\n lesiondata = variables.lesion_dat;\n \n % restore to 40 crossval steps once we introduce parallelization -- maybe make it user-configurable\n %N_subsets_to_perform = 2; % 10; % Zhang et al., 2015\n %subset_include_percentage = .8; % Zhang et al., 2015\n subset_include_percentage = parameters.hyperparameter_quality.report.repro_ind_subset_pct;\n N_subsets_to_perform = parameters.hyperparameter_quality.report.n_replications;\n\n nsubs = numel(behavdata);\n nholdin = round(subset_include_percentage*nsubs); % how many subjects should be in each subset?\n\n hyperparms = hyperparmstruct(parameters);\n \n N_subset_results = cell(1,N_subsets_to_perform); % save the correlation coefficients in this vector, then average them\n percent_obs_are_SVs = nan(1,N_subsets_to_perform); % count the number of SVs...\n \n svrlsm_waitbar(parameters.waitbar,0,'Hyperparameter optimization: Measuring reproducibility index.');\n for N = 1 : N_subsets_to_perform\n svrlsm_waitbar(parameters.waitbar,N/N_subsets_to_perform);\n includesubs = randperm(nsubs,nholdin); % each column contains a unique permutation\n \n if parameters.useLibSVM % do libsvm...\n libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % we may need to re-apply standardization...?\n lesiondata=sparse(lesiondata);\n m = svmtrain(behavdata(includesubs), lesiondata(includesubs,:), libsvmstring); %#ok\n percent_obs_are_SVs(N) = m.totalSV / variables.SubNum; % should we instead use: sum(m.sv_coef == parameters.cost)) % (this is the number of bounded SVs)\n w = m.sv_coef'*m.SVs;\n else % do with MATLAB\n Mdl = fitrsvm(lesiondata(includesubs,:),behavdata(includesubs,:),'ObservationsIn','rows','KernelFunction','rbf', 'KernelScale',hyperparms.sigma,'BoxConstraint',hyperparms.cost,'Standardize',hyperparms.standardize,'Epsilon',hyperparms.epsilon);\n percent_obs_are_SVs(N) = sum(Mdl.IsSupportVector) / numel(Mdl.IsSupportVector);\n w = Mdl.Alpha.'*Mdl.SupportVectors;\n end\n \n if N == 1 % compute initial beta_scale to reuse...\n beta_scale = 10 / prctile(abs(w),parameters.svscaling); % parameters.svscaling is e.g, 100 or 99 or 95\n end\n \n w = w'*beta_scale; % the beta here is kind of irrelevant because it just scales the data, and correlation is insensitive to scaling...\n N_subset_results{N} = w; % save the w-map...\n end\n \n % Now for each pair of w maps in N_subset_results{:}, compute a correlation coefficient...\n C = nchoosek(1:numel(N_subset_results),2); % rows of pairwise indices to correlate...\n repro_index_correlation_results = nan(size(C,1),1); % reseve space...\n for row = 1 : size(C,1)\n corrvals = corrcoef(N_subset_results{C(row,1)},N_subset_results{C(row,2)}); % compute the correlation...\n r = corrvals(2,1); % grab the r\n repro_index_correlation_results(row) = r; % store.\n end\n \n repro_index.data = repro_index_correlation_results;\n repro_index.mean = mean(repro_index_correlation_results);\n repro_index.std = std(repro_index_correlation_results);\n repro_index.percent_obs_are_SVs = percent_obs_are_SVs; % number of support vectors...\n \n% 2. prediction accuracy\n% - mean correlation coefficient between predixcted scores and testing scores with 40 5-fold cross-validations.\nfunction [pred_accuracy,mean_abs_diff] = computePredictionAccuracy(parameters,variables)\n behavdata = variables.one_score; % for clarity extract these.\n lesiondata = variables.lesion_dat;\n \n % restore to 40 crossval steps once we introduce parallelization -- maybe make it user-configurable\n %N_crossvals_to_perform = 2; % 10; % Zhang et al., 2015\n % nfolds = 5; % Zhang et al., 2014\n\n nfolds = parameters.hyperparameter_quality.report.nfolds;\n N_crossvals_to_perform = parameters.hyperparameter_quality.report.n_replications;\n \n hyperparms = hyperparmstruct(parameters);\n\n N_crossval_correl_results = nan(1,N_crossvals_to_perform); % save the correlation coefficients in this vector, then average them\n N_crossval_MAD_results = nan(1,N_crossvals_to_perform); % average mean absolute difference between predicted and real.\n percent_obs_are_SVs = nan(1,N_crossvals_to_perform); % count the number of SVs...\n \n if parameters.useLibSVM % try to save time by only doing this once...\n lesiondata=sparse(lesiondata);\n end\n \n svrlsm_waitbar(parameters.waitbar,0,'Hyperparameter optimization: Measuring prediction accuracy.');\n \n predicted = nan(variables.SubNum,1); % reserve space.\n for N = 1 : N_crossvals_to_perform\n svrlsm_waitbar(parameters.waitbar,N/N_crossvals_to_perform);\n if parameters.useLibSVM\n libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % we may need to re-apply standardization...?\n crossvalinds = crossvalind('KFold', variables.SubNum, nfolds);\n for curfold=1:nfolds\n infold = crossvalinds == curfold;\n outoffold = crossvalinds ~= curfold;\n m = svmtrain(behavdata(outoffold), lesiondata(outoffold,:), libsvmstring); %#ok\n predicted(infold) = svmpredict(behavdata(infold), lesiondata(infold,:), m, '-q'); % predict OOF observations based on cur fold data.\n end\n else\n Mdl = fitrsvm(lesiondata,behavdata,'ObservationsIn','rows','KernelFunction','rbf', 'KernelScale',hyperparms.sigma,'BoxConstraint',hyperparms.cost,'Standardize',hyperparms.standardize,'Epsilon',hyperparms.epsilon);\n percent_obs_are_SVs(N) = sum(Mdl.IsSupportVector) / numel(Mdl.IsSupportVector);\n XVMdl = crossval(Mdl,'Kfold',nfolds); % this is a 5-fold\n predicted = kfoldPredict(XVMdl);\n end\n corrvals = corrcoef(predicted,behavdata); % compute the correlation...\n r = corrvals(2,1); % grab the r\n N_crossval_correl_results(N) = r; % save.\n N_crossval_MAD_results(N) = mean(abs(predicted-behavdata));\n end\n svrlsm_waitbar(parameters.waitbar,0,'');\n pred_accuracy.data = N_crossval_correl_results; % can plot a distribution if we like...\n pred_accuracy.mean = mean(N_crossval_correl_results);\n pred_accuracy.std = std(N_crossval_correl_results);\n pred_accuracy.percent_obs_are_SVs = percent_obs_are_SVs; % number of support vectors...\n \n mean_abs_diff.data = N_crossval_MAD_results; % can plot a distribution if we like... redundant w pred_accuracy\n mean_abs_diff.mean = mean(N_crossval_MAD_results);\n mean_abs_diff.std = std(N_crossval_MAD_results);\n mean_abs_diff.percent_obs_are_SVs = percent_obs_are_SVs; % number of support vectors... redundant w pred_accuracy"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "continuize_lesions.m", "ext": ".m", "path": "svrlsmgui-master/functions/continuize_lesions.m", "size": 3445, "source_encoding": "utf_8", "md5": "4c8d28c69af12f9066e66e03d26ae518", "text": "function variables = continuize_lesions(variables,parameters)\n% 8/7/17 - added support for parallelization\n% 8/7/17 - fixed bug - intercept term and adding its beta back into residuals \n% 11/16/17 - added check for user interrupt \n% 2/19/18 - added in-gui waitbar in parallelized and non-parallelized loop \n% waitbar for the par loop involved replacing the pre-existing parfor code\n% with 'parfeval' which was introduced in MATLAB 2013b\n\nlesiondataout = nan(size(variables.lesion_dat));\nmodelcols = variables.lesion_nuisance_model;\nlesiondata = variables.lesion_dat;\nconst = ones(size(modelcols,1),1);\nmodelspec = [const modelcols];\nBouts = nan(size(modelspec,2),size(variables.lesion_dat,2));\n\nif parameters.parallelize\n svrlsm_waitbar(parameters.waitbar,0,'Running lesion nuisance model (parallelized)...')\n batch_job_size = 2500; % this is going to be optimal for different systems/#cores\n nvox = size(lesiondata,2);\n njobs = ceil(nvox/batch_job_size); % gotta round up to capture all indices\n\n p = gcp(); % get current parallel pool\n for j = 1 : njobs\n this_job_start_index = ((j-1)*batch_job_size) + 1;\n this_job_end_index = min(this_job_start_index + batch_job_size-1,nvox); % need min so we don't go past valid indices\n job_indices = this_job_start_index:this_job_end_index;\n f(j) = parfeval(p, @parallel_lesion_batch_fcn, 2,lesiondata(:,job_indices),modelspec); % 2 outputs\n end\n \n Bouts = cell(1,njobs); %reserve space - note we want to accumulate in a row here\n lesiondataout = cell(1,njobs); %reserve space - note we want to accumulate in a row here\n\n for j = 1 : njobs\n check_for_interrupt(parameters) % allow user to interrupt\n [idx, value1,value2] = fetchNext(f);\n Bouts{idx} = value1; % combine these cells afterward\n lesiondataout{idx} = value2; % combine these cells afterward\n svrlsm_waitbar(parameters.waitbar,j/njobs) % update waitbar progress...\n end\n \n Bouts = cell2mat(Bouts); % combine afterward\n lesiondataout = cell2mat(lesiondataout); % combine afterward\n\nelse % not parallelized.\n \n svrlsm_waitbar(parameters.waitbar,0,'Running lesion nuisance model...')\n for vox = 1 : size(variables.lesion_dat,2) \n if ~mod(vox,100), svrlsm_waitbar(parameters.waitbar,vox/size(variables.lesion_dat,2)); end \n check_for_interrupt(parameters) % allow user to interrupt\n [B,~,resids] = regress(lesiondata(:,vox),modelspec); \n lesiondataout(:,vox) = resids + repmat(B(1),size(resids));\n Bouts(:,vox) = B;\n end\nend\n\nsvrlsm_waitbar(parameters.waitbar,0,'') % clear the waitbar\n\nvariables.lesion_nuisance_model_betas = Bouts;\nvariables.lesion_dat2 = lesiondataout;\n\n% Parallel batch helper function for parallelizing the lesion nuisance model\nfunction [Bouts,lesiondataout] = parallel_lesion_batch_fcn(lesiondata,modelspec)\n for vox = 1 : size(lesiondata,2) % run of the mill loop now...\n [B,~,resids] = regress(lesiondata(:,vox),modelspec);\n lesiondataout(:,vox) = resids + repmat(B(1),size(resids));\n Bouts(:,vox) = B;\n end\n \n% old parallelized version without batch:\n% parfor vox = 1 : size(variables.lesion_dat,2)\n% check_for_interrupt(parameters)\n% [B,~,resids] = regress(lesiondata(:,vox),modelspec);\n% lesiondataout(:,vox) = resids + repmat(B(1),size(resids));\n% Bouts(:,vox) = B;\n% end\n"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "write_nifti_hdr.m", "ext": ".m", "path": "svrlsmgui-master/functions/nifti/write_nifti_hdr.m", "size": 2762, "source_encoding": "utf_8", "md5": "82987cccd27d7f60b004bdbec61b6d24", "text": "function write_nifti_hdr(h, fname)\r\n\r\n% WRITE_NIFTI_HDR Write NIFTI header\r\n%\r\n% WRITE_NIFTI_HDR(H, FNAME) writes the header structure H into the file\r\n% FNAME. The validity of H is not checked.\r\n\r\n[pathstr, basename, ext] = fileparts(fname);\r\nif strcmp(ext, '.img')\r\n fname = fullfile(pathstr, [basename '.hdr']);\r\nend\r\n\r\nif strcmp(ext, '.nii') && exist(fname, 'file')\r\n fid = fopen(fname, 'r+');\r\nelse\r\n fid = fopen(fname, 'w');\r\nend\r\n\r\nfwrite(fid, h.sizeof_hdr(1), 'int32');\r\nfwrite(fid, padchar(h.data_type, 10), 'char');\r\nfwrite(fid, padchar(h.db_name, 18), 'char');\r\nfwrite(fid, h.extents(1), 'int32');\r\nfwrite(fid, h.session_error(1), 'int16');\r\nfwrite(fid, h.regular(1), 'char');\r\nfwrite(fid, h.dim_info(1), 'char');\r\n\r\nfwrite(fid, h.dim(1:8), 'int16');\r\nfwrite(fid, h.intent_p1(1), 'float32');\r\nfwrite(fid, h.intent_p2(1), 'float32');\r\nfwrite(fid, h.intent_p3(1), 'float32');\r\nfwrite(fid, h.intent_code(1), 'int16');\r\nfwrite(fid, h.datatype(1), 'int16');\r\nfwrite(fid, h.bitpix(1), 'int16');\r\nfwrite(fid, h.slice_start(1), 'int16');\r\nfwrite(fid, h.pixdim(1:8), 'float32');\r\nfwrite(fid, h.vox_offset(1), 'float32');\r\nfwrite(fid, h.scl_slope(1), 'float32');\r\nfwrite(fid, h.scl_inter(1), 'float32');\r\nfwrite(fid, h.slice_end(1), 'int16');\r\nfwrite(fid, h.slice_code(1), 'uchar');\r\nfwrite(fid, h.xyzt_units(1), 'uchar');\r\nfwrite(fid, h.cal_max(1), 'float32');\r\nfwrite(fid, h.cal_min(1), 'float32');\r\nfwrite(fid, h.slice_duration(1), 'float32');\r\nfwrite(fid, h.toffset(1), 'float32');\r\nfwrite(fid, h.glmax(1), 'int32');\r\nfwrite(fid, h.glmin(1), 'int32');\r\n\r\nfwrite(fid, padchar(h.descrip, 80), 'char');\r\nfwrite(fid, padchar(h.aux_file, 24), 'char');\r\nfwrite(fid, h.qform_code(1), 'int16');\r\nfwrite(fid, h.sform_code(1), 'int16');\r\nfwrite(fid, h.quatern_b(1), 'float32');\r\nfwrite(fid, h.quatern_c(1), 'float32');\r\nfwrite(fid, h.quatern_d(1), 'float32');\r\nfwrite(fid, h.qoffset_x(1), 'float32');\r\nfwrite(fid, h.qoffset_y(1), 'float32');\r\nfwrite(fid, h.qoffset_z(1), 'float32');\r\nfwrite(fid, h.srow_x(1:4), 'float32');\r\nfwrite(fid, h.srow_y(1:4), 'float32');\r\nfwrite(fid, h.srow_z(1:4), 'float32');\r\nfwrite(fid, padchar(h.intent_name, 16), 'char');\r\nfwrite(fid, padchar(h.magic, 4), 'char');\r\n\r\nif h.qform_code == 0 && h.sform_code == 0 && isfield(h, 'originator') && ...\r\n all(h.originator(1:3) >= 1) && all(h.originator(1:3) <= h.dim(2:4))\r\n warning('Writing ANALYZE originator over the top of NIFTI orientation fields');\r\n fseek(fid, 253, 'bof');\r\n fwrite(fid, h.originator, 'int16')'; % over the top of qform_code and the following few fields\r\nend\r\n\r\nfclose(fid);\r\n\r\n\r\nfunction outstr = padchar(instr, n)\r\n\r\nif length(instr) <= n\r\n outstr = char(zeros(1, n));\r\n outstr(1:length(instr)) = instr;\r\nelse\r\n outstr = instr(1:n);\r\nend\r\n"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "analyze_to_nifti.m", "ext": ".m", "path": "svrlsmgui-master/functions/nifti/analyze_to_nifti.m", "size": 1235, "source_encoding": "utf_8", "md5": "18757b17671315605f0fda9ab06b7129", "text": "function analyze_to_nifti(fname)\r\n\r\n% ANALYZE_TO_NIFTI(FNAME)\r\n%\r\n% Converts the ANALYZE image FNAME to .nii (one file) format. If no FNAME\r\n% is provided, converts every .img file in the current directory.\r\n%\r\n% The header information is set up based on what SPM5 does if you reslice.\r\n% The origin is set to the center.\r\n\r\n\r\nif nargin == 0\r\n d = dir('*.img');\r\n if length(d) >= 1\r\n for i = 1:length(d)\r\n fprintf('%s\\n', d(i).name);\r\n do(d(i).name);\r\n end\r\n end\r\nelse\r\n do(fname);\r\nend\r\n\r\n\r\nfunction do(fname)\r\n\r\n[hdr, img] = read_nifti(fname);\r\n\r\nnhdr = make_nifti_hdr(hdr.datatype, hdr.dim(2:4), abs(hdr.pixdim(2:4)));\r\n\r\nx = (nhdr.dim(2) / 2 - 0.5) * nhdr.pixdim(2);\r\ny = (nhdr.dim(3) / 2 - 0.5) * nhdr.pixdim(3);\r\nz = (nhdr.dim(4) / 2 - 0.5) * nhdr.pixdim(4);\r\n\r\nnhdr.pixdim(1) = -1;\r\nnhdr.vox_offset = 352;\r\nnhdr.qform_code = 2;\r\nnhdr.sform_code = 2;\r\nnhdr.quatern_b = 0;\r\nnhdr.quatern_c = 1;\r\nnhdr.quatern_d = 0;\r\nnhdr.qoffset_x = x;\r\nnhdr.qoffset_y = -y;\r\nnhdr.qoffset_z = -z;\r\nnhdr.srow_x = [-nhdr.pixdim(2) 0 0 x];\r\nnhdr.srow_y = [0 nhdr.pixdim(3) 0 -y];\r\nnhdr.srow_z = [0 0 nhdr.pixdim(4) -z];\r\nnhdr.magic = 'n+1 ';\r\nnhdr.magic(4) = 0;\r\n\r\nfname((end - 2):end) = 'nii';\r\n\r\nwrite_nifti(nhdr, img, fname);\r\n"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "nifti2jpg.m", "ext": ".m", "path": "svrlsmgui-master/functions/nifti/nifti2jpg.m", "size": 1178, "source_encoding": "utf_8", "md5": "534ca9fc2dd45fab241045c7a7d29e53", "text": "function nifti2jpg(fname, skip, flip)\r\n\r\nif nargin < 2\r\n skip = 1;\r\nend\r\nif nargin < 3\r\n flip = [0 0 1; 1 0 1]; % works for NIC T1s after dicom2analyze\r\nend\r\n\r\n[hdr, img] = read_nifti(fname);\r\n\r\nvals = img(:);\r\nvals = sort(vals(1:10:end));\r\nanatmin = vals(round(length(vals) * 10 / 100));\r\nanatmax = vals(round(length(vals) * 95 / 100));\r\n\r\nfor o = 1:3\r\n for i = 1:skip:hdr.dim(o + 1)\r\n if o == 1\r\n slice = squeeze(img(i, :, :));\r\n elseif o == 2\r\n slice = squeeze(img(:, i, :));\r\n else\r\n slice = squeeze(img(:, :, i));\r\n end\r\n if flip(1, o)\r\n slice = slice';\r\n end\r\n if flip(2, o)\r\n slice = flipud(slice);\r\n end\r\n slice = scaleimg(slice, anatmin, anatmax, 0.15, 1);\r\n imwrite(slice, sprintf('%d_%03d.jpg', o, i), 'JPEG', 'Quality', 50);\r\n end\r\nend\r\n\r\nfunction sd = scaleimg(img, imin, imax, omin, omax)\r\n\r\n% scales an image such that values between imin and imax now lie between\r\n% omin and omax. values above and below are clipped.\r\n\r\nsd = omin + (img - imin) / (imax - imin) * (omax - omin);\r\nsd(sd < omin) = omin;\r\nsd(sd > omax) = omax;\r\n"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "run_beta_PMU_old.m", "ext": ".m", "path": "svrlsmgui-master/functions/unused/run_beta_PMU_old.m", "size": 24927, "source_encoding": "utf_8", "md5": "245c8f57bb62a9aebd3d04d065c89441", "text": "function variables = run_beta_PMU(parameters, variables, cmd, beta_map,handles)\n options = handles.options;\n zerostemplate = zeros(variables.vo.dim(1:3)); % make a zeros template....\n \n ori_beta_val = beta_map(variables.m_idx).'; % Original observed beta values.\n tic;\n \n if parameters.parallelize % try to parfor it...\n handles = UpdateProgress(handles,'Computing beta map permutations (parallelized)...',1);\n sparseLesionData = sparse(variables.lesion_dat);\n lidx = variables.l_idx;\n midx = variables.m_idx;\n betascale = variables.beta_scale;\n \n % create permutations beforehand.\n permdata = nan(numel(variables.one_score),parameters.PermNumVoxelwise); % each COL will be a permutation.\n npermels = size(permdata,1);\n for r = 1 : size(permdata,2) % each col...\n permdata(:,r) = variables.one_score(randperm(npermels));\n end\n \n outpath = variables.output_folder.clusterwise;\n totalperms = parameters.PermNumVoxelwise;\n uselibsvm = parameters.useLibSVM;\n parfor PermIdx=1:parameters.PermNumVoxelwise\n check_for_interrupt(parameters)\n trial_score = permdata(:,PermIdx); % extract the row of permuted data.\n if uselibsvm\n m = svmtrain(trial_score,sparseLesionData,cmd); %#ok\n alpha = m.sv_coef';\n SVs = m.SVs;\n else\n [m,~,~] = ComputeMatlabSVRLSM(parameters,variables);\n alpha = m.Alpha'; \n SVs = m.SupportVectors;\n end\n \n pmu_beta_map = betascale * alpha * SVs;\n tmp_map = zerostemplate; % zeros(nx, ny, nz);\n tmp_map(lidx) = pmu_beta_map;\n pmu_beta_map = tmp_map(midx).';\n \n % Save this permutation....\n fileID = fopen(fullfile(outpath,['pmu_beta_map_' num2str(PermIdx) '_of_' num2str(totalperms) '.bin']),'w');\n fwrite(fileID, pmu_beta_map,'single');\n fclose(fileID);\n end\n \n % now get all those individual files into one big file that we can memmap to.\n outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);\n fileID = fopen(outfname_big,'w');\n \n for PermIdx=1:parameters.PermNumVoxelwise\n check_for_interrupt(parameters)\n curpermfilepath = fullfile(outpath,['pmu_beta_map_' num2str(PermIdx) '_of_' num2str(totalperms) '.bin']);\n cur_perm_data = memmapfile(curpermfilepath,'Format','single');\n fwrite(fileID, cur_perm_data.Data,'single');\n clear cur_perm_data; % remove memmap from memory.\n delete(curpermfilepath); % delete it since we don't want the data hanging around...\n end\n fclose(fileID); % close big file\n \n else\n handles = UpdateProgress(handles,'Computing beta map permutations (not parallelized)...',1);\n % This is where we'll save our GBs of permutation data output...\n outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);\n fileID = fopen(outfname_big,'w');\n\n h = waitbar(0,'Computing beta permutations...','Tag','WB');\n for PermIdx=1:parameters.PermNumVoxelwise\n check_for_interrupt(parameters)\n\n % random permute subjects order\n loc = randperm(length(variables.one_score));\n trial_score = variables.one_score(loc);\n \n % Which package to use to compute SVM solution\n if parameters.useLibSVM\n m = svmtrain(trial_score,sparse(variables.lesion_dat),cmd); %#ok\n else\n if PermIdx == 1 \n variables.orig_one_score = variables.one_score;\n end\n \n variables.one_score = trial_score;\n \n [m,~,~] = ComputeMatlabSVRLSM(parameters,variables);\n \n if PermIdx == parameters.PermNumVoxelwise % put it back after we've done all permutations...\n variables.one_score = variables.orig_one_score;\n end\n end\n \n % compute the beta map\n if parameters.useLibSVM\n alpha = m.sv_coef';\n SVs = m.SVs;\n else % MATLAB's version.\n alpha = m.Alpha'; \n SVs = m.SupportVectors;\n end\n pmu_beta_map = variables.beta_scale * alpha*SVs;\n \n \n tmp_map = zerostemplate;\n tmp_map(variables.l_idx) = pmu_beta_map;\n pmu_beta_map = tmp_map(variables.m_idx).';\n \n % Save this permutation....\n fwrite(fileID, pmu_beta_map,'single');\n \n % Display progress.\n elapsed_time = toc;\n remain_time = round(elapsed_time * (parameters.PermNumVoxelwise - PermIdx)/(PermIdx));\n remain_time_h = floor(remain_time/3600);\n remain_time_m = floor((remain_time - remain_time_h*3600)/60);\n remain_time_s = floor(remain_time - remain_time_h*3600 - remain_time_m*60);\n prompt_str = sprintf(['Permutation ', num2str(PermIdx), '/', num2str(parameters.PermNumVoxelwise), ': Est. remaining time: ', num2str(remain_time_h), ' h ', num2str(remain_time_m), ' m ' num2str(remain_time_s), 's\\n']);\n waitbar(PermIdx/parameters.PermNumVoxelwise,h,prompt_str) % show progress.\n \n end\n \n close(h) % close the waitbar...\n fclose(fileID); % close the pmu data output file.\n end\n \n % Read in gigantic memory mapped file... no matter whether we parallelized or not.\n all_perm_data = memmapfile(outfname_big,'Format','single'); % does the single precision hurt the analysis?\n\n %% FWE cluster correction based on permutation analysis\n voxelwise_p_value = parameters.voxelwise_p;\n pos_thresh_index = median([1 round((1-voxelwise_p_value) * parameters.PermNumVoxelwise) parameters.PermNumVoxelwise]); % row 9500 in 10000 permutations.\n pos_beta_map_cutoff = nan(1,length(variables.m_idx));\n one_tail_pos_alphas = nan(1,length(variables.m_idx));\n\n neg_thresh_index = median([1 round(voxelwise_p_value * parameters.PermNumVoxelwise) parameters.PermNumVoxelwise]); % so row 500 in 10000 permutations\n neg_beta_map_cutoff = nan(1,length(variables.m_idx));\n one_tail_neg_alphas = nan(1,length(variables.m_idx));\n\n two_tailed_thresh_index_neg = median([1 round(((voxelwise_p_value/2)) * parameters.PermNumVoxelwise) parameters.PermNumVoxelwise]); % row 250 in 10000 permutations.\n two_tailed_thresh_index = median([1 round((1-(voxelwise_p_value/2)) * parameters.PermNumVoxelwise) parameters.PermNumVoxelwise]); % row 9750 in 10000 permutations.\n two_tailed_beta_map_cutoff_pos = nan(1,length(variables.m_idx));\n two_tailed_beta_map_cutoff_neg = nan(1,length(variables.m_idx));\n twotails_alphas = nan(1,length(variables.m_idx));\n\nif parameters.parallelize % try to parfor it...\n handles = UpdateProgress(handles,'Sorting null betas for each lesioned voxel in the dataset (parallelized).',1);\n L = length(variables.m_idx);\n tails = parameters.tails; % so not a broadcast variable.\n Opt1 = options.hypodirection{1};\n Opt2 = options.hypodirection{2};\n Opt3 = options.hypodirection{3};\n parfor col = 1 : length(variables.m_idx) \n check_for_interrupt(parameters)\n curcol = extractSlice(all_perm_data,col,L); % note this is a function at the bottom of this file..\n observed_beta = ori_beta_val(col); % original observed beta value.\n curcol_sorted = sort(curcol); % smallest values at the top..\n switch tails\n case Opt1\n one_tail_pos_alphas(col) = sum(observed_beta > curcol_sorted)/numel(curcol_sorted); % percent of values observed_beta is greater than.\n pos_beta_map_cutoff(col) = curcol_sorted(pos_thresh_index); % so the 9500th at p of 0.05 on 10,000 permutations\n case Opt2\n one_tail_neg_alphas(col) = sum(observed_beta < curcol_sorted)/numel(curcol_sorted); % percent of values observed_beta is greater than.\n neg_beta_map_cutoff(col) = curcol_sorted(neg_thresh_index); % so the 500th at p of 0.05 on 10,000 permutations\n case Opt3\n two_tailed_beta_map_cutoff_pos(col) = curcol_sorted(two_tailed_thresh_index); % 250...\n two_tailed_beta_map_cutoff_neg(col) = curcol_sorted(two_tailed_thresh_index_neg); % 9750...\n twotails_alphas(col) = sum(abs(observed_beta) > abs(curcol_sorted))/numel(curcol_sorted); % percent of values observed_beta is greater than.\n end\n end\nelse \n handles = UpdateProgress(handles,'Sorting null betas for each lesioned voxel in the dataset (not parallelized).',1);\n h = waitbar(0,sprintf('Sorting null betas for each lesioned voxel in the dataset (N = %d).\\n',length(variables.m_idx)),'Tag','WB');\n dataRef = all_perm_data.Data; % will this eliminate some overhead \n L = length(variables.m_idx);\n for col = 1 : length(variables.m_idx) \n check_for_interrupt(parameters)\n curcol = dataRef(col:L:end); % index out each column using skips the length of the data...\n observed_beta = ori_beta_val(col); % original observed beta value.\n curcol_sorted = sort(curcol); % smallest values at the top..\n \n % hist(curcol_sorted)\n% histogram(curcol_sorted,35)\n% hold on\n% title(num2str(col))\n% pause\n % fitdists{col} = fitdist(\n % pd = fitdist(x,'Kernel','Kernel','epanechnikov')\n\n \n% p_vec=nan(size(curcol_sorted)); % allocate space\n% all_ind = 1:numel(curcol_sorted); % we'll reuse this vector\n% for i = all_ind % for each svr beta value in the vector\n% ind_to_compare = setdiff(all_ind,i);\n% p_vec(i) = 1 - mean(curcol_sorted(i) < curcol_sorted(ind_to_compare));\n% end\n% disp([num2str(i) ' of ' num2str(numel(p_vec)) ' - observed svrB = ' num2str(observed_beta)])\n% [numel(unique(curcol_sorted)) numel(unique(p_vec))]\n\n\n % Compute beta cutoff values and a pvalue map for the observed betas.\n switch parameters.tails\n case options.hypodirection{1} % 'one_positive'\n one_tail_pos_alphas(col) = sum(observed_beta > curcol_sorted)/numel(curcol_sorted); % percent of values observed_beta is greater than.\n pos_beta_map_cutoff(col) = curcol_sorted(pos_thresh_index); % so the 9500th at p of 0.05 on 10,000 permutations\n case options.hypodirection{2} %'one_negative'\n one_tail_neg_alphas(col) = sum(observed_beta < curcol_sorted)/numel(curcol_sorted); % percent of values observed_beta is greater than.\n neg_beta_map_cutoff(col) = curcol_sorted(neg_thresh_index); % so the 500th at p of 0.05 on 10,000 permutations\n case options.hypodirection{3} % 'two'\n two_tailed_beta_map_cutoff_pos(col) = curcol_sorted(two_tailed_thresh_index); % 250...\n two_tailed_beta_map_cutoff_neg(col) = curcol_sorted(two_tailed_thresh_index_neg); % 9750...\n twotails_alphas(col) = sum(abs(observed_beta) > abs(curcol_sorted))/numel(curcol_sorted); % percent of values observed_beta is greater than.\n end \n waitbar(col/L,h) % show progress.\n end\n close(h)\n\nend\n %% Construct volumes of the solved alpha values and write them out - and write out beta cutoff maps, too\n switch parameters.tails\n case options.hypodirection{1} % 'one_positive' % One-tailed positive tail...\n thresholded_pos = zerostemplate; \n if parameters.invert_p_map_flag % it's already inverted\n thresholded_pos(variables.m_idx) = one_tail_pos_alphas; \n % Write unthresholded P-map for the positive tail \n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values (inv).nii');\n svrlsmgui_write_vol(variables.vo, thresholded_pos);\n % Now write out the thresholded P-map for the positive tail \n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');\n thresholded_pos(thresholded_pos < (1-parameters.voxelwise_p)) = 0; % zero out sub-threshold p value voxels (note the 1-p)\n svrlsmgui_write_vol(variables.vo, thresholded_pos);\n else\n thresholded_pos(variables.m_idx) = 1 - one_tail_pos_alphas;\n % Write unthresholded P-map for the positive tail \n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values.nii');\n svrlsmgui_write_vol(variables.vo, thresholded_pos);\n % Now write out the thresholded P-map for the positive tail \n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values.nii');\n thresholded_pos(thresholded_pos > parameters.voxelwise_p) = 0; % zero out voxels whose values are greater than p \n svrlsmgui_write_vol(variables.vo, thresholded_pos);\n end\n \n % Now write out beta cutoff map.\n thresholded_pos = zerostemplate; % zeros(nx,ny,nz); % reserve space\n thresholded_pos(variables.m_idx) = pos_beta_map_cutoff; % put the 95th percentil beta values back into the lesion indices in a full volume\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (positive tail).nii');\n svrlsmgui_write_vol(variables.vo, thresholded_pos);\n \n case options.hypodirection{2} % 'one_negative' % One-tailed negative tail...\n thresholded_neg = zerostemplate;\n if parameters.invert_p_map_flag % it's already inverted...\n thresholded_neg(variables.m_idx) = one_tail_neg_alphas;\n % write out unthresholded negative p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values (inv).nii');\n svrlsmgui_write_vol(variables.vo, thresholded_neg);\n % write out thresholded negative p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');\n thresholded_neg(thresholded_neg < (1-parameters.voxelwise_p)) = 0; % zero out subthreshold p value voxels (note 1-p)\n svrlsmgui_write_vol(variables.vo, thresholded_neg);\n else\n thresholded_neg(variables.m_idx) = 1 - one_tail_neg_alphas;\n % write out unthresholded negative p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values.nii');\n svrlsmgui_write_vol(variables.vo, thresholded_neg);\n % write out thresholded negative p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values.nii');\n thresholded_neg(thresholded_neg > parameters.voxelwise_p) = 0; % zero out voxels whose values are greater than p \n svrlsmgui_write_vol(variables.vo, thresholded_neg);\n end\n \n % Now beta cutoff map for one-taled negative tail...\n thresholded_neg = zerostemplate; % reserve space;\n thresholded_neg(variables.m_idx) = neg_beta_map_cutoff; % put the 5th percentil beta values back into the lesion indices in a full volume\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (negative tail).nii');\n svrlsmgui_write_vol(variables.vo, thresholded_neg);\n \n case options.hypodirection{3} %'two'% Both tails..\n thresholded_twotails = zerostemplate;% reserve space;\n if parameters.invert_p_map_flag % it's already inverted...\n thresholded_twotails(variables.m_idx) = twotails_alphas;\n % write out unthresholded p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values (inv).nii');\n svrlsmgui_write_vol(variables.vo, thresholded_twotails);\n % write out thresholded p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');\n thresholded_twotails(thresholded_twotails < (1-(parameters.voxelwise_p/2))) = 0; % zero out subthreshold p value voxels (note 1-p)\n svrlsmgui_write_vol(variables.vo, thresholded_twotails);\n else\n thresholded_twotails(variables.m_idx) = 1 - twotails_alphas;\n % write out unthresholded p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values.nii');\n svrlsmgui_write_vol(variables.vo, thresholded_twotails);\n % write out thresholded p map\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');\n thresholded_twotails(thresholded_twotails > (parameters.voxelwise_p/2)) = 0; % zero out supra-alpha p value voxels\n svrlsmgui_write_vol(variables.vo, thresholded_twotails);\n end\n \n % Beta cutoff maps\n % Two-tailed upper tail\n thresholded_twotail_upper = zerostemplate; %zeros(nx,ny,nz); % reserve space;\n thresholded_twotail_upper(variables.m_idx) = two_tailed_beta_map_cutoff_pos; % put the 2.5th percentil beta values back into the lesion indices in a full volume\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (two tail, upper).nii');\n svrlsmgui_write_vol(variables.vo, thresholded_twotail_upper);\n \n % Two-tailed lower tail\n thresholded_twotail_lower = zerostemplate; % zeros(nx,ny,nz); % reserve space;\n thresholded_twotail_lower(variables.m_idx) = two_tailed_beta_map_cutoff_neg; % put the 2.5th percentil beta values back into the lesion indices in a full volume\n variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (two tail, lower).nii');\n svrlsmgui_write_vol(variables.vo, thresholded_twotail_lower);\n end\n \n % Now for each permuted beta map, apply the beta mask and determine largest surviving cluster.\n \n h = waitbar(0,'Applying voxelwise beta mask to null data and noting largest null clusters...','Tag','WB');\n \n % Reconstruct the volumes so we can threshold and examine cluster sizes\n all_max_cluster_sizes = nan(parameters.PermNumClusterwise,1); % reserve space.\n \n if parameters.PermNumClusterwise > parameters.PermNumVoxelwise, error('Cannot sample more cluster permutations than have been generated by the voxelwise permutation procedure.'); end\n \n handles = UpdateProgress(handles,'Applying voxelwise beta mask to null data and noting largest null clusters...',1);\n\n for f = 1 : parameters.PermNumVoxelwise % go through each frame of generated betas in the null data...\n waitbar(f/parameters.PermNumVoxelwise,h) % show progress.\n check_for_interrupt(parameters)\n\n frame_length = length(variables.m_idx);\n frame_start_index = 1+((f-1)*frame_length); % +1 since not zero indexing\n frame_end_index = (frame_start_index-1)+frame_length; % -1 so we are not 1 too long.\n relevant_data_frame = all_perm_data.Data(frame_start_index:frame_end_index); % extract the frame\n templatevol = zerostemplate; % zeros(nx,ny,nz); % reserve space\n templatevol(variables.m_idx) = relevant_data_frame; % put the beta values back in indices.\n \n if parameters.SavePreThresholdedPermutations % then write out raw voxel NON-thresholded images for this permutation.\n variables.vo.fname = fullfile(variables.output_folder.clusterwise,['UNthreshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumVoxelwise) '.nii']);\n svrlsmgui_write_vol(variables.vo, templatevol);\n end\n \n switch parameters.tails\n case options.hypodirection{1} \n pos_threshed = templatevol .* (templatevol>=thresholded_pos); % elementwise greater than operator to threshold positive tail of test betas\n case options.hypodirection{2} \n neg_threshed = templatevol .* (templatevol<=thresholded_neg); % elementwise less than operator to threshold negative tail of test betas.\n case options.hypodirection{3} % Now build a two-tailed thresholded version\n threshmask = and(templatevol > 0,templatevol >= thresholded_twotail_upper) | and(templatevol < 0,templatevol <= thresholded_twotail_lower);\n twotail_threshed = templatevol .* threshmask; % mask the two-tailed beta mask for this null data...\n end\n \n if parameters.SavePostVoxelwiseThresholdedPermutations % then write out raw voxel thresholded images for this permutation.\n switch parameters.tails\n case options.hypodirection{1} % 'one_positive'\n variables.vo.fname = fullfile(variables.output_folder.clusterwise,['pos_threshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumVoxelwise) '.nii']);\n svrlsmgui_write_vol(variables.vo, pos_threshed);\n case options.hypodirection{2} %'one_negative'\n variables.vo.fname = fullfile(variables.output_folder.clusterwise,['neg_threshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumVoxelwise) '.nii']);\n svrlsmgui_write_vol(variables.vo, neg_threshed);\n case options.hypodirection{3} %'two'\n variables.vo.fname = fullfile(variables.output_folder.clusterwise,['twotail_threshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumVoxelwise) '.nii']);\n svrlsmgui_write_vol(variables.vo, twotail_threshed);\n end\n end\n \n if f <= parameters.PermNumClusterwise\n switch parameters.tails\n case options.hypodirection{1}\n permtype='pos';\n thresholded_mask=pos_threshed;\n case options.hypodirection{2}\n permtype='neg';\n thresholded_mask=neg_threshed;\n case options.hypodirection{3}\n permtype='twotail';\n thresholded_mask=twotail_threshed;\n end\n\n testvol_thresholded = thresholded_mask; % now evaluate the surviving voxels for clusters...\n CC = bwconncomp(testvol_thresholded, 6);\n largest_cluster_size = max(cellfun(@numel,CC.PixelIdxList(1,:))); % max val for numels in each cluster object found\n if isempty(largest_cluster_size)\n largest_cluster_size = 0;\n else % threshold the volume and write it out.\n if parameters.SavePostClusterwiseThresholdedPermutations % then save them...\n out_map = remove_scatter_clusters(testvol_thresholded, largest_cluster_size-1);\n variables.vo.fname = fullfile(variables.output_folder.clusterwise,[permtype '_threshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumClusterwise) '_largest_cluster.nii']);\n svrlsmgui_write_vol(variables.vo, out_map);\n end\n end\n all_max_cluster_sizes(f) = largest_cluster_size; % record...\n end\n end\n close(h)\n\n % Save the resulting cluster lists\n fname = 'Largest clusters.mat';\n save(fullfile(variables.output_folder.clusterwise,fname),'all_max_cluster_sizes');\n \n handles = UpdateProgress(handles,'Cleaning up null data...',1);\n \n % Clean up as necessary\n if ~parameters.SavePermutationData\n fclose all;\n delete(outfname_big); % delete the monster bin file with raw permutation data in it.\n if exist(outfname_big,'file') % if it still exists...\n warning('Was not able to delete large binary file with raw permutation data in it. This file can be quite large, so you may want to manually clean up the file and adjust your permissions so that this is not a problem in the future.')\n end\n end\n \n% for parallelization to eliminate large overhead transfering to and from workers\nfunction sliceData = extractSlice(all_perm_data,col,L)\n sliceData = all_perm_data.Data(col:L:end);"} +{"plateform": "github", "repo_name": "atdemarco/svrlsmgui-master", "name": "crossval_diagnostics.m", "ext": ".m", "path": "svrlsmgui-master/functions/unused/crossval_diagnostics.m", "size": 3065, "source_encoding": "utf_8", "md5": "02ba5b4ce471ec375db0f8ee55bbdfad", "text": "function varargout = crossval_diagnostics(varargin)\n% CROSSVAL_DIAGNOSTICS MATLAB code for crossval_diagnostics.fig\n% CROSSVAL_DIAGNOSTICS, by itself, creates a new CROSSVAL_DIAGNOSTICS or raises the existing\n% singleton*.\n%\n% H = CROSSVAL_DIAGNOSTICS returns the handle to a new CROSSVAL_DIAGNOSTICS or the handle to\n% the existing singleton*.\n%\n% CROSSVAL_DIAGNOSTICS('CALLBACK',hObject,eventData,handles,...) calls the local\n% function named CALLBACK in CROSSVAL_DIAGNOSTICS.M with the given input arguments.\n%\n% CROSSVAL_DIAGNOSTICS('Property','Value',...) creates a new CROSSVAL_DIAGNOSTICS or raises the\n% existing singleton*. Starting from the left, property value pairs are\n% applied to the GUI before crossval_diagnostics_OpeningFcn gets called. An\n% unrecognized property name or invalid value makes property application\n% stop. All inputs are passed to crossval_diagnostics_OpeningFcn via varargin.\n%\n% *See GUI Options on GUIDE's Tools menu. Choose \"GUI allows only one\n% instance to run (singleton)\".\n%\n% See also: GUIDE, GUIDATA, GUIHANDLES\n\n% Edit the above text to modify the response to help crossval_diagnostics\n\n% Last Modified by GUIDE v2.5 21-Feb-2018 11:09:25\n\n% Begin initialization code - DO NOT EDIT\ngui_Singleton = 1;\ngui_State = struct('gui_Name', mfilename, ...\n 'gui_Singleton', gui_Singleton, ...\n 'gui_OpeningFcn', @crossval_diagnostics_OpeningFcn, ...\n 'gui_OutputFcn', @crossval_diagnostics_OutputFcn, ...\n 'gui_LayoutFcn', [] , ...\n 'gui_Callback', []);\nif nargin && ischar(varargin{1})\n gui_State.gui_Callback = str2func(varargin{1});\nend\n\nif nargout\n [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});\nelse\n gui_mainfcn(gui_State, varargin{:});\nend\n% End initialization code - DO NOT EDIT\n\n\n% --- Executes just before crossval_diagnostics is made visible.\nfunction crossval_diagnostics_OpeningFcn(hObject, eventdata, handles, varargin)\n% This function has no output args, see OutputFcn.\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n% varargin command line arguments to crossval_diagnostics (see VARARGIN)\n\n% Choose default command line output for crossval_diagnostics\nhandles.output = hObject;\n\n% Update handles structure\nguidata(hObject, handles);\n\n% UIWAIT makes crossval_diagnostics wait for user response (see UIRESUME)\n% uiwait(handles.figure1);\n\n\n% --- Outputs from this function are returned to the command line.\nfunction varargout = crossval_diagnostics_OutputFcn(hObject, eventdata, handles) \n% varargout cell array for returning output args (see VARARGOUT);\n% hObject handle to figure\n% eventdata reserved - to be defined in a future version of MATLAB\n% handles structure with handles and user data (see GUIDATA)\n\n% Get default command line output from handles structure\nvarargout{1} = handles.output;\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "eventDetector.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/eventDetection/eventDetector.m", "size": 15135, "source_encoding": "utf_8", "md5": "64d69083f3f62775510da94cfc8f656b", "text": "function varargout = eventDetector(ROIStats, stim, ROISet, eventDetectMethod, frameRate, bpfilter, psConfig, saveName)\n% event detection function - wrapper to different event detection algorithms\n% input: structure created by GetRoiStats (*_RoiStats)\ndbgLevel = 2;\n% required folders\nfolderList = {'Projects/EventDetect','Projects/TwoPhotonAnalyzer'};\naddFolders2Path(folderList,1);\nmaxRuns = Inf; % for testing\n% maxRuns = 2; % for testing\ndoCaTracesPlot = 1;\ndoPlotEvents = doCaTracesPlot && 1; %%#ok\ndoRasterPlot = 1;\ndoStimEventRasterPlot = 1;\n% doPsStimPlot = 1;\ndoEventCountPlot = 0;\ndoEventDetection = 1;\no(' #eventDetector: method: \"%s\", maxRuns = %d ...', eventDetectMethod, maxRuns, 1, dbgLevel);\n%% Event detection parameters\n[config, V, P] = getDefaultParameters(eventDetectMethod, frameRate); %%#ok\no(' #eventDetector: event detection parameters configured.', 3, dbgLevel);\n%% Event detection\n% event detection on roiStats\n% % last row is neuropil, remove it\n% allDFFData(end, :) = [];\n% init sizes of data set\nnROIs = size(ROIStats, 1);\nnRuns = size(ROIStats, 2);\nnFrames = size(ROIStats{1, 1}, 2);\n% only process requested runs\nif nRuns > maxRuns;\n nRuns = maxRuns;\n ROIStats(:, maxRuns + 1 : end) = [];\nend\n\no(' #eventDetector: variables initialized.', 3, dbgLevel);\no(' #eventDetector: starting event detection ... ', 2, dbgLevel);\neventDetectStartTime = tic;\neventData = cell(size(ROIStats));\nresiduals = cell(size(ROIStats));\nmodels = cell(size(ROIStats));\neventMatAllRuns = zeros(nROIs, nRuns * size(ROIStats{1, 1}, 2));\nstimVectorAllRuns = zeros(1, nRuns * size(ROIStats{1, 1}, 2));\n% outerDffData = ROIStats;\nnRunsWithError = 0;\nnTotEvents = 0;\n% nRuns = 1; o('/!\\\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);\n% for iRun = 1 : nRuns;\nnRuns = 1; o('/!\\\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);\nfor iRun = 7;\n try\n% ROIStats = outerDffData;\n startIndex = (iRun - 1) * nFrames + 1;\n endIndex = iRun * nFrames;\n eventDetect = config.EventDetect;\n o(' #eventDetector: run %d/%d, %d rois...', iRun, nRuns, nROIs, 4, dbgLevel);\n if size(stim{iRun}, 2) ~= endIndex - startIndex + 1;\n o(' #eventDetector: run %d/%d, %d rois: skip for bad size.', iRun, nRuns, nROIs, 1, dbgLevel);\n continue;\n end;\n stimVectorAllRuns(startIndex : endIndex) = stim{iRun};\n eventDetect.rate = frameRate;\n% eventCounts = zeros(1, nROIs);\n% residuals = zeros(1, nROIs);\n currentEventMat = zeros(nROIs, nFrames);\n \n if doEventDetection;\n% parfor iROI = 1 : nROIs;\n% for iROI = 1 : nROIs;\n for iROI = 1 : 3;\n o(' #eventDetector: run %d/%d - roi %d/%d ...', iRun, nRuns, iROI, nROIs, 5, dbgLevel);\n caTrace = ROIStats{iROI, iRun};\n% caTrace = mpi_BandPassFilterTimeSeries(caTrace, 1 / frameRate, bpfilter.low, bpfilter.high); %#ok\n if isempty(caTrace);\n warning('eventDetector:caTraceEmpty', 'caTrace is empty!');\n continue;\n elseif isnan(caTrace);\n% warning('eventDetector:caTraceNaN', 'caTrace is NaN!');\n eventData{iROI, iRun} = nan(1, nFrames);\n continue;\n end;\n switch lower(eventDetectMethod)\n case 'fast_oopsi'\n oopsiOut = fast_oopsi(caTrace, V, P);\n oopsiOut(oopsiOut < config.EventDetect.oopsi_thr) = 0; %#ok\n currentEventMat(iROI, :) = oopsiOut';\n eventData{iROI, iRun} = oopsiOut';\n case 'peeling'\n% eventOut = doPeeling(eventDetect, caTrace);\n [~, ~, peelRes] = Peeling(caTrace, frameRate);\n residuals{iROI, iRun} = peelRes.peel;\n models{iROI, iRun} = peelRes.model;\n% eventCounts(iROI) = sum(peelRes.spiketrain); %%#ok\n% residualVector(iROI) = sum(abs(eventOut.data.peel)) / length(eventOut.data.peel);\n currentEventMat(iROI, :) = peelRes.spiketrain;\n eventData{iROI, iRun} = peelRes.spiketrain;\n end;\n nEventsFound = sum(currentEventMat(iROI, :));\n nTotEvents = nTotEvents + nEventsFound;\n o(' #eventDetector: run %d/%d - roi %d/%d done, %d event(s) found.', ...\n iRun, nRuns, iROI, nROIs, nEventsFound, 4, dbgLevel);\n end ;\n end;\n eventMatAllRuns(:, startIndex : endIndex) = currentEventMat;\n o(' #eventDetector: run %d/%d done.', iRun, nRuns, 3, dbgLevel);\n catch err;\n nRunsWithError = nRunsWithError + 1; %#ok\n o(' #eventDetector: problem in run %d/%d.', iRun, nRuns, 2, dbgLevel);\n rethrow(err);\n end;\nend;\neventDetectEndTime = toc(eventDetectStartTime);\n% PSTraceRoi = PsPlotAnalysisCellArray(ROIStats, stim, psConfig);\no(' #eventDetector: event detection done for %d runs (%d error(s), %d total events, %.2f sec).', ...\n nRuns, nRunsWithError, nTotEvents, eventDetectEndTime, 2, dbgLevel);\nif ~isempty(eventMatAllRuns) && nTotEvents > 0;\n o(' #eventDetector: extracting peri-stimulus events...', 3, dbgLevel);\n PSEventRoi = PsPlotAnalysis(eventMatAllRuns, stimVectorAllRuns, psConfig);\n config.PsPlotEventRoi = PSEventRoi;\n o(' #eventDetector: extracting peri-stimulus events done.', 2, dbgLevel);\nelse\n o(' #eventDetector: no events found (%d).', nTotEvents, 1, dbgLevel);\nend\n\no(' #eventDetector: moving to plotting section ...', 3, dbgLevel);\n%% Calcium DFF / DRR Plot - with events\nif doCaTracesPlot; % only plot if required\n o(' #eventDetector: plotting the calcium DFF (or DRR) Plot with events...', 2, dbgLevel); %#ok<*UNRCH>\n % go through each run\n% nRuns = 1; o('/!\\\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);\n% for iRun = 1 : nRuns;\n nRuns = 1; o('/!\\\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);\n for iRun = 7;\n o(' #eventDetector: plotting run %d/%d ...', iRun, nRuns, 4, dbgLevel);\n fig = plotROICaTracesWithEvent(iRun, saveName, ... % run number and figure name\n cell2mat(ROIStats(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix\n cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix\n stim{iRun}, ... % stimulus as a nFrames long vector\n ROISet, ... % name and coordinates of the rois\n frameRate, ... % frame rate\n bpfilter, ... % band-pass filter settings\n eventDetectMethod, ... % used detection method\n doPlotEvents); % tells whether to plot the events or not\n \n fig = plotROICaTracesWithEvent(iRun, saveName, ... % run number and figure name\n cell2mat(residuals(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix\n cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix\n stim{iRun}, ... % stimulus as a nFrames long vector\n ROISet, ... % name and coordinates of the rois\n frameRate, ... % frame rate\n [], ... % band-pass filter settings\n eventDetectMethod, ... % used detection method\n doPlotEvents); % tells whether to plot the events or not\n \n fig = plotROICaTracesWithEvent(iRun, saveName, ... % run number and figure name\n cell2mat(models(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix\n cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix\n stim{iRun}, ... % stimulus as a nFrames long vector\n ROISet, ... % name and coordinates of the rois\n frameRate, ... % frame rate\n [], ... % band-pass filter settings\n eventDetectMethod, ... % used detection method\n doPlotEvents); % tells whether to plot the events or not\n \n o(' #eventDetector: plotting run %d/%d done, saving...', iRun, nRuns, 4, dbgLevel);\n% set(fig, 'WindowStyle', 'docked');\n if doCaTracesPlot > 1;\n if doPlotEvents;\n saveName = sprintf('%s_ROICaTracesWithEvents_run%02d_%s', saveName, iRun, ...\n eventDetectMethod);\n else\n saveName = sprintf('%s_ROICaTracesWithoutEvents_run%02d_%s', saveName, iRun, ...\n eventDetectMethod);\n end;\n saveas(fig, saveName);\n saveas(fig, [saveName '.png']);\n close(fig);\n end;\n o(' #eventDetector: plotting & saving run %d/%d done.', iRun, nRuns, 3, dbgLevel);\n end\n o(' #eventDetector: plotting %d run(s) done.', nRuns, 2, dbgLevel);\nend;\n%% Event count plot\nif doEventCountPlot;\n o(' #eventDetector: plotting the event counts for ROI image...', 2, dbgLevel); %#ok<*UNRCH>\n fig = plotCountROIMap( ...\n eventCounts, ... % event counts for each ROI\n 256, 256, ... % dimensions of the frame\n ROISet(1 : end - 1, 2)); % the positions of the ROI\n %% TODO HARD CODED IMAGE DIMS\n if doEventCountPlot > 1;\n set(fig, 'WindowStyle', 'docked');\n saveas(fig, sprintf('%s_ROIEventCount_%s', saveName, eventDetectMethod));\n saveas(fig, sprintf('%s_ROIEventCount_%s.png', saveName, eventDetectMethod));\n close(fig);\n end;\n o(' #eventDetector: plotting the event counts for ROI image done.', 3, dbgLevel); %#ok<*UNRCH>\nend;\n%% Population stimulus event raster plot\nif doStimEventRasterPlot;\n o(' #eventDetector: plotting the peri-stimulus event raster plot ...', 2, dbgLevel); %#ok<*UNRCH>\n fig = plotStimEventRaster( ...\n 'PopRasterSinglePlot', ... % title of the plot\n PSEventRoi, ... % event counts around the stimulus\n stim{1}, ... % stimuli for extracting their 'name'\n psConfig.base, ... % number of frames looked before the stimulus\n psConfig.evoked, ... % number of frames looked after the stimulus\n frameRate); % frame rate\n% set(fig, 'WindowStyle', 'docked');\n if doStimEventRasterPlot > 1;\n saveas(fig, sprintf('%s_EventStimRaster_%s', saveName, eventDetectMethod));\n saveas(fig, sprintf('%s_EventStimRaster_%s.png', saveName, eventDetectMethod));\n close(fig);\n end;\n o(' #eventDetector: plotting the peri-stimulus event raster plot done.', 2, dbgLevel); %#ok<*UNRCH>\nend;\n% %% Population stimulus plot\n% if doPsStimPlot;\n% o(' #eventDetector: plotting the peri-stimulus plot ...', 2, dbgLevel); %#ok<*UNRCH>\n% fig = plotPSStimPlot( ...\n% 'PopPeriStimPlot', ... % title of the plot\n% PSTraceRoi, ... % all traces around the stimulus\n% stim{1}, ... % stimuli for extracting their 'name'\n% psConfig.base, ... % number of frames looked before the stimulus\n% psConfig.evoked, ... % number of frames looked after the stimulus\n% frameRate); % frame rate\n% if doPsStimPlot > 1;\n% % set(fig, 'WindowStyle', 'docked');\n% saveas(fig, sprintf('%s_PSStimAverage_%s', roiStats.saveName, eventDetectMethod));\n% saveas(fig, sprintf('%s_PSStimAverage_%s.png', roiStats.saveName, eventDetectMethod));\n% close(fig);\n% end;\n% o(' #eventDetector: plotting the peri-stimulus plot done.', 2, dbgLevel); %#ok<*UNRCH>\n% end;\n%% Population raster plot\nif doRasterPlot;\n o(' #eventDetector: plotting the population raster plot ...', 2, dbgLevel); %#ok<*UNRCH>\n cellIDaxes = ROISet(:, 1);\n switch lower(eventDetectMethod)\n case {'peeling', 'fast_oopsi'};\n titleStr = 'PopRaster';\n [fig, ~] = PsPlot2Raster(PSEventRoi, frameRate, ...\n psConfig.base + 1, cellIDaxes(1 : length(cellIDaxes) - 1), 1, 0);\n set(fig, 'Name', titleStr, 'NumberTitle', 'off');\n% set(fig, 'WindowStyle', 'docked');\n if doRasterPlot > 1;\n saveas(fig,sprintf('%s_EventRasterByRoi_%s', saveName, eventDetectMethod));\n saveas(fig,sprintf('%s_EventRasterByRoi_%s.png', saveName, eventDetectMethod));\n close(fig);\n end;\n end\n o(' #eventDetector: plotting the population raster plot done.', 2, dbgLevel); %#ok<*UNRCH>\nend;\n%% end\nvarargout{1} = config;\nend\n\nfunction [config, V, P] = getDefaultParameters(eventDetectMethod, frameRate)\n amp = 10;\n tau = 2;\n onsettau = 0.01;\n switch lower(eventDetectMethod);\n case 'fast_oopsi';\n config.EventDetect.amp = amp;\n config.EventDetect.tau = tau;\n config.EventDetect.onsettau = onsettau;\n config.EventDetect.doPlot = 0; % should be switched off\n config.EventDetect.lam = 0.2; % firing rate(ish)\n config.EventDetect.base_frames = 10;\n config.EventDetect.oopsi_thr = 0.3;\n config.EventDetect.integral_thr = 5;\n config.EventDetect.filter = [7 2];\n config.EventDetect.minGof = 0.5;\n P.lam = config.EventDetect.lam;\n % P.gam = (1-(1/freq_ca)) / ca_tau;\n V.dt = 1/frameRate;\n V.est_gam = 1; % estimate decay time parameter (does not work)\n V.est_sig = 1; % estimate baseline noise SD\n V.est_lam = 1; % estimate firing rate\n V.est_a = 0; % estimate spatial filter\n V.est_b = 0; % estimate background fluo.\n V.fast_thr = 1;\n V.fast_iter_max = 3;\n case 'peeling';\n V = [];\n P = [];\n config.EventDetect.optimizeSpikeTimes = 0;\n config.EventDetect.schmittHi = [1.75 0 3];\n config.EventDetect.schmittLo = [-1 -3 0];\n config.EventDetect.schmittMinDur = [0.3 0.05 3];\n config.EventDetect.A1 = amp;\n config.EventDetect.tau1 = tau;\n config.EventDetect.onsettau = onsettau;\n config.EventDetect.optimMethod = 'none';\n config.EventDetect.minPercentChange = 0.1;\n config.EventDetect.maxIter = 20;\n config.EventDetect.plotFinal = 0;\n case 'none';\n config = [];\n V = [];\n P = [];\n warning('Nothing to do here! Exit ...')\n return;\n end;\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "eventDetector_old.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/eventDetection/eventDetector_old.m", "size": 12802, "source_encoding": "utf_8", "md5": "ad7f17e5b4904c061333c7f354dac6c0", "text": "function varargout = eventDetector(roiStats, eventDetectMethod)\n% event detection function - wrapper to different event detection algorithms\n% input: structure created by GetRoiStats (*_RoiStats)\ndbgLevel = 2;\n% required folders\nfolderList = {'Projects/EventDetect','Projects/TwoPhotonAnalyzer'};\naddFolders2Path(folderList,1);\nmaxRuns = Inf; % for testing\n% maxRuns = 2; % for testing\ndoCaTracesPlot = 1;\ndoPlotEvents = doCaTracesPlot && 0; %%#ok\ndoRasterPlot = 0;\ndoStimEventRasterPlot = 0;\ndoPsStimPlot = 0;\ndoEventCountPlot = 0;\ndoEventDetection = 0;\no(' #eventDetector: method: \"%s\", maxRuns = %d ...', eventDetectMethod, maxRuns, 1, dbgLevel);\n%% Event detection parameters\n[config, V, P] = getDefaultParameters(eventDetectMethod, roiStats.frameRate{1}); %%#ok\no(' #eventDetector: event detection parameters configured.', 3, dbgLevel);\n%% Event detection\n% event detection on roiStats\nallDFFData = roiStats.dataRoi;\n% last row is neuropil, remove it\nallDFFData(end, :) = [];\n% init sizes of data set\nnROIs = size(allDFFData, 1);\nnRuns = size(allDFFData, 2);\nnFrames = size(allDFFData{1, 1}, 2);\n% only process requested runs\nif nRuns > maxRuns;\n nRuns = maxRuns;\n allDFFData(:, maxRuns + 1 : end) = [];\nend\n\no(' #eventDetector: variables initialized.', 3, dbgLevel);\no(' #eventDetector: starting event detection ... ', 2, dbgLevel);\neventDetectStartTime = tic;\neventData = cell(size(allDFFData));\neventMatAllRuns = zeros(nROIs, nRuns * size(allDFFData{1, 1}, 2));\nStimVectorAllRuns = zeros(1, nRuns * size(allDFFData{1, 1}, 2));\nouterDffData = allDFFData;\nnRunsWithError = 0;\nnTotEvents = 0;\n% nRuns = 1; o('/!\\\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);\nfor iRun = 1 : nRuns;\n try\n allDFFData = outerDffData;\n startIndex = (iRun - 1) * nFrames + 1;\n endIndex = iRun * nFrames;\n eventDetect = config.EventDetect;\n o(' #eventDetector: run %d/%d, %d rois...', iRun, nRuns, nROIs, 4, dbgLevel);\n if size(roiStats.stim{iRun}, 2) ~= startIndex - endIndex + 1;\n o(' #eventDetector: run %d/%d, %d rois: skip for bad size.', iRun, nRuns, nROIs, 1, dbgLevel);\n continue;\n end;\n StimVectorAllRuns(startIndex : endIndex) = roiStats.stim{iRun};\n eventDetect.rate = roiStats.frameRate{iRun};\n eventCounts = zeros(1, nROIs);\n% residualVector = zeros(1,nROIs);\n currentEventMat = zeros(nROIs, nFrames);\n \n if doEventDetection;\n parfor iRoi = 1 : nROIs;\n o(' #eventDetector: run %d/%d - roi %d/%d ...', iRun, nRuns, iRoi, nROIs, 5, dbgLevel);\n dff = allDFFData{iRoi, iRun};\n if isempty(dff);\n warning('eventDetector:dffEmpty', 'dff is empty!');\n continue;\n end;\n switch lower(eventDetectMethod)\n case 'fast_oopsi'\n oopsiOut = fast_oopsi(dff, V, P);\n oopsiOut(oopsiOut < config.EventDetect.oopsi_thr) = 0; %#ok\n currentEventMat(iRoi, :) = oopsiOut';\n eventData{iRoi, iRun} = oopsiOut';\n case 'peeling'\n eventOut = doPeeling(eventDetect,dff);\n % residual{iRoi,iRun} = eventOut.data.peel;\n % model{iRoi,iRun} = eventOut.data.model;\n eventCounts(iRoi) = sum(eventOut.data.spiketrain); %%#ok\n % residualVector(iRoi) = sum(abs(eventOut.data.peel)) / length(eventOut.data.peel);\n currentEventMat(iRoi, :) = eventOut.data.spiketrain;\n eventData{iRoi, iRun} = eventOut.data.spiketrain;\n end;\n nEventsFound = sum(currentEventMat(iRoi, :));\n nTotEvents = nTotEvents + nEventsFound;\n o(' #eventDetector: run %d/%d - roi %d/%d done, %d event(s) found.', ...\n iRun, nRuns, iRoi, nROIs, nEventsFound, 4, dbgLevel);\n end ;\n end;\n eventMatAllRuns(:, startIndex : endIndex) = currentEventMat;\n o(' #eventDetector: run %d/%d done.', iRun, nRuns, 3, dbgLevel);\n catch err;\n nRunsWithError = nRunsWithError + 1; %#ok\n o(' #eventDetector: problem in run %d/%d.', iRun, nRuns, 2, dbgLevel);\n rethrow(err);\n end;\nend;\neventDetectEndTime = toc(eventDetectStartTime);\nPSTraceRoi = PsPlotAnalysis(cell2mat(allDFFData(:, :)), StimVectorAllRuns, roiStats.psConfig);\no(' #eventDetector: event detection done for %d runs (%d error(s), %d total events, %.2f sec).', ...\n nRuns, nRunsWithError, nTotEvents, eventDetectEndTime, 2, dbgLevel);\nif ~isempty(eventMatAllRuns) && nTotEvents > 0;\n o(' #eventDetector: extracting peri-stimulus events...', 3, dbgLevel);\n PSEventRoi = PsPlotAnalysis(eventMatAllRuns, StimVectorAllRuns, roiStats.psConfig);\n config.PsPlotEventRoi = PSEventRoi;\n o(' #eventDetector: extracting peri-stimulus events done.', 2, dbgLevel);\nelse\n o(' #eventDetector: no events found (%d).', nTotEvents, 1, dbgLevel);\nend\n\no(' #eventDetector: moving to plotting section ...', 3, dbgLevel);\n%% Calcium DFF / DRR Plot - with events\nif doCaTracesPlot; % only plot if required\n o(' #eventDetector: plotting the calcium DFF (or DRR) Plot with events...', 2, dbgLevel); %#ok<*UNRCH>\n % go through each run\n% nRuns = 1; o('/!\\\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);\n for iRun = 1 : nRuns;\n o(' #eventDetector: plotting run %d/%d ...', iRun, nRuns, 4, dbgLevel);\n fig = plotROICaTraces(iRun, roiStats.saveName, ... % run number and figure name\n cell2mat(allDFFData(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix\n cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix\n roiStats.stim{iRun}, ... % stimulus as a nFrames long vector\n roiStats.ROISet, ... % name and coordinates of the rois\n roiStats.frameRate{1}, ... % frame rate\n eventDetectMethod, ... % used detection method\n doPlotEvents); % tells whether to plot the events or not\n o(' #eventDetector: plotting run %d/%d done, saving...', iRun, nRuns, 4, dbgLevel);\n set(fig, 'WindowStyle', 'docked');\n if doPlotEvents;\n saveName = sprintf('%s_ROICaTracesWithEvents_run%02d_%s', roiStats.saveName, iRun, ...\n eventDetectMethod);\n else\n saveName = sprintf('%s_ROICaTracesWithoutEvents_run%02d_%s', roiStats.saveName, iRun, ...\n eventDetectMethod);\n end;\n saveas(fig, saveName);\n saveas(fig, [saveName '.png']);\n close(fig);\n o(' #eventDetector: plotting & saving run %d/%d done.', iRun, nRuns, 3, dbgLevel);\n end\n o(' #eventDetector: plotting %d run(s) done.', nRuns, 2, dbgLevel);\nend;\n%% Event count plot\nif doEventCountPlot;\n o(' #eventDetector: plotting the event counts for ROI image...', 2, dbgLevel); %#ok<*UNRCH>\n fig = plotCountROIMap( ...\n eventCounts, ... % event counts for each ROI\n roiStats.img_dims(1), roiStats.img_dims(2), ... % dimensions of the frame\n roiStats.ROISet(1 : end - 1, 2)); % the positions of the ROI\n \n set(fig, 'WindowStyle', 'docked');\n saveas(fig, sprintf('%s_ROIEventCount_%s', roiStats.saveName, eventDetectMethod));\n saveas(fig, sprintf('%s_ROIEventCount_%s.png', roiStats.saveName, eventDetectMethod));\n close(fig);\n o(' #eventDetector: plotting the event counts for ROI image done.', 3, dbgLevel); %#ok<*UNRCH>\nend;\n%% Population stimulus event raster plot\nif doStimEventRasterPlot;\n o(' #eventDetector: plotting the peri-stimulus event raster plot ...', 2, dbgLevel); %#ok<*UNRCH>\n fig = plotStimEventRaster( ...\n 'PopRasterSinglePlot', ... % title of the plot\n PSEventRoi, ... % event counts around the stimulus\n roiStats.stim{1}, ... % stimuli for extracting their 'name'\n roiStats.psConfig.baseFrames, ... % number of frames looked before the stimulus\n roiStats.psConfig.evokedFrames, ... % number of frames looked after the stimulus\n roiStats.frameRate{1}); % frame rate\n set(fig, 'WindowStyle', 'docked');\n saveas(fig, sprintf('%s_EventStimRaster_%s', roiStats.saveName, eventDetectMethod));\n saveas(fig, sprintf('%s_EventStimRaster_%s.png', roiStats.saveName, eventDetectMethod));\n close(fig);\n o(' #eventDetector: plotting the peri-stimulus event raster plot done.', 2, dbgLevel); %#ok<*UNRCH>\nend;\n%% Population stimulus plot\nif doPsStimPlot;\n o(' #eventDetector: plotting the peri-stimulus plot ...', 2, dbgLevel); %#ok<*UNRCH>\n fig = plotPSStimPlot( ...\n 'PopPeriStimPlot', ... % title of the plot\n PSTraceRoi, ... % all traces around the stimulus\n roiStats.stim{1}, ... % stimuli for extracting their 'name'\n roiStats.psConfig.baseFrames, ... % number of frames looked before the stimulus\n roiStats.psConfig.evokedFrames, ... % number of frames looked after the stimulus\n roiStats.frameRate{1}); % frame rate\n set(fig, 'WindowStyle', 'docked');\n saveas(fig, sprintf('%s_PSStimAverage_%s', roiStats.saveName, eventDetectMethod));\n saveas(fig, sprintf('%s_PSStimAverage_%s.png', roiStats.saveName, eventDetectMethod));\n close(fig);\n o(' #eventDetector: plotting the peri-stimulus plot done.', 2, dbgLevel); %#ok<*UNRCH>\nend;\n%% Population raster plot\nif doRasterPlot;\n o(' #eventDetector: plotting the population raster plot ...', 2, dbgLevel); %#ok<*UNRCH>\n roiSet = roiStats.ROISet;\n cellIDaxes = roiSet(:, 1);\n switch lower(eventDetectMethod)\n case {'peeling', 'fast_oopsi'};\n titleStr = 'PopRaster';\n [fig, ~] = PsPlot2Raster(PSEventRoi, roiStats.frameRate{1}, ...\n roiStats.psConfig.baseFrames + 1, cellIDaxes(1 : length(cellIDaxes) - 1), 1, 0);\n set(fig, 'Name', titleStr, 'NumberTitle', 'off');\n set(fig, 'WindowStyle', 'docked');\n saveas(fig,sprintf('%s_EventRasterByRoi_%s', roiStats.saveName, eventDetectMethod));\n saveas(fig,sprintf('%s_EventRasterByRoi_%s.png', roiStats.saveName, eventDetectMethod));\n close(fig);\n end\n o(' #eventDetector: plotting the population raster plot done.', 2, dbgLevel); %#ok<*UNRCH>\nend;\n%% end\nvarargout{1} = config;\nend\n\nfunction [config, V, P] = getDefaultParameters(eventDetectMethod, frameRate)\n amp = 10;\n tau = 2;\n onsettau = 0.01;\n switch lower(eventDetectMethod);\n case 'fast_oopsi';\n config.EventDetect.amp = amp;\n config.EventDetect.tau = tau;\n config.EventDetect.onsettau = onsettau;\n config.EventDetect.doPlot = 0; % should be switched off\n config.EventDetect.lam = 0.2; % firing rate(ish)\n config.EventDetect.base_frames = 10;\n config.EventDetect.oopsi_thr = 0.3;\n config.EventDetect.integral_thr = 5;\n config.EventDetect.filter = [7 2];\n config.EventDetect.minGof = 0.5;\n P.lam = config.EventDetect.lam;\n % P.gam = (1-(1/freq_ca)) / ca_tau;\n V.dt = 1/frameRate;\n V.est_gam = 1; % estimate decay time parameter (does not work)\n V.est_sig = 1; % estimate baseline noise SD\n V.est_lam = 1; % estimate firing rate\n V.est_a = 0; % estimate spatial filter\n V.est_b = 0; % estimate background fluo.\n V.fast_thr = 1;\n V.fast_iter_max = 3;\n case 'peeling';\n V = [];\n P = [];\n config.EventDetect.optimizeSpikeTimes = 0;\n config.EventDetect.schmittHi = [1.75 0 3];\n config.EventDetect.schmittLo = [-1 -3 0];\n config.EventDetect.schmittMinDur = [0.3 0.05 3];\n config.EventDetect.A1 = amp;\n config.EventDetect.tau1 = tau;\n config.EventDetect.onsettau = onsettau;\n config.EventDetect.optimMethod = 'none';\n config.EventDetect.minPercentChange = 0.1;\n config.EventDetect.maxIter = 20;\n config.EventDetect.plotFinal = 0;\n case 'none';\n config = [];\n V = [];\n P = [];\n warning('Nothing to do here! Exit ...')\n return;\n end;\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "PeelingOptimizeSpikeTimesSaturation.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/eventDetection/newPeeling/PeelingOptimizeSpikeTimesSaturation.m", "size": 4465, "source_encoding": "utf_8", "md5": "82892eced9f5fb70e0d8ad3f544df164", "text": "function [spkTout,output] = PeelingOptimizeSpikeTimesSaturation(dff,spkTin,lowerT,upperT,...\n ca_amp,ca_gamma,ca_onsettau,ca_rest, ca_kappas, kd, conc, dffmax, frameRate, dur, optimMethod,maxIter,doPlot)\n% optimization of spike times found by Peeling algorithm\n% minimize the sum of the residual squared\n% while several optimization algorithms are implemented (see below), we have only used pattern\n% search. Other algorithms are only provided for convenience and are not tested sufficiently.\n%\n% Henry Luetcke (hluetck@gmail.com)\n% Brain Research Institut\n% University of Zurich\n% Switzerland\n\nspkTout = spkTin;\nt = (1:numel(dff))./frameRate;\n\nca = spkTimes2FreeCalcium(spkTin,ca_amp,ca_gamma,ca_onsettau,ca_rest, ca_kappas,...\n kd, conc,frameRate,dur);\nmodeltmp = Calcium2Fluor(ca,ca_rest,kd,dffmax);\nmodel = modeltmp(1:length(dff));\n\nif doPlot\n figure('Name','Before Optimization')\n plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b')\n legend('DFF','Model','Residual')\nend\n\nresidual = dff - model;\nresInit = sum(residual.^2);\n\n% start optimization\nx0 = spkTin;\nlbound = spkTin - lowerT;\nlbound(lbound<0) = 0;\nubound = spkTin + upperT;\nubound(ubound>max(t)) = max(t);\n\nlbound = zeros(size(spkTin));\nubound = repmat(max(t),size(spkTin));\n\nopt_args.dff = dff;\nopt_args.ca_rest = ca_rest;\nopt_args.ca_amp = ca_amp;\nopt_args.ca_gamma = ca_gamma;\nopt_args.ca_onsettau = ca_onsettau;\nopt_args.ca_kappas = ca_kappas;\nopt_args.kd = kd;\nopt_args.conc = conc;\nopt_args.dffmax = dffmax;\nopt_args.frameRate = frameRate;\nopt_args.dur = dur;\n\noptimClock = tic;\n\nswitch lower(optimMethod)\n case 'simulated annealing'\n options = saoptimset;\n case 'pattern search'\n options = psoptimset;\n case 'genetic'\n options = gaoptimset;\n otherwise\n error('Optimization method %s not supported.',optimMethod)\nend\n\n% options for optimization algorithms\n% not all options are used for all algorithms\noptions.Display = 'off';\noptions.MaxIter = maxIter;\noptions.MaxIter = Inf;\noptions.UseParallel = 'always';\noptions.ObjectiveLimit = 0;\noptions.TimeLimit = 10; % in s / default is Inf\n\n% experimental\noptions.MeshAccelerator = 'on'; % off by default\noptions.TolFun = 1e-9; % default is 1e-6\noptions.TolMesh = 1e-9; % default is 1e-6\noptions.TolX = 1e-9; % default is 1e-6\n% options.MaxFunEvals = numel(spkTin)*100; % default is 2000*numberOfVariables\n% options.MaxFunEvals = 20000;\n\noptions.Display = 'none';\n% options.Display = 'final';\n\n% options.PlotFcns = {@psplotbestf @psplotbestx};\n% options.OutputFcns = @psoutputfcn_peel;\n\nswitch lower(optimMethod)\n case 'simulated annealing'\n [x, fval , exitFlag, output] = simulannealbnd(...\n @(x) objectiveFunc(x,opt_args),x0,lbound,ubound,options);\n case 'pattern search'\n [x, fval , exitFlag, output] = patternsearch(...\n @(x) objectiveFunc(x,opt_args),x0,[],[],[],[],lbound,...\n ubound,[],options);\n case 'genetic'\n [x, fval , exitFlag, output] = ga(...\n @(x) objectiveFunc(x,opt_args),numel(x0),[],[],[],[],lbound,...\n ubound,[],options);\nend\n\nif fval < resInit\n spkTout = x;\nelse\n disp('Optimization did not improve residual. Keeping input spike times.')\nend\n\nif doPlot\n fprintf('Optimization time (%s): %1.2f s\\n',optimMethod,toc(optimClock))\n fprintf('Final squared residual: %1.2f (Change: %1.2f)\\n',fval,resInit-fval);\n spkVector = zeros(1,numel(t));\n for i = 1:numel(spkTout)\n [~,idx] = min(abs(spkTout(i)-t));\n spkVector(idx) = spkVector(idx)+1;\n end\n model = conv(spkVector,modelTransient);\n model = model(1:length(t));\n figure('Name','After Optimization')\n plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b')\n legend('DFF','Model','Residual')\nend\n\n\nfunction residual = objectiveFunc(spkTin,opt_args)\n\ndff = opt_args.dff;\nca_rest = opt_args.ca_rest;\nca_amp = opt_args.ca_amp;\nca_gamma = opt_args.ca_gamma;\nca_onsettau = opt_args.ca_onsettau;\nca_kappas = opt_args.ca_kappas;\nkd = opt_args.kd;\nconc = opt_args.conc;\ndffmax = opt_args.dffmax;\nframeRate = opt_args.frameRate;\ndur = opt_args.dur;\n\nca = spkTimes2FreeCalcium(sort(spkTin),ca_amp,ca_gamma,ca_onsettau,ca_rest, ca_kappas,...\n kd, conc,frameRate,dur);\nmodeltmp = Calcium2Fluor(ca,ca_rest,kd,dffmax);\nmodel = modeltmp(1:length(dff));\n\nresidual = dff-model;\nresidual = sum(residual.^2);\n\n\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "PeelingOptimizeSpikeTimes.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/eventDetection/newPeeling/PeelingOptimizeSpikeTimes.m", "size": 4159, "source_encoding": "utf_8", "md5": "61e419a2e0808657c62b39f38bc0fb60", "text": "function [spkTout,output] = PeelingOptimizeSpikeTimes(dff,spkTin,lowerT,upperT,...\n rate,tauOn,A1,tau1,optimMethod,maxIter,doPlot)\n% optimization of spike times found by Peeling algorithm\n% minimize the sum of the residual squared\n% while several optimization algorithms are implemented (see below), we have only used pattern\n% search. Other algorithms are only provided for convenience and are not tested sufficiently.\n%\n% Henry Luetcke (hluetck@gmail.com)\n% Brain Research Institut\n% University of Zurich\n% Switzerland\n\nt = (1:numel(dff))./rate;\n\nmodelTransient = modelCalciumTransient(t,t(1),tauOn,A1,tau1);\nmodelTransient = modelTransient';\n\nspkTout = spkTin;\n\nspkVector = zeros(1,numel(t));\nfor i = 1:numel(spkTin)\n [~,idx] = min(abs(spkTin(i)-t));\n spkVector(idx) = spkVector(idx)+1;\nend\nmodel = conv(spkVector,modelTransient);\nmodel = model(1:length(t));\n\nif doPlot\n figure('Name','Before Optimization')\n plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b')\n legend('DFF','Model','Residual')\nend\n\nresidual = dff - model;\n\nresInit = sum(residual.^2);\n\n% start optimization\nx0 = spkTin;\nlbound = spkTin - lowerT;\nlbound(lbound<0) = 0;\nubound = spkTin + upperT;\nubound(ubound>max(t)) = max(t);\n\nlbound = zeros(size(spkTin));\nubound = repmat(max(t),size(spkTin));\n\nopt_args.dff = dff;\nopt_args.rate = rate;\nopt_args.tauOn = tauOn;\nopt_args.A1 = A1;\nopt_args.tau1 = tau1;\noptimClock = tic;\n\nswitch lower(optimMethod)\n case 'simulated annealing'\n options = saoptimset;\n case 'pattern search'\n options = psoptimset;\n case 'genetic'\n options = gaoptimset;\n otherwise\n error('Optimization method %s not supported.',optimMethod)\nend\n\n% options for optimization algorithms\n% not all options are used for all algorithms\noptions.Display = 'off';\noptions.MaxIter = maxIter;\noptions.MaxIter = Inf;\noptions.UseParallel = 'always';\noptions.ObjectiveLimit = 0;\n% options.TimeLimit = 10; % in s / default is Inf\n\n% experimental\noptions.MeshAccelerator = 'on'; % off by default\noptions.TolFun = 1e-9; % default is 1e-6\noptions.TolMesh = 1e-9; % default is 1e-6\noptions.TolX = 1e-9; % default is 1e-6\n% options.MaxFunEvals = numel(spkTin)*100; % default is 2000*numberOfVariables\n% options.MaxFunEvals = 20000;\n\noptions.Display = 'none';\n% options.Display = 'final';\n\n% options.PlotFcns = {@psplotbestf @psplotbestx};\n% options.OutputFcns = @psoutputfcn_peel;\n\nswitch lower(optimMethod)\n case 'simulated annealing'\n [x, fval , exitFlag, output] = simulannealbnd(...\n @(x) objectiveFunc(x,opt_args),x0,lbound,ubound,options);\n case 'pattern search'\n [x, fval , exitFlag, output] = patternsearch(...\n @(x) objectiveFunc(x,opt_args),x0,[],[],[],[],lbound,...\n ubound,[],options);\n case 'genetic'\n [x, fval , exitFlag, output] = ga(...\n @(x) objectiveFunc(x,opt_args),numel(x0),[],[],[],[],lbound,...\n ubound,[],options);\nend\n\nif fval < resInit\n spkTout = x;\nelse\n disp('Optimization did not improve residual. Keeping input spike times.')\nend\n\nif doPlot\n fprintf('Optimization time (%s): %1.2f s\\n',optimMethod,toc(optimClock))\n fprintf('Final squared residual: %1.2f (Change: %1.2f)\\n',fval,resInit-fval);\n spkVector = zeros(1,numel(t));\n for i = 1:numel(spkTout)\n [~,idx] = min(abs(spkTout(i)-t));\n spkVector(idx) = spkVector(idx)+1;\n end\n model = conv(spkVector,modelTransient);\n model = model(1:length(t));\n figure('Name','After Optimization')\n plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b')\n legend('DFF','Model','Residual')\nend\n\n\nfunction residual = objectiveFunc(spkTin,opt_args)\n\ndff = opt_args.dff;\nrate = opt_args.rate;\ntauOn = opt_args.tauOn;\nA1 = opt_args.A1;\ntau1 = opt_args.tau1;\nt = (1:numel(dff))./rate;\nmodelTransient = spkTimes2Calcium(0,tauOn,A1,tau1,0,0,rate,max(t));\nspkVector = zeros(1,numel(t));\nfor i = 1:numel(spkTin)\n [~,idx] = min(abs(spkTin(i)-t));\n spkVector(idx) = spkVector(idx)+1;\nend\nmodel = conv(spkVector,modelTransient);\nmodel = model(1:length(t));\nresidual = dff-model;\nresidual = sum(residual.^2);\n\n\n\n\n\n\n\n\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "Peeling.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/eventDetection/newPeeling/Peeling.m", "size": 9350, "source_encoding": "utf_8", "md5": "feca5c14c59423537078bfaf885a57e7", "text": "function [ca_p, peel_p, data] = Peeling(dff, rate, varargin)\n% this is the main routine of the peeling algorithm\n%\n% Peeling algorithm was developed by Fritjof Helmchen\n% Brain Research Institute\n% University of Zurich\n% Switzerland\n%\n% Matlab implementation and spike timing optimization by Henry Luetcke & Fritjof Helmchen\n% Brain Research Institute\n% University of Zurich\n% Switzerland\n%\n% Please cite:\n% Grewe BF, Langer D, Kasper H, Kampa BM, Helmchen F. High-speed in vivo calcium imaging\n% reveals neuronal network activity with near-millisecond precision.\n% Nat Methods. 2010 May;7(5):399-405. \n\nmaxRate_peel = Inf;\n\nif rate > maxRate_peel\n peel_rate = maxRate_peel;\n fit_rate = rate;\n x = 1/rate:1/rate:numel(dff)/rate;\n xi = 1/peel_rate:1/peel_rate:max(x);\n peel_dff = interp1(x,dff,xi);\nelse\n peel_rate = rate;\n fit_rate = rate;\n peel_dff = dff;\nend\n\n[ca_p,exp_p,peel_p, data] = InitPeeling(peel_dff, peel_rate);\n\nif nargin > 2\n for n = 1:numel(varargin)\n S = varargin{n};\n if n == 1\n ca_p = overrideFieldValues(ca_p,S);\n elseif n == 2\n exp_p = overrideFieldValues(exp_p,S);\n elseif n == 3\n peel_p = overrideFieldValues(peel_p,S);\n end\n end\nend\n\ndata.model = 0;\ndata.freecamodel = ca_p.ca_rest;\ndata.spikes = zeros(1,1000);\ndata.numspikes = 0;\n\ndata.peel = data.dff;\n\nwsiz = round(peel_p.slidwinsiz*exp_p.acqrate);\ncheckwsiz = round(peel_p.negintwin*exp_p.acqrate);\n\npeel_p.smttmindurFrames = ceil(peel_p.smttmindur*exp_p.acqrate);\npeel_p.smttlowMinEvents = 1;\n\nnexttim = 1/exp_p.acqrate;\n\n[ca_p, peel_p, data] = FindNextEvent(ca_p, exp_p, peel_p, data, nexttim);\nif (peel_p.evtfound == 1)\n data.numspikes = data.numspikes + 1;\n data.spikes(data.numspikes) = peel_p.nextevt;\n [ca_p, exp_p, data] = SingleFluorTransient(ca_p, exp_p, data, peel_p.spk_recmode, peel_p.nextevt);\n data.model = data.model + data.singleTransient;\nend\n\nmaxiter = 999999;\niter = 0;\nnexttimMem = Inf;\nnexttimCounter = 0;\ntimeStepForward = 2./exp_p.acqrate;\nwhile (peel_p.evtfound == 1)\n % check integral after subtracting Ca transient\n if (peel_p.spk_recmode == 'linDFF')\n elseif (peel_p.spk_recmode == 'satDFF')\n ca_p.onsetposition = peel_p.nextevt;\n ca_p = IntegralofCaTransient(ca_p, peel_p, exp_p, data);\n end\n \n dummy = data.peel - data.singleTransient;\n [~,startIdx] = min(abs(data.tim-data.spikes(data.numspikes)));\n [~,stopIdx] = min(abs(data.tim-(data.spikes(data.numspikes)+...\n peel_p.intcheckwin)));\n if startIdx < stopIdx\n currentTim = data.tim(startIdx:stopIdx);\n currentPeel = dummy(startIdx:stopIdx);\n currentIntegral = trapz(currentTim,currentPeel);\n else\n % if this is true, startIdx is the last data point and we should\n % not accept it as a spike\n currentIntegral = ca_p.negintegral*peel_p.negintacc;\n end\n if currentIntegral > (ca_p.negintegral*peel_p.negintacc)\n data.peel = data.peel - data.singleTransient;\n nexttim = data.spikes(data.numspikes) - peel_p.stepback;\n if (nexttim < 0)\n nexttim = 1/exp_p.acqrate;\n end\n else\n data.spikes(data.numspikes) = [];\n data.numspikes = data.numspikes-1;\n data.model = data.model - data.singleTransient;\n nexttim = peel_p.nextevt + timeStepForward;\n end\n \n peel_p.evtaccepted = 0;\n \n [ca_p, peel_p, data] = FindNextEvent(ca_p, exp_p, peel_p, data, nexttim);\n \n if peel_p.evtfound\n data.numspikes = data.numspikes + 1;\n data.spikes(data.numspikes) = peel_p.nextevt;\n [ca_p, exp_p, data] = SingleFluorTransient(ca_p, exp_p, data, peel_p.spk_recmode, peel_p.nextevt);\n data.model = data.model + data.singleTransient;\n else\n break\n end\n \n iter = iter + 1;\n \n if nexttim == nexttimMem\n nexttimCounter = nexttimCounter + 1;\n else\n nexttimMem = nexttim;\n nexttimCounter = 0;\n end\n %%\n \n if nexttimCounter > 50\n nexttim = nexttim + timeStepForward;\n end\n \n if (iter > maxiter)\n% warning('Reached maxiter (%1.0f). nexttim=%1.2f. Timeout!',maxiter,nexttim);\n% save\n% error('Covergence failed!')\n break\n end\nend\n\nif length(data.spikes) > data.numspikes\n data.spikes(data.numspikes+1:end) = [];\nend\n\n% go back to original frame rate\nif rate > maxRate_peel\n spikes = data.spikes;\n [ca_p,exp_p,peel_p, data] = InitPeeling(dff, fit_rate);\n if nargin > 2\n for n = 1:numel(varargin)\n S = varargin{n};\n if n == 1\n ca_p = overrideFieldValues(ca_p,S);\n elseif n == 2\n exp_p = overrideFieldValues(exp_p,S);\n elseif n == 3\n peel_p = overrideFieldValues(peel_p,S);\n end\n end\n end\n data.spikes = spikes;\nend\n\n% optimization of reconstructed spike times to improve timing\noptMethod = 'pattern search';\noptMaxIter = 100000;\n%lowerT = 1; % relative to x0\n%upperT = 1; % relative to x0\nlowerT = 0.1; % relative to x0\nupperT = 0.1; % relative to x0\n\nif numel(data.spikes) && peel_p.optimizeSpikeTimes\n if (peel_p.spk_recmode == 'linDFF')\n spikes = PeelingOptimizeSpikeTimes(data.dff,data.spikes,lowerT,upperT,...\n exp_p.acqrate,ca_p.onsettau,ca_p.amp1,ca_p.tau1,optMethod,optMaxIter,0);\n elseif (peel_p.spk_recmode == 'satDFF')\n spikes = PeelingOptimizeSpikeTimesSaturation(data.dff,data.spikes,lowerT,upperT,...\n ca_p.ca_amp,ca_p.ca_gamma,ca_p.ca_onsettau,ca_p.ca_rest,ca_p.ca_kappas, exp_p.kd,...\n exp_p.conc,exp_p.dffmax, exp_p.acqrate, length(data.dff)./exp_p.acqrate, optMethod,optMaxIter,0);\n else\n error('Undefined mode');\n end\n data.spikes = sort(spikes);\nend\n\n% fit onset to improve timing accuracy\nif peel_p.fitonset\n onsetfittype = fittype('modelCalciumTransient(t,onsettime,onsettau,amp1,tau1)',...\n 'independent','t','coefficients',{'onsettime','onsettau','amp1'},...\n 'problem',{'tau1'});\n \n wleft = round(peel_p.fitwinleft*exp_p.acqrate); % left window for onset fit\n wright = round(peel_p.fitwinright*exp_p.acqrate); % right window for onset fit\n for i = 1:numel(data.spikes)\n [~,idx] = min(abs(data.spikes(i)-data.tim));\n if (idx-wleft) < 1\n currentwin = data.dff(1:idx+wright);\n currenttim = data.tim(1:idx+wright);\n elseif (idx+wright) > numel(data.dff)\n currentwin = data.dff(idx-wleft:numel(data.dff));\n currenttim = data.tim(idx-wleft:numel(data.dff));\n currentwin = currentwin - mean(data.dff(idx-wleft:idx));\n else\n currentwin = data.dff(idx-wleft:idx+wright);\n currenttim = data.tim(idx-wleft:idx+wright);\n currentwin = currentwin - mean(data.dff(idx-wleft:idx));\n end\n lowerBounds = [currenttim(1) 0.1*ca_p.onsettau 0.5*ca_p.amp1];\n upperBounds = [currenttim(end) 5*ca_p.onsettau 10*ca_p.amp1];\n startPoint = [data.spikes(i) ca_p.onsettau ca_p.amp1];\n problemParams = {ca_p.tau1};\n \n fOptions = fitoptions('Method','NonLinearLeastSquares','Lower',...\n lowerBounds,...\n 'Upper',upperBounds,'StartPoint',startPoint);\n [fitonset,gof] = fit(currenttim',currentwin',onsetfittype,...\n 'problem',problemParams,fOptions);\n \n if gof.rsquare < 0.95\n% fprintf('\\nBad onset fit (t=%1.3f, r^2=%1.3f)\\n',...\n% data.spikes(i),gof.rsquare);\n else\n % fprintf('\\nGood onset fit (r^2=%1.3f)\\n',gof.rsquare);\n data.spikes(i) = fitonset.onsettime;\n end\n end\nend\n\n% loop to create spike train vector from spike times\ndata.spiketrain = zeros(1,numel(data.tim));\nfor i = 1:numel(data.spikes)\n [~,idx] = min(abs(data.spikes(i)-data.tim));\n data.spiketrain(idx) = data.spiketrain(idx)+1;\nend\n\n% re-derive model and residuals after optimization\n\nif (peel_p.spk_recmode == 'linDFF')\n modelTransient = spkTimes2Calcium(0,ca_p.onsettau,ca_p.amp1,ca_p.tau1,...\n ca_p.amp2,ca_p.tau2,exp_p.acqrate,max(data.tim));\n data.model = conv(data.spiketrain,modelTransient);\n data.model = data.model(1:length(data.tim));\nelseif (peel_p.spk_recmode == 'satDFF')\n modeltmp = spkTimes2FreeCalcium(data.spikes,ca_p.ca_amp,ca_p.ca_gamma,ca_p.ca_onsettau,ca_p.ca_rest, ca_p.ca_kappas,...\n exp_p.kd, exp_p.conc,exp_p.acqrate,max(data.tim));\n data.model = Calcium2Fluor(modeltmp,ca_p.ca_rest,exp_p.kd, exp_p.dffmax);\nend\n\ndata.peel = data.dff - data.model;\n\n% plotting parameter\nif isfield(peel_p,'doPlot')\n if peel_p.doPlot\n doPlot = 1;\n else\n doPlot = 0;\n end\nelse\n doPlot = 0;\nend\nif doPlot % plots at interpolation rate\n figure; plot(data.tim,data.peel); hold all\n plot(data.tim,data.dff); hold all\n plot(data.tim,data.spiketrain,'LineWidth',2)\n legend({'Residual','Calcium','UPAPs'}) % unverified putative action potential\nend\n\nend\n\nfunction Sout = overrideFieldValues(Sout,Sin)\nfieldIDs = fieldnames(Sin);\nfor n = 1:numel(fieldIDs)\n Sout.(fieldIDs{n}) = Sin.(fieldIDs{n});\nend\n\nend\n\n\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "CalciumDecay.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/eventDetection/newPeeling/CalciumDecay.m", "size": 1116, "source_encoding": "utf_8", "md5": "67138b4224a9d6e8edefa5aa8b387b8e", "text": "function [t,X] = CalciumDecay(p_gamma,p_carest,p_cacurrent,p_kappas,p_kd,p_conc,tspan)\n% Uses ODE45 to solve Single-compartment model differential equation \n% \n% Fritjof Helmchen (helmchen@hifo.uzh.ch)\n% Brain Research Institute,University of Zurich, Switzerland\n% created: 7.10.2013, last update: 25.10.2013 fh\n\noptions=odeset('RelTol',1e-6); % set an error\nXo = p_cacurrent; % initial conditions\nmypar = [p_gamma,p_carest,p_kappas,p_kd,p_conc]; % parameters\n[t,X] = ode45(@Relax2CaRest,tspan,Xo,options, mypar); % call the solver, tspan should contain time vector with more than two elements\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nfunction [dx_dt]= Relax2CaRest(t,x,pp)\n% differential equation describing the decay of calcium conc level to resting level in the presence\n% of indicator dye with variable buffering capacity.\n% paramters pp: 1 - gamma, 2 - ca_rest, 3 - kappaS, 4 - kd, 5 - indicator total concentration (all conc in nM) \ndx_dt = -pp(1)* (x - pp(2))/(1 + pp(3) + pp(4)*pp(5)/(x + pp(4))^2);\nreturn\nend\n\nend"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "comparingReferences.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/misc/comparingReferences.m", "size": 2914, "source_encoding": "utf_8", "md5": "fd9fe5ba3dd91c9f7ff76ab741405cee", "text": "function comparingReferences\n\nload('refImg_fromMapping');\nrefImgMapping = refImg;\nload('refImg');\nload('ROIs');\n\nfigure('NumberTitle', 'off', 'Name', 'Reference compare', 'Position', [30, 80, 1850, 910], 'Color', 'white');\n\nmakeSubplot(1, refImg, 'Reference from session', ROIs, [-0.05, 1.05]); %#ok<*USENS,*NODEF>\nmakeSubplot(2, refImgMapping, 'Reference from mapping (ROIs)', ROIs, [-0.05, 1.05]);\n\ncorrCoeffs = corrcoef(refImg, refImgMapping, 'rows', 'pairwise');\nmakeSubplot(3, refImgMapping - refImg, sprintf('Ref_{session} - Ref_{mapping}, corr: %.3f', corrCoeffs(2, 1)), ROIs, [-0.5 0.2]);\n\n% register reference onto local session reference\nCP = fix(256 / 2); % center point\nTTP = fix(2 * 256 / 3); % two third point\nrefPoints = [CP TTP CP TTP TTP CP TTP CP CP CP CP CP];\n[~, targPoints, srcPoints] = turboReg(refImgMapping, refImg, 'rigidBody', 3, refPoints, 0);\n% get the transformation matrix\ntForm = cp2tform(squeeze(srcPoints), squeeze(targPoints), 'affine'); %#ok\n% get the transformed frame\nrefImgMappingReg = imtransform(refImgMapping, tForm, 'XData', [1, 256], 'YData', [1, 256], 'FillValues', NaN); %#ok\n\n% shift ROIs\nROIsShift = ROIs;\ntranslationShifts = squeeze(srcPoints(:, 1, :) - targPoints(:, 1, :));\nfor iROI = 1 : size(ROIs, 1);\n % adjust mask\n ROIsShift{iROI, 3} = imtransform(ROIs{iROI, 3}, tForm, 'XData', [1, 256], 'YData', [1, 256], 'FillValues', NaN) == 1; %#ok\n % adjust coordinates\n ROIsShift{iROI, 2} = round(ROIsShift{iROI, 2} + repmat(translationShifts', size(ROIsShift{iROI, 2}, 1), 1));\nend;\n\n\ncorrCoeffs = corrcoef(refImg, refImgMappingReg, 'rows', 'pairwise');\nmakeSubplot(4, refImgMappingReg - refImg, sprintf('Ref_{mapReg} - Ref_{session}, corr: %.3f', corrCoeffs(2, 1)), ROIsShift, [-0.5 0.2]);\n\ncorrCoeffs = corrcoef(refImgMapping, refImgMappingReg, 'rows', 'pairwise');\nmakeSubplot(5, refImgMappingReg - refImgMapping, sprintf('Ref_{mapReg} - Ref_{mapping}, corr: %.3f', corrCoeffs(2, 1)), ROIsShift, [-0.5 0.2]);\n\nmakeSubplot(6, refImgMappingReg, 'Reference from mapping registered', ROIsShift, [-0.05, 1.05]); %#ok<*NODEF>\n\nROIsOri = ROIs; %#ok\nROIs = ROIsShift; %#ok\nsave('ROIs_registered', 'ROIs');\nclear ROIs iROI CP TTP corrCoeffs;\n\nsave('registration');\nexport_fig('registration.fig', gcf);\nexport_fig('registration.png', '-r300', gcf);\n\nend\n\nfunction makeSubplot(iSubPlot, data, titleStr, ROIs, cLim)\n\n subplot(2, 3, iSubPlot);\n imagesc(1 : 256, 1 : 256, data);\n title(titleStr);\n colormap('gray');\n set(gca, 'CLim', cLim);\n % axis('square');\n hold('on');\n ROIColors = [0 1 1; 1 0 1; 0 1 0; 1 1 0; 1 0 0; 0 0 1];\n for iROI = 1 : size(ROIs, 1);\n contour(ROIs{iROI, 3}, 'Color', ROIColors(iROI, :), 'LineStyle', '-');\n end;\n legend(ROIs(:, 1));\n hold('off');\n\nend\n\n% export_fig('analysis/ref_withROIs.png', '-r300', gcf);\n% export_fig('analysis/ref_withROIs.fig', gcf);"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "plotWideFieldMaps_old.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/misc/plotWideFieldMaps_old.m", "size": 5024, "source_encoding": "utf_8", "md5": "df2406424fd659898e4fbbbb5e365bf9", "text": "% plot Wide-Field maps\n\nsessDirs = dir();\nsessDirs(arrayfun(@(i) isempty(regexp(sessDirs(i).name, '^session\\d\\d_\\d+$', 'once')), 1 : numel(sessDirs))) = [];\n\nsessDirs = sessDirs([1, 2, 4 6]);\n\nif ~exist('sessMat', 'var');\n sessMat = struct();\n sessMat(numel(sessDirs)) = struct();\nend;\n\ntrialTypesRegexp = { 'hit', 'CR', 'quiet', 'moveDur', 'moveBef', ...\n 'hit_AND_moveDur', 'hit_AND_quiet', 'hit_AND_moveBef', 'hit_AND_[quiet|moveBef]', ...\n 'CR_AND_moveDur', 'CR_AND_quiet', 'CR_AND_moveBef', 'CR_AND_[quiet|moveBef]' };\ntrialTypeSaveName = { 'hit', 'CR', 'strict_quiet', 'move', 'early_move', ...\n 'strict_quiet_hit', 'move_hit', 'early_move_hit', 'quiet_hit', ...\n 'strict_quiet_CR', 'move_CR', 'early_move_CR', 'quiet_CR' };\n\n%% delay\ntimePeriod = 'delay';\nframesToAvg = 104 : 140;\ncLim = [-0.005, 0.02];\n\nfigure('NumberTitle', 'off', 'Name', timePeriod, 'Position', [67, 432, 1803, 505]);\n \niPlot = 1;\nfor iSess = 1 : numel(sessDirs);\n if ~isfield(sessMat(iSess), 'hit') || isempty(sessMat(iSess).hit);\n hitAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_hit_average.mat']);\n sessMat(iSess).hit = hitAvgMat;\n end;\n subplot(2, numel(sessDirs), iPlot);\n imagesc(1 : 256, 1 : 256, smoothn(nanmean(sessMat(iSess).hit.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));\n set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);\n title(sprintf('Hit - %s', sessDirs(iSess).name), 'Interpreter', 'none');\n colorbar();\n colormap(gca, 'mapgeog');\n iPlot = iPlot + 1;\nend;\n\nfor iSess = 1 : numel(sessDirs);\n if ~isfield(sessMat(iSess), 'CR') || isempty(sessMat(iSess).CR);\n CRAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_CR_average.mat']);\n sessMat(iSess).CR = CRAvgMat;\n end;\n subplot(2, numel(sessDirs), iPlot);\n imagesc(1 : 256, 1 : 256, smoothn(nanmean(sessMat(iSess).CR.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));\n set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);\n title(sprintf('CR - %s', sessDirs(iSess).name), 'Interpreter', 'none');\n colorbar();\n colormap(gca, 'mapgeog');\n iPlot = iPlot + 1;\nend;\n\n%% sensation\ntimePeriod = 'sensation';\nframesToAvg = 60 : 100;\ncLim = [-0.005, 0.02];\n\nfigure('NumberTitle', 'off', 'Name', timePeriod, 'Position', [67, 432, 1803, 505]);\niPlot = 1;\nfor iSess = 1 : numel(sessDirs);\n if ~isfield(sessMat(iSess), 'hit') || isempty(sessMat(iSess).hit);\n hitAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_hit_average.mat']);\n sessMat(iSess).hit = hitAvgMat;\n end;\n subplot(2, numel(sessDirs), iPlot);\n imagesc(1 : 256, 1 : 256, smoothn(nanmean(hitAvgMat.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));\n set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);\n title(sprintf('Hit - %s', sessDirs(iSess).name), 'Interpreter', 'none');\n colorbar();\n colormap(gca, 'mapgeog');\n iPlot = iPlot + 1;\nend;\n\nfor iSess = 1 : numel(sessDirs);\n if ~isfield(sessMat(iSess), 'CR') || isempty(sessMat(iSess).CR);\n CRAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_CR_average.mat']);\n sessMat(iSess).CR = CRAvgMat;\n end;\n subplot(2, numel(sessDirs), iPlot);\n imagesc(1 : 256, 1 : 256, smoothn(nanmean(CRAvgMat.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));\n set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);\n title(sprintf('CR - %s', sessDirs(iSess).name), 'Interpreter', 'none');\n colorbar();\n colormap(gca, 'mapgeog');\n iPlot = iPlot + 1;\nend;\n\n%{\n\nfunction doPlot(timePeriod, framesToAvg, cLim);\n\nfigure('NumberTitle', 'off', 'Name', timePeriod, 'Position', [67, 432, 1803, 505]);\niPlot = 1;\nfor iSess = 1 : numel(sessDirs);\n if ~isfield(sessMat(iSess), 'hit') || isempty(sessMat(iSess).hit);\n hitAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_hit_average.mat']);\n sessMat(iSess).hit = hitAvgMat;\n end;\n subplot(2, numel(sessDirs), iPlot);\n imagesc(1 : 256, 1 : 256, smoothn(nanmean(hitAvgMat.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));\n set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);\n title(sprintf('Hit - %s', sessDirs(iSess).name), 'Interpreter', 'none');\n colorbar();\n colormap(gca, 'mapgeog');\n iPlot = iPlot + 1;\nend;\n\nfor iSess = 1 : numel(sessDirs);\n if ~isfield(sessMat(iSess), 'CR') || isempty(sessMat(iSess).CR);\n CRAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_CR_average.mat']);\n sessMat(iSess).CR = CRAvgMat;\n end;\n subplot(2, numel(sessDirs), iPlot);\n imagesc(1 : 256, 1 : 256, smoothn(nanmean(CRAvgMat.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));\n set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);\n title(sprintf('CR - %s', sessDirs(iSess).name), 'Interpreter', 'none');\n colorbar();\n colormap(gca, 'mapgeog');\n iPlot = iPlot + 1;\nend;\n\n%}"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "changing_frame_0_balazs.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/misc/changing_frame_0_balazs.m", "size": 6227, "source_encoding": "utf_8", "md5": "4da913c737f7e68564f0e3529a5fd541", "text": "function changing_frame_0_balazs()\n\nfr0 = [];\n\nload('stimStartFrames');\nload('trials_ind');\nload('norm_frame');\nload('rois_OCIA_old');\nload('ROIs_registered');\n\nfr2=57:58;\nfr_dev2 = nan(size(fr_dev)); %#ok<*NODEF>\nstimFrames = 59:68;\nfixedStartFrame = max(stimStartFrame);\n% trialTypes = { 'hit', 'CR' };\ntrialTypes = { 'hit' };\n\nnMaxTrials = 1;\n\n% exclTrials = { [4 5 7 8 11 12 15 19 22 27 28 29], [] };\nexclTrials = { [], [] };\n\ndoSinglePlots = true;\ndoAvgPlot = false;\n\navgYLims = [-0.01 0.01];\ntrialYLims = [-0.05 0.05]; %#ok<*NASGU>\n\navgCLim = [-0.001 0.001];\ntrialCLim = [-0.005 0.01]; %#ok<*NASGU>\n\n\n% ROINames = { 'V1', 'M2', 'A1', 'S1FL' };\n% ROIColors = { 'b', 'k', 'g', 'r' };\n% ROINames = { 'V1', 'A1', 'S1FL' };\n% ROIColors = { 'b', 'g', 'c' };\nROINames = { };\nROIColors = { };\n\n\n\nROI2Inds = 1 : 6;\nROIColors2 = [0 1 1; 1 0 1; 0 1 0; 1 1 0; 1 0 0; 0 0 1];\n% ROI2Inds = [6, 3, 1];\n% ROIColors2 = [0 0 1; 0 1 0; 0 1 1;];\n\n\nROIs = ROIs(ROI2Inds, :);\n\n\n%% HIT trials\nfor iType = 1 : numel(trialTypes);\n \n listTrials = dir(['cond_' trialTypes{iType} '_trial*']);\n cond_avg = zeros(256, 256, 240);\n cond_avg_0 = zeros(256, 256, 240);\n cond_avgNoAlign = zeros(256, 256, 240);\n cond_avgNoAlign_0 = zeros(256, 256, 240);\n nTrials = 0;\n trialInd = eval(['tr_', trialTypes{iType}]);\n\n for iTrial = 1 : min(nMaxTrials, size(listTrials, 1));\n\n if ismember(iTrial, exclTrials{iType}); continue; end;\n\n trialPath = sprintf('cond_%s_trial%d.mat', trialTypes{iType}, iTrial);\n if ~exist(trialPath, 'file'); continue; end;\n \n fprintf('Loading trial %s %03d ...\\n', trialTypes{iType}, iTrial);\n load(trialPath);\n\n % reset the baseline\n tr = tr .* repmat(fr_dev(:, :, trialInd(iTrial)), [1, 1, size(tr, 3)]);\n trNoAlign = tr;\n\n % re-align frames\n stimStartFrameTrial = stimStartFrame(trialInd(iTrial));\n nFramesDiff = fixedStartFrame - stimStartFrameTrial;\n if nFramesDiff > 0;\n tr = cat(3, nan(size(tr, 1), size(tr, 2), nFramesDiff), tr(:, :, 1 : (end - nFramesDiff)));\n elseif nFramesDiff < 0;\n tr = cat(3, tr(:, :, (nFramesDiff + 1) : end), nan(size(tr, 1), size(tr, 2), nFramesDiff));\n end;\n\n % re-normalize with baseline\n tr0 = tr;\n tr0 = tr0 ./ repmat(fr_dev(:, :, trialInd(iTrial)), [1 1 size(tr0, 3)]);\n fr_dev2(:, :, trialInd(iTrial)) = nanmean(tr(:, :, fr2), 3);\n tr = tr ./ repmat(fr_dev2(:, :, trialInd(iTrial)), [1 1 size(tr, 3)]);\n % re-normalize with baseline\n trNoAlign0 = trNoAlign;\n trNoAlign0 = trNoAlign0 ./ repmat(fr_dev(:, :, trialInd(iTrial)), [1 1 size(trNoAlign0, 3)]);\n fr_dev2(:, :, trialInd(iTrial)) = nanmean(trNoAlign(:, :, fr2), 3);\n trNoAlign = trNoAlign ./ repmat(fr_dev2(:, :, trialInd(iTrial)), [1 1 size(trNoAlign, 3)]);\n\n % add average\n cond_avg = cond_avg + tr;\n cond_avg_0 = cond_avg_0 + tr0;\n cond_avgNoAlign = cond_avgNoAlign + tr;\n cond_avgNoAlign_0 = cond_avgNoAlign_0 + tr0;\n nTrials = nTrials + 1;\n\n % plot\n if doSinglePlots;\n createPlot(sprintf('%s %03d - trial %03d', trialTypes{iType}, iTrial, trialInd(iTrial)), ...\n tr0, tr, trNoAlign0, trNoAlign, fr0, fr2, stimFrames, roi_V1, roi_M2, roi_A1, roi_S1FL, ROINames, ...\n ROIColors, ROIColors2, ROIs, trialCLim, trialYLims); %#ok<*UNRCH>\n\n end;\n\n end\n\n % compute average\n cond_avg = cond_avg ./ nTrials;\n cond_avg_0 = cond_avg_0 ./ nTrials;\n cond_avgNoAlign = cond_avgNoAlign ./ nTrials;\n cond_avgNoAlign_0 = cond_avgNoAlign_0 ./ nTrials;\n\n % plot\n if doAvgPlot;\n\n createPlot(sprintf('%s average - %03d trial(s)', trialTypes{iType}, nTrials), ...\n cond_avg_0, cond_avg, cond_avgNoAlign, cond_avgNoAlign_0, fr0, fr2, stimFrames, ...\n roi_V1, roi_M2, roi_A1, roi_S1FL, ROINames, ROIColors, ROIColors2, ROIs, avgCLim, avgYLims);\n\n end;\n\nend;\n\nend\n\n\nfunction createPlot(figTitle, dataFr0, dataFr2, dataNoAlignFr0, dataNoAlignFr2, fr0, fr2, ...\n stimFrames, roi_V1, roi_M2, roi_A1, roi_S1FL, ROINames, ROIColors, ROIColors2, ROIs, cLim, yLims) %#ok\n\nsubPlotTitles = { sprintf('Sound aligned, norm. %02d:%02d', fr0(1), fr0(end)), ...\nsprintf('Sound aligned, norm. %02d:%02d, stim. %02d:%02d', fr0([1 end]), stimFrames([1 end])), ...\nsprintf('Trig. aligned, norm %02d:%02d', fr2([1 end])), ...\nsprintf('Trig. aligned, norm. %02d:%02d, stim. %02d:%02d', fr2([1 end]), stimFrames([1 end])) };\n\nlegendParams = { [ROINames ROIs(:, 1)'], 'Location', 'NorthOutside', 'Orientation', 'Horizontal', 'FontSize', 6 };\n \nfigure('Name', figTitle, 'NumberTitle', 'off', 'Position', [30 100 1850 970]);\n\ndataToPlot = { dataFr0, dataFr2, dataNoAlignFr0, dataNoAlignFr2 };\n\niSubPlot = 1;\nfor iData = 1 : 4;\n \n subplot(2, 4, iSubPlot);\n title(subPlotTitles{1});\n hold on;\n linTr = reshape(dataToPlot{iData}, size(dataToPlot{iData}, 2) * size(dataToPlot{iData}, 2), size(dataToPlot{iData}, 3));\n for iROI = 1 : numel(ROINames);\n plot(squeeze(nanmean(linTr(eval(['roi_' ROINames{iROI}]), :), 1)) - 1, ['--', ROIColors{iROI}]);\n end;\n for iROI = 1 : size(ROIs, 1);\n trace = nanmean(GetRoiTimeseries(dataFr2, ROIs{iROI, 3})) - 1;\n plot(trace, 'Color', ROIColors2(iROI, :), 'LineStyle', '-');\n end;\n plot(repmat(stimFrames(1), 1, 2), yLims, ':k');\n plot(repmat(stimFrames(end), 1, 2), yLims, ':k');\n set(gca, 'YLim', yLims);\n hold off;\n legend(legendParams{:});\n iSubPlot = iSubPlot + 1;\n\n subplot(2, 4, iSubPlot);\n title(subPlotTitles{2});\n imagesc(1 : 256, 1 : 256, smoothn(nanmean(dataToPlot{iData}(:, :, stimFrames) - 1, 3), [5 5], 'Gauss'), cLim);\n colorbar();\n axis('square');\n colormap(mapgeog);\n hold on;\n for iROI = 1 : numel(ROINames);\n h = zeros(256 * 256, 1);\n h(eval(['roi_' ROINames{iROI}])) = 1;\n contour(reshape(h, 256, 256), ROIColors{iROI});\n end;\n for iROI = 1 : size(ROIs, 1);\n contour(ROIs{iROI, 3}, 'Color', ROIColors2(iROI, :), 'LineStyle', '-');\n end;\n hold off;\n iSubPlot = iSubPlot + 1;\n \nend;\n\nend\n\n\n\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "BEGetTrialInfo.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/BEGetTrialInfo.m", "size": 2254, "source_encoding": "utf_8", "md5": "ecb6e0a8914941c49d705be87c4ca6df", "text": "%% #BEGetTrialInfo\nfunction trialInfo = BEGetTrialInfo(this, iTrial)\n\n% default is empty\nfreq = ''; spotIndex = ''; isTargetOrNTones = ''; resp = ''; respTime = ''; corr = ''; rew = '';\n\nif iTrial > 0 && iTrial <= this.be.config.training.nTrials && isfield(this.be, 'stims');\n \n if isfield(this.be, 'spotMatrix') && ~isempty(this.be.spotMatrix);\n spotIndex = this.be.spotMatrix(iTrial);\n end;\n \n freq = round(this.be.config.tone.freqs(this.be.stims(iTrial)) / 1000);\n \n % no goStim = no behavior\n if ~isempty(this.be.config.tone.goStim);\n \n % oddball discrimination\n if isfield(this.be.config.tone, 'oddProba') && this.be.config.tone.oddProba > 0;\n \n isTargetOrNTones = double(this.be.stims(iTrial) ~= this.be.odds(iTrial) && this.be.config.tone.goStim);\n \n % frequency/cloud of tone discrimination\n else\n \n isTargetOrNTones = double(ismember(this.be.stims(iTrial), this.be.config.tone.goStim));\n \n end;\n \n elseif strcmp(this.be.taskType, 'cotOdd') && numel(this.be.nTones) > 1;\n \n % fill with number of tones\n isTargetOrNTones = this.be.nTones(iTrial);\n \n end;\n\n if ~isempty(this.be.config.tone.goStim) && isfield(this.be, 'resps') && ~isnan(this.be.resps(iTrial));\n resp = this.be.resps(iTrial);\n if ~isnan(this.be.respDelays(iTrial));\n respTime = sprintf('%.2f', this.be.respDelays(iTrial));\n else\n respTime = ' - ';\n end;\n corr = double((isTargetOrNTones && resp) || (~isTargetOrNTones && ~resp));\n if corr; corr = ' T '; else corr = ' F '; end;\n if ~isnan(this.be.giveRewards(iTrial)) && this.be.giveRewards(iTrial);\n rew = ' T ';\n else\n rew = ' F';\n end;\n if this.be.resps(iTrial); resp = ' T '; else resp = ' F'; end;\n if this.be.autoRewardGiven(iTrial) && strcmp(corr, ' T '); corr = ' F*'; end;\n end;\n if isTargetOrNTones; isTargetOrNTones = ' T '; else isTargetOrNTones = ' F'; end;\n \n% no trial number\nelse\n \n iTrial = '';\n \nend;\n\ntrialInfo = {iTrial, spotIndex, freq, isTargetOrNTones, resp, respTime, corr, rew};\n\nend\n\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "DWMatchBehavTrialsToImagingData.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/DWMatchBehavTrialsToImagingData.m", "size": 6399, "source_encoding": "utf_8", "md5": "afd7fe9d63c0d81ca6439a845346cc6f", "text": "function DWMatchBehavTrialsToImagingData(this)\n% DWMatchBehavTrialsToImagingData - [no description]\n%\n% DWMatchBehavTrialsToImagingData(this)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n% match the behavior trials and the data files\n\n% update the wait bar\nDWWaitBar(this, 0);\n \n% get the behavior rows with no animal ID and figure it out from the data structure\nbehavRows = DWFilterTable(this, 'animal !~= \\w+ AND rowType = Behavior data');\nfor iBehavRow = 1 : size(behavRows, 1);\n % get the DataWatcher table's row index for this row\n iDWRow = str2double(get(this, iBehavRow, 'rowNum', behavRows));\n % load the row\n DWLoadRow(this, iDWRow, 'full');\n % get the behavior data\n behavData = getData(this, iDWRow, 'behav', 'data');\n % set the new animal ID\n set(this, iDWRow, 'animal', regexprep(['mou_bl_', behavData.animalID], 'mou_bl_mou_bl', 'mou_bl'));\nend;\n\n% get the list of all animals\nuniqueAnimals = get(this, 'animal');\nif ~iscell(uniqueAnimals) && ischar(uniqueAnimals) && ~isempty(uniqueAnimals); uniqueAnimals = { uniqueAnimals }; end;\nuniqueAnimals(cellfun(@isempty, uniqueAnimals)) = { '' };\nuniqueAnimals = unique(uniqueAnimals);\n\n% get the list of all days\nuniqueDays = get(this, 'day');\nif ~iscell(uniqueDays) && ischar(uniqueDays) && ~isempty(uniqueDays); uniqueDays = { uniqueDays }; end;\nuniqueDays(cellfun(@isempty, uniqueDays)) = [];\nuniqueDays = unique(uniqueDays);\n\n% get the selected animal IDs\nselectedAnimalIDs = this.dw.animalIDs(get(this.GUI.handles.dw.filt.animalID, 'Value'));\n% if the dash '-' is selected, select all IDs\nif numel(selectedAnimalIDs) == 1 && strcmp(selectedAnimalIDs{1}, '-');\n selectedAnimalIDs = uniqueAnimals;\nend;\n\n% get the selected day IDs\nselectedDayIDs = this.dw.dayIDs(get(this.GUI.handles.dw.filt.dayID, 'Value'));\n% if the dash '-' is selected, select all IDs\nif numel(selectedDayIDs) == 1 && strcmp(selectedDayIDs{1}, '-');\n selectedDayIDs = uniqueDays;\nend;\n\n% cell array storing all the informations to process each session\nallSessionInfos = cell(1000, 6);\n\n% first get all the information for each sessions to process\n% go through each animal\nfor iAnim = 1 : numel(uniqueAnimals); \n animalID = uniqueAnimals{iAnim}; % get the current animal\n\n % skip irrelevant animal IDs\n if ~ismember(animalID, selectedAnimalIDs); continue; end;\n \n % go through each day\n for iDay = 1 : numel(uniqueDays); \n dayID = uniqueDays{iDay}; % get the current day\n\n % skip irrelevant days\n if ~ismember(dayID, selectedDayIDs); continue; end;\n\n % empty spot filters\n spotID = '';\n spotFilter = '';\n\n % create animal filter\n if isempty(animalID);\n animalFilter = 'animal !~= \\w AND ';\n else\n animalFilter = sprintf('animal = %s AND ', animalID);\n end;\n\n % use different filters for different locations\n locFilter = {\n '', '';\n };\n if ismember('loc', this.dw.tableIDs);\n locFilter = {\n '', ' AND loc !~= \\w+'; \n 'local', ' AND loc = local';\n 'remote', ' AND loc = remote';\n }; \n end;\n \n % go through each location filter\n for iLocFilter = 1 : size(locFilter, 1);\n \n % get the imaging rows indexes\n imagingRows = DWFilterTable(this, ...\n sprintf('%s%sday = %s AND rowType = Imaging data AND runType !~= \\\\w+%s', ...\n animalFilter, spotFilter, dayID, locFilter{iLocFilter, 2}));\n imagingRowIndexes = str2double(get(this, 'all', 'rowNum', imagingRows));\n\n % if no imaging data, skip\n if isempty(imagingRowIndexes) || any(isnan(imagingRowIndexes));\n continue;\n % if only one row found, label it as session 1\n elseif numel(imagingRowIndexes) == 1;\n sessIDs = 1; \n % if several rows, cluster them by session using time\n else\n sessIDs = clusterRowsBySession(this, imagingRowIndexes);\n end;\n\n % go through session by session\n for iSess = 1 : size(unique(sessIDs), 1);\n % get the indexes of this session\n sessRowIndexes = imagingRowIndexes(sessIDs == iSess);\n % store the data to process\n allSessionInfos(end + 1, :) = { animalID, dayID, spotID, iSess, sessRowIndexes, ...\n locFilter{iLocFilter, 2} }; %#ok\n end;\n \n end; % end of location filter\n end; % end of day loop\nend; % end of animal loop\n\n% remove empty lines\nallSessionInfos(cellfun(@isempty, allSessionInfos(:, 1)), :) = [];\nnTotSessions = size(allSessionInfos, 1);\n\n% match all sessions\nfor iTotSess = 1 : nTotSessions;\n \n % match the behavior trials using the stored informations\n DWMatchBehavTrialsToImagingDataForSession(this, allSessionInfos{iTotSess, :});\n \n % update the wait bar\n DWWaitBar(this, 99 * (iTotSess / nTotSessions));\n \nend;\n\n% % remove raw behavior data for the current session\n% behavRows = DWFilterTable(this, 'rowType = Behavior data');\n% DWFlushData(this, str2double(get(this, 'all', 'rowNum', behavRows)), false, 'behav');\n\n% final update of the wait bar\nDWWaitBar(this, 100);\n\nend\n\n%% - #clusterRowsBySession\nfunction sessIDs = clusterRowsBySession(this, rowNums)\n\n% do not process if not at least 2 rows\nif numel(rowNums) < 2;\n sessIDs = repmat('1', numel(rowNums), 1);\n return;\nend;\n \n% separate rows into morning and afternoon sessions\nnUnknRows = size(rowNums, 1);\ndateNums = zeros(nUnknRows, 1);\nfor iUnknRow = 1 : nUnknRows;\n dateAndTime = get(this, rowNums(iUnknRow), { 'day', 'time' });\n dateNums(iUnknRow) = datenum(sprintf('%s__%s', dateAndTime{:}), 'yyyy_mm_dd__HH_MM_SS');\nend;\nsessIDs = clusterdata(dateNums, 'maxclust', 2);\nnearbySessDiffInHours = (dn2unix(dateNums(find(sessIDs == sessIDs(end), 1, 'first'))) ...\n - dn2unix(dateNums(find(sessIDs == sessIDs(1), 1, 'last')))) / 1000 / 60 / 60;\n% if sessions are too close, it means that it was a single session with a missing trial/interruption\nif nearbySessDiffInHours < 3; % minimum 3 hours between sessions\n sessIDs = clusterdata(dateNums, 'maxclust', 1);\nend;\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "DWMatchBehavTrialsToImagingDataForSession.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/DWMatchBehavTrialsToImagingDataForSession.m", "size": 16055, "source_encoding": "utf_8", "md5": "3a28c46a1d44236c27a5d27a8ab6b9fb", "text": "%% - #DWMatchBehavTrialsToImagingDataForSession\nfunction DWMatchBehavTrialsToImagingDataForSession(this, animalID, dayID, spotID, iSess, rowIndexes, locFilter)\n\n% get the number of imaging trials found\nnTrialsFound = size(rowIndexes, 1);\n\n% abort if no trials\nif ~nTrialsFound; return; end;\n\n% find the right behavior out file : get the behavior rows\nbehavRows = DWFilterTable(this, sprintf('animal = %s AND day = %s AND rowType = Behavior data%s', animalID, dayID, ...\n locFilter));\nnBehavs = size(behavRows, 1); % count them\n\n% go through all behavior files by comparing behavior trial and data file times\nallBehavUNIXTimes = []; % behaviorally recorded times\nallBehavBelongInds = []; % behavior file IDs (B01, B02, etc.)\n% extract all behavior times from the behavior files\nfor iBehav = 1 : nBehavs;\n \n % get the DataWatcher table's row index for this row\n iDWRow = str2double(get(this, iBehav, 'rowNum', behavRows));\n \n % make sure behavior data is loaded\n DWLoadRow(this, iDWRow, 'full');\n % get the output structure\n behavData = getData(this, iDWRow, 'behav', 'data');\n \n % skip empty structures\n if isempty(behavData); continue; end;\n \n % find the end timing name (backward compatibility)\n fieldName = 'endImagExp';\n if ~isfield(behavData.times, fieldName);\n fieldName = 'endImagExpect';\n end;\n if ~isfield(behavData.times, fieldName);\n fieldName = 'imgStopExp';\n end;\n \n if ~isfield(behavData.times, fieldName);\n showWarning(this, 'OCIA:DW:DWMatchBehavTrialsToImagingDataForSession:NoEndImagingFieldName', ...\n sprintf('Cannot find an imaging end time field for row %03d: %s.', iDWRow, DWGetRowID(this, iDWRow)));\n continue;\n end;\n \n % extract the behavior UNIX times\n behavUNIXTimes = (behavData.times.(fieldName) + behavData.times.start) * 1000;\n behavUNIXTimes(behavUNIXTimes == 0) = [];\n % concatenate the times\n allBehavUNIXTimes = [allBehavUNIXTimes behavUNIXTimes]; %#ok\n allBehavBelongInds = [allBehavBelongInds repmat(iBehav, 1, size(behavUNIXTimes, 2))]; %#ok\n \nend;\n\n% remove NaN trials because they were not recorded\nallBehavBelongInds(isnan(allBehavUNIXTimes)) = [];\nallBehavUNIXTimes(isnan(allBehavUNIXTimes)) = [];\n\n% use a time threshold to check for time mismatchs\ntimeThresh = this.dw.trialMatchingTimeDifferenceThreshold;\n\n% minimum time differences between behavior timestamps and data file timestamps\n[allMinTDiffs, allMinTInds] = compareImgFileTimeWithBehavTimes(this, allBehavUNIXTimes, rowIndexes, timeThresh);\n\n% abort if no rows to process\nif isempty(allMinTDiffs) || isempty(allMinTInds); return; end;\n\n% best fitting behavior file are the ones with less than 3 hours \niBestBehav = unique(allBehavBelongInds(allMinTDiffs < 3 * 60 * 60));\nnMatchBehavs = size(iBestBehav, 2);\niBestBehavMask = ismember(allBehavBelongInds, iBestBehav);\n\n% abort if no behavior match found\nif isempty(iBestBehav); return; end;\n\n% extract the adjusted time differences\nminTDiff = abs(allMinTDiffs(iBestBehavMask) - nanmedian(allMinTDiffs(iBestBehavMask)));\n\n% calculate the number of expected trials\nnTrialsExp = 0;\nfor iBehav = 1 : nMatchBehavs;\n % get the DataWatcher table's row index for this row\n iDWRow = str2double(get(this, iBestBehav(iBehav), 'rowNum', behavRows));\n % get the output structure\n behavData = getData(this, iDWRow, 'behav', 'data');\n % count the number of trials that are expected\n nTrialsExp = nTrialsExp + find(~isnan(behavData.times.end) & ~isnan(behavData.resps), 1, 'last');\nend;\n\n% calculate the difference in trial numbers\ndiffTrials = nTrialsExp - nTrialsFound;\n\n% get whether the difference is in missing or extra trials\nmissExtraInd = []; % indexes of rows that are missing or extra\nmissExtraLabel = ''; % label specifying whether the trials are missing or extra\n\n% no trial number difference and no timing mismatch => no missmatch\nif diffTrials == 0 && ~any(minTDiff > timeThresh);\n % nothing to do\n \n% missing/extra trials\nelseif diffTrials ~= 0;\n \n % difference is positive => missing trials\n if diffTrials > 0;\n missExtraLabel = 'missing'; % label the mismatch\n % loop to find all missing trials using a stepwise decreasing time threshold\n while size(missExtraInd, 1) < diffTrials;\n missExtraInd = find(minTDiff > timeThresh); % get the missing trials\n timeThresh = timeThresh - 100; % update the threshold\n end;\n \n % get the most different missing trials\n [~, missExtraIndOrdered] = sort(minTDiff(missExtraInd)); % sort by most different timing\n missExtraInd = sort(missExtraInd(missExtraIndOrdered(end - diffTrials + 1 : end)));\n \n% % get the first missing trials\n% missExtraInd = sort(missExtraInd(1 : abs(diffTrials)));\n \n % difference is negative => extra trials\n else\n missExtraLabel = 'extra'; % label the mismatch\n diffTrials = - diffTrials; % invert the sign\n % find the extra trials\n missExtraInd = find(~ismember(1 : nTrialsExp, allMinTInds(iBestBehavMask)), diffTrials);\n % if no extra trials found, try to find them using setdiff\n if isempty(missExtraInd); missExtraInd = setdiff(1 : nTrialsFound, allMinTInds); end;\n % only take the required number of different trials\n missExtraInd = sort(missExtraInd(1 : abs(diffTrials)));\n end;\n\n % create a list of mismatched indexes\n missList = regexprep(sprintf('%02d ', missExtraInd), ' $', '');\n % if the list is too long, make it shorter: find the space characters\n spaceCharStart = find(missList == ' ', 3, 'first');\n % find the second and before last space character\n if isempty(spaceCharStart); spaceCharStart = min(8, round(numel(missList) * 0.5));\n else spaceCharStart = spaceCharStart(end);\n end;\n spaceCharEnd = find(missList == ' ', 3, 'last');\n if isempty(spaceCharEnd); spaceCharEnd = max(numel(missList) - 8, round(numel(missList) * 0.5));\n else spaceCharEnd = spaceCharEnd(1);\n end;\n if size(missList, 2) > 30; missList = [missList(1 : spaceCharStart) ' ... ' missList(spaceCharEnd : end)]; end;\n % show the warning\n showWarning(this, 'OCIA:DWMatchBehavTrialsToImagingDataForSession:MissingTrials', ...\n sprintf('Found %d %s trial(s) ( %s ) for %s %s %s session %d.', diffTrials, missExtraLabel, ...\n missList, animalID, dayID, spotID, iSess));\nend;\n\n% label the stimuli\nif strcmp(behavData.taskType, 'cotOdd');\n stimLabels = { 'lowStd ', 'highStd' };\nelse\n stimLabels = { 'low', 'high' };\nend;\n\n% create the annotations for the imaging rows\nbehavIDs = cell(nTrialsExp, 1);\nrunTypes = cell(nTrialsExp, 1);\ntrialNums = cell(nTrialsExp, 1);\nspotIDs = cell(nTrialsExp, 1);\nbehavInfo = cell(nTrialsExp, 1);\n\n% initialize the current behavior data to use for annotation\niBehav = 1;\niDWRowBehav = str2double(get(this, iBestBehav(iBehav), 'rowNum', behavRows)); % get the DW table's row index\nbehavID = DWGetRowID(this, iDWRowBehav); % get the behavior row's ID\nbehavData = getData(this, iDWRowBehav, 'behav', 'data'); % get the behavior data\ncurrMaxTrial = find(~isnan(behavData.times.end) & ~isnan(behavData.resps), 1, 'last'); % get the number of trials for this behavior\n\n% loop through all trials\niTrial = 1;\nfor iTotTrial = 1 : nTrialsExp; \n % annotate this trial using the behavior's informations\n behavIDs{iTotTrial} = behavID;\n runTypes{iTotTrial} = 'Trial';\n trialNums{iTotTrial} = sprintf('%02d', iTrial);\n spotIDs{iTotTrial} = sprintf('spot%02d', behavData.spotMatrix(iTrial));\n\n % gather some information about the behavior\n behavInfo{iTotTrial} = sprintf('[ %s', stimLabels{behavData.stims(iTrial)});\n \n % response type\n if ~isnan(behavData.respTypes(iTrial)); \n % target\n if ismember(behavData.respTypes(iTrial), [1 4]);\n behavInfo{iTotTrial} = sprintf('%s / targ', behavInfo{iTotTrial}); \n % distractor\n elseif ismember(behavData.respTypes(iTrial), [2 3]);\n behavInfo{iTotTrial} = sprintf('%s / distr', behavInfo{iTotTrial});\n end; \n % correct\n if ismember(behavData.respTypes(iTrial), [1 2]);\n behavInfo{iTotTrial} = sprintf('%s / corr', behavInfo{iTotTrial}); \n % wrong\n elseif ismember(behavData.respTypes(iTrial), [3 4]);\n behavInfo{iTotTrial} = sprintf('%s / false', behavInfo{iTotTrial});\n end; \n end;\n \n % cloud of tones oddball case\n if strcmp(behavData.taskType, 'cotOdd') && numel(behavData.nTones) >= iTrial;\n behavInfo{iTotTrial} = sprintf('%s / %02d tones', behavInfo{iTotTrial}, behavData.nTones(iTrial));\n end;\n \n % close the information section\n behavInfo{iTotTrial} = sprintf('%s ]', behavInfo{iTotTrial});\n\n % update the trial count\n iTrial = iTrial + 1;\n \n % if we reach the start of a new behavior file\n if iTrial > currMaxTrial && iBehav < nMatchBehavs;\n \n % update the current behavior data to use for annotation\n iTrial = 1;\n iBehav = iBehav + 1;\n iDWRowBehav = str2double(get(this, iBestBehav(iBehav), 'rowNum', behavRows)); % get the DW table's row index\n behavID = DWGetRowID(this, iDWRowBehav); % get the behavior row's ID\n behavData = getData(this, iDWRowBehav, 'behav', 'data'); % get the behavior data\n currMaxTrial = find(~isnan(behavData.times.end) & ~isnan(behavData.resps), 1, 'last'); % get the number of trials for this behavior\n end;\nend;\n\n% re-order the rows according to the minimum time indexes\nrowIndexes = rowIndexes(allMinTInds(iBestBehavMask));\n\n% remove the annotations for the missing trials\nif strcmp(missExtraLabel, 'missing');\n \n behavIDs(missExtraInd) = [];\n runTypes(missExtraInd) = [];\n trialNums(missExtraInd) = [];\n spotIDs(missExtraInd) = [];\n behavInfo(missExtraInd) = []; \n rowIndexes(missExtraInd) = [];\n \nend;\n\n% update in the table\nset(this, rowIndexes, 'behav', behavIDs);\nset(this, rowIndexes, 'runType', runTypes);\nset(this, rowIndexes, 'runNum', trialNums);\nset(this, rowIndexes, 'spot', spotIDs);\nset(this, rowIndexes, 'comments', behavInfo);\n\n%% extract behavior data to imaging rows and get spot ID for behavior rows\n% go through each behavior file and try to get a spot ID annotation for them\nfor iBehav = 1 : nBehavs;\n % get the DataWatcher table's row index for this row\n iDWRowBehav = str2double(get(this, iBehav, 'rowNum', behavRows)); % get the DW table's row index\n behavID = DWGetRowID(this, iDWRowBehav); % get the behavior row's ID\n \n % get the imaging trial rows that have a matching behavior ID\n trialRows = DWFilterTable(this, sprintf('rowType = Imaging data AND behav = %s AND runNum ~= \\\\d+', behavID)); \n \n % skip the process if no imaging rows have this behavior ID\n if isempty(trialRows); continue; end;\n \n % get the behavior data\n behavDataForRow = getData(this, iDWRowBehav, 'behav', 'data');\n \n % go through each trial\n for iTrialLoop = 1 : size(trialRows, 1);\n iTrial = str2double(get(this, iTrialLoop, 'runNum', trialRows)); % get the trial number\n iDWRowTrial = str2double(get(this, iTrialLoop, 'rowNum', trialRows)); % get the row's index\n % extract the behavior data for this trial and store it in the imaging row's data\n setData(this, iDWRowTrial, 'behavExtr', 'data', DWExtractBehavDataForImagingRow(this, iTrial, behavDataForRow));\n setData(this, iDWRowTrial, 'behavExtr', 'loadStatus', 'full');\n end;\n \n % if the behavior file does not have a spot annotation\n if isempty(get(this, iDWRowBehav, 'spot'));\n % create a spot annotation using the one from the frist trial\n set(this, iDWRowBehav, 'spot', get(this, iTrialLoop, 'spot', trialRows)); \n end;\n \nend;\n\nend\n\n%% - #compareImgFileTimeWithBehavTimes\nfunction [minTDiffs, minTInds] = compareImgFileTimeWithBehavTimes(this, behavUNIXTimes, DWTableRowInds, timeDiffThresh)\n\n% do not process if no rows\nDWTableRowInds(isnan(DWTableRowInds)) = []; % remove nans\nif isempty(DWTableRowInds);\n minTDiffs = [];\n minTInds = [];\n return;\nend;\n\nnTrialsExp = size(behavUNIXTimes, 2);\nnTrialsFound = size(DWTableRowInds, 1);\nfileTimes = arrayfun(@(i) dn2unix(datenum(sprintf('%s__%s', get(this, DWTableRowInds(i), 'day'), ...\n get(this, DWTableRowInds(i), 'time')), 'yyyy_mm_dd__HH_MM_SS')), 1 : nTrialsFound);\n% nFrames = arrayfun(@(i) str2double(regexprep(get(this, DWTableRowInds(i), 'dim'), '^\\d+x\\d+x', '')), 1 : nTrialsFound);\n% fileTimes = fileTimes(nFrames >= this.an.img.funcMovieNFramesLimit);\nminTDiffs = zeros(nTrialsExp, 1);\nminTInds = zeros(nTrialsExp, 1);\nfor iTrial = 1 : nTrialsExp;\n tDiffs = abs(behavUNIXTimes(iTrial) - fileTimes);\n [minTDiffs(iTrial), minTInds(iTrial)] = min(abs(tDiffs));\nend;\n\n%% show debug plot if required\nif get(this.GUI.handles.dw.SLROpts.procDataShowDebug, 'Value');\n figure('Name', 'Time comparison for trial matching', 'NumberTitle', 'off', 'WindowStyle', 'docked');\n \n % match lines\n lineHandles = plot([fileTimes(minTInds); behavUNIXTimes(1 : nTrialsExp)], ...\n [ones(1, nTrialsExp); 2 * ones(1, nTrialsExp)], 'green');\n hold on;\n \n % imaging files scatter\n filePointHandles = scatter(fileTimes, ones(1, numel(fileTimes)), 10, 's', 'blue', 'fill');\n fileTrialList = regexp(regexprep(sprintf('%d,', 1 : numel(fileTimes)), ',$', ''), ',', 'split');\n behavTrialList = regexp(regexprep(sprintf('%d,', 1 : numel(behavUNIXTimes)), ',$', ''), ',', 'split');\n text(fileTimes, ones(1, numel(fileTimes)) - 0.05, fileTrialList, 'FontSize', 5, ...\n 'HorizontalAlignment', 'center');\n \n % extract which are the deviant times\n deviantTimes = find(minTDiffs > timeDiffThresh);\n\n % time differences\n scaledTDiffs = linScale([0; timeDiffThresh; minTDiffs; max(minTDiffs)], 0, 0.5);\n timeDiffHandle = plot(behavUNIXTimes, scaledTDiffs(3 : end - 1) + 1.25, 'k', 'LineWidth', 1.5);\n plot([behavUNIXTimes(1) - 10E5 behavUNIXTimes(end) + 10E5], repmat(scaledTDiffs(1), 1, 2) + 1.25, ':k', 'LineWidth', 0.5);\n plot([behavUNIXTimes(1) - 10E5 behavUNIXTimes(end) + 10E5], repmat(scaledTDiffs(end), 1, 2) + 1.25, ':k', 'LineWidth', 0.5);\n text(behavUNIXTimes(1) - 10E5, scaledTDiffs(end) + 1.25, sprintf('%.1f', max(minTDiffs)), 'FontSize', 5, ...\n 'HorizontalAlignment', 'right');\n text(behavUNIXTimes(1) - 10E5, scaledTDiffs(1) + 1.25, '0.0', 'FontSize', 5, 'HorizontalAlignment', 'right');\n % threshold\n plot([behavUNIXTimes(1) - 10E5 behavUNIXTimes(end) + 10E5], repmat(scaledTDiffs(2), 1, 2) + 1.25, ':r', 'LineWidth', 0.5);\n text(behavUNIXTimes(1) - 10E5, scaledTDiffs(2) + 1.25, sprintf('%.1f', timeDiffThresh), 'FontSize', 5, ...\n 'HorizontalAlignment', 'right', 'Color', 'red');\n if ~isempty(deviantTimes);\n deviantTimesHandle = scatter(behavUNIXTimes(deviantTimes), scaledTDiffs(2 + deviantTimes) + 1.25, 65, 'red', ...\n 'filled');\n else\n deviantTimesHandle = [];\n end;\n \n \n % behavior trials scatter\n behavPointHandles = scatter(behavUNIXTimes, 2 * ones(1, numel(behavUNIXTimes)), 10, 's', 'red', 'fill');\n text(behavUNIXTimes, 2 * ones(1, numel(behavUNIXTimes)) + 0.05, behavTrialList, 'FontSize', 5, ...\n 'HorizontalAlignment', 'center');\n \n ylim([0.8 2.1]);\n if ~isempty(deviantTimesHandle);\n legend([filePointHandles, behavPointHandles, lineHandles(1), timeDiffHandle], ...\n { 'imaging files', 'behavior times', 'potential matches', 'time differences' });\n else\n legend([filePointHandles, behavPointHandles, lineHandles(1), timeDiffHandle, deviantTimesHandle], ...\n { 'imaging files', 'behavior times', 'potential matches', 'time differences', 'deviant time points' });\n end;\n hold off;\n \nend;\n\nend"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "INRunExp_standard.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/INRunExp_standard.m", "size": 6976, "source_encoding": "utf_8", "md5": "0ca07cd497925df810b83f5c082ea448", "text": "function INRunExp_standard(this)\n% INRunExp_standard - [no description]\n%\n% INRunExp_standard(this)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\no('#%s ...', mfilename, 3, this.verb);\n\n%% init\n% extract the parameters structure\nparams = this.in.standard;\ncomParams = this.in.common;\n\n% timing reference\nt0 = nowUNIX();\nthis.in.expStartTime = t0;\nthis.in.timestamp = datestr(unix2dn(t0), 'HHMMSS');\n\n% update experiment counter\nthis.in.common.expNumber = this.in.common.expNumber + 1;\n\n% stores the baseline 1 frames for each run\nthis.in.data.base1Frames = cell(params.nRuns, 1);\n% stores the baseline 2 frames for each run\nthis.in.data.base2Frames = cell(params.nRuns, 1);\n% stores the stimulus frames for each run\nthis.in.data.stimFrames = cell(params.nRuns, 1);\n\n% stores the DFF average frame for each run\nthis.in.data.baseDFFAvg = cell(params.nRuns, 1);\nthis.in.data.stimDFFAvg = cell(params.nRuns, 1);\n\n% set the include states\nthis.in.data.includeInAvg = ones(params.nRuns, 1);\n\n% initialize stimulation\nINInitStim(this);\n\n%% init camera\n% flush the previous data\nstop(this.in.camH);\nflushdata(this.in.camH);\n% switch to non-stop collection mode and set logging to memory\ntriggerconfig(this.in.camH, 'manual');\nset(this.in.camH, 'FramesPerTrigger', Inf, 'LoggingMode', 'memory');\n% start camera but it waits for trigger\nstart(this.in.camH);\n\n%% starting delay\nshowMessage(this, sprintf('%s | Intrinsic: starting delay (%.1f sec) ...', INGetTime(this), comParams.startDelay), ...\n 'yellow');\npause(comParams.startDelay);\nif ~this.in.expRunning; INEndExp(this); return; end;\n\n%% run loop\n% loop over all runs\nfor iRun = 1 : params.nRuns;\n\n % create the title string\n titleString = sprintf(' | Intrinsic: Run %02d/%02d:', iRun, params.nRuns);\n\n % collect the baseline frames\n showMessage(this, sprintf('%s%s baseline 1 frames collection ...', INGetTime(this), titleString), 'yellow');\n this.in.data.base1Frames{iRun} = collectData(this, params.baselineAvgDur);\n if ~this.in.expRunning; INEndExp(this); return; end;\n\n % wait until stimulus time\n showMessage(this, sprintf('%s%s waiting for second baseline ...', INGetTime(this), titleString), 'yellow');\n pause(params.baselineToStimDelay);\n if ~this.in.expRunning; INEndExp(this); return; end;\n\n % collect the baseline frames\n showMessage(this, sprintf('%s%s baseline 2 frames collection ...', INGetTime(this), titleString), 'yellow');\n this.in.data.base2Frames{iRun} = collectData(this, params.baselineAvgDur);\n % calculate DFF of baseline data\n this.in.data.baseDFFAvg{iRun} = getDFFAvg(this, this.in.data.base1Frames{iRun}, this.in.data.base2Frames{iRun});\n % display data\n INUpdateGUI(this);\n if ~this.in.expRunning; INEndExp(this); return; end;\n\n % wait until stimulus time\n showMessage(this, sprintf('%s%s waiting for stimulus time ...', INGetTime(this), titleString), 'yellow');\n pause(params.baselineToStimDelay);\n if ~this.in.expRunning; INEndExp(this); return; end;\n\n % stimulus\n showMessage(this, sprintf('%s%s stimulus ...', INGetTime(this), titleString), 'yellow');\n % play sound using TDT\n if strcmp(comParams.stimMode, 'TDT');\n % use the software trigger to launch the sound\n this.in.RP.SoftTrg(1);\n % wait for it to finish\n pause(params.stdStimDur);\n \n % play sound without TDT\n elseif strcmp(comParams.stimMode, 'soundCard');\n % blocking so that the program waits for the stimlus to finish\n this.in.audioplayer.playblocking();\n \n % send out a digital trigger\n elseif strcmp(comParams.stimMode, 'trigOut');\n outputSingleScan(this.in.daq.sessHandle, 1); % TTL high\n outputSingleScan(this.in.daq.sessHandle, 0); % back to TTL low\n % wait for it to finish\n pause(params.stdStimDur);\n \n end;\n if ~this.in.expRunning; INEndExp(this); return; end;\n\n % wait until stimulus data collection time\n showMessage(this, sprintf('%s%s waiting for stimulus collection time ...', INGetTime(this), titleString), 'yellow');\n pause(params.stimToStimAvgDelay);\n if ~this.in.expRunning; INEndExp(this); return; end;\n\n % collect the stimulus frames\n showMessage(this, sprintf('%s%s stimulus frames collection ...', INGetTime(this), titleString), 'yellow');\n this.in.data.stimFrames{iRun} = collectData(this, params.stimAvgDur);\n % calculate DFF of stimulus data\n this.in.data.stimDFFAvg{iRun} = getDFFAvg(this, this.in.data.base1Frames{iRun}, this.in.data.stimFrames{iRun});\n % display data\n INUpdateGUI(this);\n if ~this.in.expRunning; INEndExp(this); return; end;\n \n % wait the end period (recovery), unless it is the last run\n if iRun ~= params.nRuns;\n showMessage(this, sprintf('%s%s waiting for recovery period ...', INGetTime(this), titleString), 'yellow');\n pause(params.waitPeriod);\n end;\n if ~this.in.expRunning; INEndExp(this); return; end;\n\nend;\n\n% clean up and free ressources\nINCleanUp(this);\n\n%% spatial downsampling loop\nshowMessage(this, sprintf('%s | Intrinsic: spatial down-sampling ...', INGetTime(this)));\n% loop over all runs\nfor iRun = 1 : params.nRuns;\n this.in.data.base1Frames{iRun} = INSpatialDownSample(this, this.in.data.base1Frames{iRun});\n this.in.data.base2Frames{iRun} = INSpatialDownSample(this, this.in.data.base2Frames{iRun});\n this.in.data.stimFrames{iRun} = INSpatialDownSample(this, this.in.data.stimFrames{iRun});\nend;\nshowMessage(this, sprintf('%s | Intrinsic: spatial down-sampling done.', INGetTime(this)));\n\n% set flags, update counter and update GUI\nthis.in.expRunning = false;\nset(this.GUI.handles.in.paramPanElems.expNumber, 'String', sprintf('%d', this.in.common.expNumber)); % update in GUI\nset(this.GUI.handles.in.runExpBut, 'BackgroundColor', 'red', 'Value', 0);\nshowMessage(this, sprintf('%s | Intrinsic: experiment number %02d done !', INGetTime(this), this.in.common.expNumber));\n\nend\n\nfunction frames = collectData(this, collectDur)\n\n% collection start time\nt0 = nowUNIXSec();\n\n% start collecting\ntrigger(this.in.camH);\n\n% start waiting loop\nwhile nowUNIXSec() - t0 < collectDur;\n pause(0.01); % avoid full-speed looping\nend;\n\n% stop and collect frames\nstop(this.in.camH);\nframes = getdata(this.in.camH);\no(['#%s: collected ' regexprep(repmat('%02dx', 1, ndims(frames)), 'x$', '') ' frame(s) ...'], ...\n mfilename(), size(frames), 4, this.verb);\n\npause(0.02);\n\n% flush data\nflushdata(this.in.camH);\n% restart camera\nstart(this.in.camH);\n\nend\n\n% extracts the DFF average of the frames as (F2 - F1) / F1\nfunction DFFAvg = getDFFAvg(this, frames1, frames2)\n % average frames1 over time\n frames1 = INSpatialDownSample(this, nanmean(squeeze(frames1), 3)); \n % average frames2 over time\n frames2 = INSpatialDownSample(this, nanmean(squeeze(frames2), 3));\n \n %% calculate DFF\n DFFAvg = (frames2 - frames1) ./ frames1;\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "INSavePlot.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/INSavePlot.m", "size": 3579, "source_encoding": "utf_8", "md5": "4a457e0f84d96fe70d00758e8266075b", "text": "function INSavePlot(this, savePath, plotToSave, varargin)\n% INSavePlot - [no description]\n%\n% INSavePlot(this, savePath, plotToSave, varargin)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\n% if no save path has been provided, create a dialog to request one\nif isempty(savePath);\n % create the folder if it does not exist yet\n if exist(this.path.OCIASave, 'dir') ~= 7; mkdir(this.path.OCIASave); end;\n % create the dialog\n [saveName, savePath] = uiputfile('*.*', 'Select a path where to save the plot', this.path.OCIASave);\n if ischar(saveName)\n savePath = [savePath saveName];\n saveName = regexprep(saveName, '(\\.\\w{3})?$', '');\n else % otherwise abort the saving\n return;\n end;\nelse\n saveName = savePath;\nend;\n% clean up path and show message\nsavePath = strrep(savePath, '\\', '/');\nshowMessage(this, sprintf('Saving intrinsic plot to \"%s\" ...', savePath), 'yellow');\nsaveTic = tic; % for performance timing purposes\n\nfigName = saveName;\nsaveFig = figure('Name', figName, 'NumberTitle', 'off', 'Color', 'white', 'Units', 'pixels', ...\n 'Position', get(this.GUI.figH, 'Position'), 'Visible', 'off', 'MenuBar', 'none', 'Toolbar', 'none');\n\nanAxe = this.GUI.in.fouSubAxeHands.(plotToSave);\ninPanelChild = get(get(anAxe, 'Parent'), 'Children');\n% gather everything that doesn't belong to the Intrinsic panel's GUI (buttons)\ninPanelChild(~cellfun(@isempty, regexp(get(inPanelChild, 'Tag'), '^IN')) & inPanelChild ~= anAxe) = [];\n\n% if the panel has no child or only the Intrinsic's axe but it's hidden, then do not save anything\nif isempty(inPanelChild) || (numel(inPanelChild) == 1 && inPanelChild(1) == anAxe && strcmp(get(anAxe, 'Visible'), 'off'));\n showWarning(this, 'OCIA:INSavePlot:NothingToSave', ...\n sprintf('Cannot save analyser plot \"%s\" to \"%s\" because there is no plot to save.', figName, savePath));\n return;\nend;\n\n% copy objects one by one starting from the last one\nfor iObj = fliplr(1 : numel(inPanelChild));\n removeCallbacks(inPanelChild(iObj));\n copyobj(inPanelChild(iObj), saveFig);\nend;\n\n% copy the colormap\nset(saveFig, 'Colormap', get(this.GUI.figH, 'Colormap'));\n\nsaveFolder = regexprep(savePath, '/[\\w\\.]+$', '');\nif exist(saveFolder, 'dir') ~= 7; mkdir(saveFolder); end;\n\n% get extension\next = regexprep(regexp(savePath, '\\.(\\w+)$', 'match'), '^\\.', '');\n% if extension is supported by the export_fig function, use that\nif ~isempty(ext) && ~strcmp(ext, 'fig') && ~isempty(regexp(ext, 'png|pdf|jpg|eps|tif|bmp', 'once'));\n if numel(varargin) > 0 && isnumeric(varargin{1});\n resolution = sprintf('-r%d', varargin{1});\n else\n \tresolution = '-r150';\n end;\n if numel(varargin) > 1 && strcmpi(varargin{2}, 'noCrop');\n export_fig(savePath, ['-' ext], resolution, '-nocrop', saveFig);\n else\n export_fig(savePath, ['-' ext], resolution, saveFig);\n end;\n \n% otherwise save as figure\nelse \n savePath = [regexprep(savePath, ['\\.' ext '$'], ''), '.fig'];\n set(saveFig, 'Visible', 'on');\n saveas(saveFig, savePath);\n \nend;\nclose(saveFig);\n\nshowMessage(this, sprintf('Saving analyser plot to \"%s\" done (%.3f sec).', savePath, toc(saveTic)));\n \nend\n\nfunction removeCallbacks(elem)\n if isprop(elem, 'Callback'); set(elem, 'Callback', []); end;\n if isprop(elem, 'ButtonDownFcn'); set(elem, 'ButtonDownFcn', []); end;\n childElems = get(elem, 'Children');\n for iElem = 1 : numel(childElems);\n removeCallbacks(childElems(iElem));\n end;\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "JTUpdateVirtualJoints.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/JTUpdateVirtualJoints.m", "size": 5706, "source_encoding": "utf_8", "md5": "72e85fec6b3a1f27b93113ed88dc6252", "text": "function JTUpdateVirtualJoints(this, iFrame, iJointType)\r\n% JTUpdateVirtualJoints - [no description]\r\n%\r\n% JTUpdateVirtualJoints(this, iFrame, iJointType)\r\n%\r\n% [No description]\r\n%\r\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\r\n\r\n% show debug plots of virtual joints\r\nshowDebugPlot = 0;\n\n% get the joints' x coordinate\r\njoints = squeeze(this.jt.joints(:, iFrame, 1, iJointType));\n\r\n% loop through the joint handles\r\nfor iJoint = 1 : this.jt.nJoints;\n \r\n % if a joint coordinate is empty and it is a virtual joint and the previous and next coordinates are not empty,\r\n % get the virtual joint's coordinates\r\n if joints(iJoint) == 0 && this.jt.jointConfig{iJoint, 2} ...\r\n && joints(iJoint - 1) ~= 0 && joints(iJoint + 1) ~= 0;\n\r\n jointCoords = squeeze(this.jt.joints(:, iFrame, :, iJointType));\n p1 = jointCoords(iJoint - 1, :); % coordinates of the joint before\r\n p2 = jointCoords(iJoint + 1, :); % coordinates of the joint after\r\n r1 = this.jt.jointConfig{iJoint, 4}(1); % distance with the joint before\r\n r2 = this.jt.jointConfig{iJoint, 4}(2); % distance with the joint after\r\n\r\n o(['#JTUpdateVirtualJoints: trying to predict virtual joint %d with: p1: [%.1f,%.1f], p2: [%.1f,%.1f], ', ...\r\n 'd1: %.1f, d2: %.1f ...'], iJoint, p1, p2, r1, r2, 4, this.verb);\n\n % iteratively try to find the interesection point with increasing distances\r\n increaseStepR1 = r1 * 0.05; increaseStepR2 = r2 * 0.05; iLoop = 1; nMaxLoop = 10;\n intersects = {}; % default is empty\r\n while isempty(intersects) && iLoop < nMaxLoop;\n \r\n % try to get the joints\r\n [cx1, cy1, cx2, cy2, intersects] = calcVirtJoint(p1(1), p1(2), p2(1), p2(2), r1, r2); %#ok\r\n \r\n % if there is going to be another loop, increase distances\r\n if isempty(intersects) && iLoop < nMaxLoop;\n r1 = r1 + increaseStepR1;\n r2 = r2 + increaseStepR2;\n iLoop = iLoop + 1;\n end;\n \r\n end; % end while loop\r\n \r\n % show debug informations\r\n if showDebugPlot;\n \r\n axeH = this.GUI.handles.jt.axe; %#ok\r\n hold(axeH, 'on');\n \r\n % show the intersection circles\r\n commonArgs = {'FaceColor', 'none', 'EdgeColor', [0.3 1 0], 'Curvature', [1, 1]};\n rectangle('Parent', axeH, 'Position', [a - r1 b - r1 2 * r1 2 * r1], commonArgs{:});\n rectangle('Parent', axeH, 'Position', [c - r2 d - r2 2 * r2 2 * r2], commonArgs{:});\n \r\n % show the possible points\r\n r = 4;\n commonArgs = {'FaceColor', [0 0 1], 'EdgeColor', [0 0 1], 'Curvature', [1, 1]};\n rectangle('Parent', axeH, 'Position', [cx1 - r/2 cy1 - r/2 r r], commonArgs{:});\n rectangle('Parent', axeH, 'Position', [cx2 - r/2 cy2 - r/2 r r], commonArgs{:});\n \r\n hold(axeH, 'off');\n \r\n end;\n \r\n if isempty(intersects);\n o('#JTUpdateVirtualJoints: virtual joint %d could not be placed (iLoop: %d).', iJoint, iLoop, 2, this.verb);\n showWarning(this, 'OCIA:JT:JTUpdateVirtualJoints:VirtualJointImpossible', ...\r\n sprintf(['Impossible to get a virtual joint for joint %d with the distances: ', ...\r\n '%.1f and %.1f and coordinates: [%.1f,%.1f] and [%.1f,%.1f]!'], iJoint, r1, r2, p1, p2));\n % clear the joint coordinates\r\n this.jt.joints(iJoint, iFrame, :, iJointType) = [0 0];\n else\r\n o('#JTUpdateVirtualJoints: virtual joint %d is either at: c1 [%.1f,%.1f] or c2 [%.1f,%.1f] (iLoop: %d).', ...\r\n iJoint, intersects{1}, intersects{2}, iLoop, 3, this.verb);\n % save the joint coordinates\r\n this.jt.joints(iJoint, iFrame, :, iJointType) = intersects{1}; % hard coded, always the first intersect\r\n end;\n\n end; % end of virtual joint if condition\r\n \r\nend; % end of joint looping\r\n\r\nend\r\n\r\n% little functino to find the virtual joint by calculating the intersecitno of two circles\r\nfunction [cx1, cy1, cx2, cy2, intersects] = calcVirtJoint(a, b, c, d, r1, r2)\r\n\r\n cx1 = NaN; cy1 = NaN; cx2 = NaN; cy2 = NaN; intersects = {};\n\n % Finding the coordinates c (c1,c2) of the virtual joint is basically finding the intersection of two \r\n % circles centered on p1 (a,b) and p2 (c,d) with respective radius r1 and r2:\r\n %\r\n % (x - a)^2 + (y - b)^2 = r1^2 AND (x - c)^2 + (y - d)^2 = r2^2\r\n %\r\n % First express the distance D between the two circles :\r\n D = sqrt((c - a)^2 + (d - b)^2);\n\n % Inter sections only happen if:\r\n %\r\n % r1 + r2 > D AND D > |r1 - r2|\r\n %\r\n\r\n % check for intersection\r\n circlesIntersect = r1 + r2 >= D && D > abs(r1 - r2);\n if ~circlesIntersect;\n return;\n end;\n\n % To get the coordinates, first express gamma : \r\n gamma = 0.25 * sqrt((D + r1 + r2) * (D + r1 - r2) * (D - r1 + r2) * (-D + r1 + r2));\n\n % Then the coordinates can be calculated with :\r\n cx1 = ((a + c) / 2) + (((c - a) * (r1^2 - r2^2)) / (2 * D^2)) + ((2 * gamma * (b - d)) / D^2);\n cx2 = ((a + c) / 2) + (((c - a) * (r1^2 - r2^2)) / (2 * D^2)) - ((2 * gamma * (b - d)) / D^2);\n cy1 = ((b + d) / 2) + (((d - b) * (r1^2 - r2^2)) / (2 * D^2)) - ((2 * gamma * (a - c)) / D^2);\n cy2 = ((b + d) / 2) + (((d - b) * (r1^2 - r2^2)) / (2 * D^2)) + ((2 * gamma * (a - c)) / D^2);\n\n % The intersection points are then:\r\n intersects = {[cx1, cy1]; [cx2, cy2]};\n\nend\r\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "BELightPulse.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/BELightPulse.m", "size": 1073, "source_encoding": "utf_8", "md5": "7d7e8d6d47649bbc740a57b9bccf2f5e", "text": "function BELightPulse(this, pulseDur, IPI, nPulses)\n% BELightPulse - [no description]\n%\n% BELightPulse(this, pulseDur, IPI, nPulses)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\nimagTTLState = get(this.GUI.handles.be.imagTTL, 'Value');\no('#%s(): pulseDur %.3f, IPI %.3f, nPulses %d.', mfilename, pulseDur, IPI, nPulses, 2, this.verb);\n\nif this.be.hw.connected && isfield(this.be.hw, 'anOut');\n start(timer('Name', 'PulseTimer', 'TimerFcn', { @doPulse, this.be, pulseDur, imagTTLState }, ...\n 'Period', pulseDur + IPI, 'TasksToExecute', nPulses, 'ExecutionMode', 'fixedRate'));\nelse\n showWarning(this, 'OCIA:Behavior:LightHardwareDisconnected', 'Hardware is disconnected.');\n set(this.GUI.handles.be.light, 'BackgroundColor', 'red', 'Value', 0);\nend;\n\n\nend\n\nfunction doPulse(~, ~, be, pulseDur, imagTTLState)\n\nbe.hw.anOut.outputSingleScan([imagTTLState * 5, 1 * be.params.maxLight]);\npauseTicToc(pulseDur);\nbe.hw.anOut.outputSingleScan([imagTTLState * 5, 0 * be.params.maxLight]);\n \nend"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "INTestStim.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/INTestStim.m", "size": 3097, "source_encoding": "utf_8", "md5": "d3c965f0467534cb336f38b928666bc2", "text": "\nfunction INTestStim(this, ~, ~)\n% INTestStim - [no description]\n%\n% INTestStim(this)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\n% update button\nset(this.GUI.handles.in.testStimBut, 'Value', 1, 'Enable', 'off', 'BackgroundColor', 'yellow');\n% disable run exp button\nset(this.GUI.handles.in.runExpBut, 'Enable', 'off');\n\n% extract the parameters structure\ncomParams = this.in.common;\n\ntry\n \n % test stimulus differently depending on the stimulus mode\n switch comParams.stimMode;\n \n % play through the sound card\n case 'soundCard';\n\n % get the sound stimulus of the current setting\n [soundToPlay, sampFreq] = INGetSoundStim(this);\n if isempty(soundToPlay); return; end;\n % use MATLAB sound function\n this.in.audioplayer = audioplayer(soundToPlay, sampFreq);\n this.in.audioplayer.playblocking();\n \n % play by software triggering the TDT\n case { 'TDT', 'trigIn' };\n\n % get the sound stimulus of the current setting\n [soundToPlay, sampFreq] = INGetSoundStim(this);\n if isempty(soundToPlay); return; end;\n % 1 loop for standard mode and nSweeps for fourier mode\n nLoops = iff(strcmp(this.in.expMode, 'standard'), 1, this.in.fourier.nSweeps);\n % calculate wait time\n waitTime = 1.1 * numel(soundToPlay) * nLoops / sampFreq;\n % load stimulus\n this.in.RP = playTDTSound(soundToPlay, 0, this.GUI.figH, nLoops);\n % launch stimulus with software trigger\n this.in.RP.SoftTrg(1);\n \n % wait for sound to finish\n startWait = tic;\n while ~isempty(this.in.RP) && toc(startWait) < waitTime;\n pause(0.01);\n end;\n \n % send trigger out\n case 'trigOut';\n % show message\n showMessage(this, 'Intrinsic: sending out TTL ...', 'yellow');\n % suppress silly warning about on-demand channels\n warning('off', 'daq:Session:onDemandOnlyChannelsAdded');\n % create NI session with a digital channel\n this.in.daq.sessHandle = daq.createSession(this.in.daq.vendorName);\n addDigitalChannel(this.in.daq.sessHandle, this.in.daq.deviceID, this.in.daq.trigOutPort, 'OutputOnly');\n % restore silly warning\n warning('on', 'daq:Session:onDemandOnlyChannelsAdded');\n % init to TTL low\n outputSingleScan(this.in.daq.sessHandle, 0);\n % send trigger\n outputSingleScan(this.in.daq.sessHandle, 1); % TTL high\n outputSingleScan(this.in.daq.sessHandle, 0); % back to TTL low\n \n end;\n\n% if something failed, capture and abort but still clean up\ncatch err;\n \n showWarning(this, 'OCIA:INTestStim:TestFailed', ...\n sprintf('Intrinsic: error during testing of stimulation (\"%s\"): %s.', err.identifier, err.message));\n \nend;\n\n% release resources\nINCleanUp(this);\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "ANSavePlot.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/ANSavePlot.m", "size": 6041, "source_encoding": "utf_8", "md5": "3d1614ebf1f33d5130d6d4f323ecb622", "text": "function ANSavePlot(this, savePath, varargin)\n% ANSavePlot - [no description]\n%\n% ANSavePlot(this, savePath, varargin)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\n% if no save path has been provided, create a dialog to request one\nif isempty(savePath);\n % create the folder if it does not exist yet\n if exist(this.path.OCIASave, 'dir') ~= 7; mkdir(this.path.OCIASave); end;\n % create the dialog\n [saveName, savePath] = uiputfile('*.*', 'Select a path where to save the plot', this.path.OCIASave);\n if ischar(saveName)\n savePath = [savePath saveName];\n saveName = regexprep(saveName, '(\\.\\w{3})?$', '');\n else % otherwise abort the saving\n return;\n end;\nelse\n saveName = savePath;\nend;\n% clean up path and show message\nsavePath = strrep(savePath, '\\', '/');\nshowMessage(this, sprintf('Saving analyser plot to \"%s\" ...', savePath), 'yellow');\nsaveTic = tic; % for performance timing purposes\n\nfigName = saveName;\nif numel(varargin) > 0 && ~isempty(varargin{1}); figName = varargin{1}; end;\nsaveFig = figure('Name', figName, 'NumberTitle', 'off', 'Color', 'white', 'Units', 'pixels', ...\n 'Position', get(this.GUI.figH, 'Position'), 'Visible', 'off', 'MenuBar', 'none', 'Toolbar', 'none');\n\nanAxe = this.GUI.handles.an.axe;\nanPanelChild = get(this.GUI.handles.panels.AnalyserPanel, 'Children');\n% gather everything that doesn't belong to the Analyser panel's GUI (buttons)\nanPanelChild(~cellfun(@isempty, regexp(get(anPanelChild, 'Tag'), '^AN')) & anPanelChild ~= anAxe) = [];\n\n% if the panel has no child or only the Analyser's axe but it's hidden, then do not save anything\nif isempty(anPanelChild) || (numel(anPanelChild) == 1 && anPanelChild(1) == anAxe && strcmp(get(anAxe, 'Visible'), 'off'));\n % get the empty or hidden plot reason\n statusTextReason = get(this.GUI.handles.an.message, 'String');\n if isempty(statusTextReason); statusTextReason = 'unknown'; end;\n statusTextReason(1) = lower(statusTextReason(1));\n statusTextReason = regexprep(statusTextReason, '\\.$', '');\n % show warning\n showWarning(this, 'OCIA:ANSavePlot:NothingToSave', ...\n sprintf('Cannot save analyser plot \"%s\" to \"%s\" because there is no plot to save. Possible cause: %s.', ...\n figName, savePath, statusTextReason));\n return;\nend;\n\nif ~verLessThan('matlab', '8.4.0');\n \n % remove colorbar if a legend is present because of weird saving system\n if any(arrayfun(@(i)isa(i, 'matlab.graphics.illustration.ColorBar'), anPanelChild)) ...\n && any(arrayfun(@(i)isa(i, 'matlab.graphics.illustration.Legend'), anPanelChild));\n anPanelChild(arrayfun(@(i)isa(i, 'matlab.graphics.illustration.ColorBar'), anPanelChild)) = [];\n end;\n \n % copy objects one by one starting from the last one\n for iObj = fliplr(1 : numel(anPanelChild));\n % do not copy axes if next one is a colorbar\n if isa(anPanelChild(iObj), 'matlab.graphics.axis.Axes') && iObj > 1 ...\n && (isa(anPanelChild(iObj - 1), 'matlab.graphics.illustration.ColorBar') ...\n || isa(anPanelChild(iObj - 1), 'matlab.graphics.illustration.Legend'));\n continue;\n % copy colorbar AND its axes\n elseif isa(anPanelChild(iObj), 'matlab.graphics.illustration.ColorBar') && iObj < numel(anPanelChild) ...\n && isa(anPanelChild(iObj + 1), 'matlab.graphics.axis.Axes');\n removeCallbacks(anPanelChild(iObj));\n removeCallbacks(anPanelChild(iObj + 1));\n copyobj([anPanelChild(iObj), anPanelChild(iObj + 1)], saveFig);\n % copy legend AND its axes\n elseif isa(anPanelChild(iObj), 'matlab.graphics.illustration.Legend') && iObj < numel(anPanelChild) ...\n && isa(anPanelChild(iObj + 1), 'matlab.graphics.axis.Axes');\n removeCallbacks(anPanelChild(iObj));\n removeCallbacks(anPanelChild(iObj + 1));\n copyobj([anPanelChild(iObj), anPanelChild(iObj + 1)], saveFig);\n else\n % do not copy invisible stuff\n if strcmp(get(anPanelChild(iObj), 'Visible'), 'off'); continue; end;\n removeCallbacks(anPanelChild(iObj));\n copyobj(anPanelChild(iObj), saveFig);\n end;\n end;\nelse\n % copy objects one by one starting from the last one\n for iObj = fliplr(1 : numel(anPanelChild));\n removeCallbacks(anPanelChild(iObj));\n copyobj(anPanelChild(iObj), saveFig);\n end;\nend;\n\n% copy the colormap\nset(saveFig, 'Colormap', get(this.GUI.figH, 'Colormap'));\n\nsaveFolder = regexprep(savePath, '/[\\w\\.]+$', '');\nif exist(saveFolder, 'dir') ~= 7; mkdir(saveFolder); end;\n\n% get extension\next = regexprep(regexp(savePath, '\\.(\\w+)$', 'match'), '^\\.', '');\n% if extension is supported by the export_fig function, use that\nif ~isempty(ext) && ~strcmp(ext, 'fig') && ~isempty(regexp(ext, 'png|pdf|jpg|eps|tif|bmp', 'once'));\n if numel(varargin) > 1 && isnumeric(varargin{2});\n resolution = sprintf('-r%d', varargin{2});\n else\n \tresolution = this.an.plotSaveResolution;\n end;\n warning('off', 'MATLAB:LargeImage');\n if numel(varargin) > 2 && strcmpi(varargin{3}, 'noCrop');\n export_fig(savePath, ['-' ext], resolution, '-nocrop', saveFig);\n else\n export_fig(savePath, ['-' ext], resolution, saveFig);\n end;\n warning('on', 'MATLAB:LargeImage');\n \n% otherwise save as figure\nelse \n savePath = [regexprep(savePath, ['\\.' ext '$'], ''), '.fig'];\n set(saveFig, 'Visible', 'on');\n saveas(saveFig, savePath);\n \nend;\nclose(saveFig);\n\nshowMessage(this, sprintf('Saving analyser plot to \"%s\" done (%.3f sec).', savePath, toc(saveTic)));\n \nend\n\nfunction removeCallbacks(elem)\n if isprop(elem, 'Callback'); set(elem, 'Callback', []); end;\n if isprop(elem, 'ButtonDownFcn'); set(elem, 'ButtonDownFcn', []); end;\n childElems = get(elem, 'Children');\n for iElem = 1 : numel(childElems);\n removeCallbacks(childElems(iElem));\n end;\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "DIUpdateGUI.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/DIUpdateGUI.m", "size": 4060, "source_encoding": "utf_8", "md5": "7053fe17121fcccefd4ec7791bf84fb4", "text": "%% #DIUpdateGUI\nfunction DIUpdateGUI(this, ~, ~)\n\no('#%s() ...', mfilename, 3, this.verb);\n\ntry % capture display errors\n\n\n%% camera plot\ntry\n currFrame = peekdata(this.GUI.di.camHandle, 1);\n flushdata(this.GUI.di.camHandle);\n currFrame(:, :, 2) = currFrame(:, :, 1);\n currFrame(:, :, 3) = currFrame(:, :, 1);\n% imagesc(currFrame, 'Parent', this.GUI.handles.di.camAxe);\n cameAxeChild = get(this.GUI.handles.di.camAxe, 'Child');\n if isempty(cameAxeChild);\n cameAxeChild = imagesc(zeros(576, 720, 3), 'Parent', this.GUI.handles.di.camAxe);\n axis(this.GUI.handles.di.camAxe, 'equal');\n end;\n set(cameAxeChild, 'CData', currFrame);\ncatch\n imagesc(zeros(576, 720, 3), 'Parent', this.GUI.handles.di.camAxe);\nend;\n\n\n%% activity plot\nactiW = 180; actiH = 180;\n\nif this.GUI.di.activityRunning && ~isempty(this.GUI.di.actiMovies); \n % get the current frame\n activityFrame = this.GUI.di.actiMovies{this.GUI.di.actiMovieIndex}(:, :, :, this.GUI.di.actiMovieFrame);\n \n % update the frame\n this.GUI.di.actiMovieFrame = this.GUI.di.actiMovieFrame + 3;\n \n if this.GUI.di.actiMovieFrame > size(this.GUI.di.actiMovies{1}, 4); this.GUI.di.actiMovieFrame = 1; end;\nelse\n activityFrame = zeros(actiH, actiW, 3);\nend;\n\n\n% plot the frame\nactiAxeChild = get(this.GUI.handles.di.actiAxe, 'Child');\nif isempty(actiAxeChild);\n actiAxeChild = imagesc(activityFrame, 'Parent', this.GUI.handles.di.actiAxe);\n axis(this.GUI.handles.di.actiAxe, 'equal');\nend;\nset(actiAxeChild, 'CData', activityFrame);\n\n% calculate zoom factors\nactiWZoom = actiW / this.GUI.di.zoomLevel; actiHZoom = actiH / this.GUI.di.zoomLevel;\nactiMargX = (actiW - actiWZoom) / 2; actiMargY = (actiH - actiHZoom) / 2;\nxLims = [0, actiW - actiMargX]; yLims = [0, actiH - actiMargY];\nset(this.GUI.handles.di.actiAxe, 'XLim', xLims, 'YLim', yLims);\n\n%% reponse axe\n% create the response rate rectangle\ndelete(get(this.GUI.handles.di.respRateAxe, 'Child'));\nhold(this.GUI.handles.di.respRateAxe, 'on');\nrectangle('Parent', this.GUI.handles.di.respRateAxe, 'FaceColor', 'blue', 'EdgeColor', 'black', 'Position', [0 0 min(abs(this.di.nResps + 0.1), 10) 1]);\n% add the threshold\nplot(this.GUI.handles.di.respRateAxe, ones(2, 1) * this.di.respRateThresh, [0 1], 'Color', 'red', 'LineWidth', 8);\nhold(this.GUI.handles.di.respRateAxe, 'off');\nset(this.GUI.handles.di.respRateAxe, 'XLim', [0, 10], 'YLim', [0 1], 'XTick', [], 'YTick', []);\n\n% apply the decay\nthis.di.nResps = min(max((this.di.nResps - this.di.nRespsDecay) * 0.99, 0), 10 + 0.5);\n\n%% time axe\n% create the time rectangle\nif this.di.waitingForResp;\n \n delete(get(this.GUI.handles.di.respTimeAxe, 'Child'));\n hold(this.GUI.handles.di.respTimeAxe, 'on');\n remTime = min(max(this.di.waitingTime - (nowUNIX - this.di.waitingStartTime), 0) + 0.001, this.di.waitingTime);\n rectangle('Parent', this.GUI.handles.di.respTimeAxe, 'FaceColor', 'green', 'EdgeColor', 'black', 'Position', [0 0 remTime 1]);\n hold(this.GUI.handles.di.respTimeAxe, 'off');\n set(this.GUI.handles.di.respTimeAxe, 'XLim', [0, this.di.waitingTime], 'YLim', [0 1], 'XTick', [], 'YTick', []);\n\n set(this.GUI.handles.di.panels.time, 'Title', sprintf('Response time - %.1f sec', remTime / 1000));\n\nend;\n\n\n% check if a response was given\nif this.di.waitingForResp && this.di.nResps > this.di.respRateThresh;\n this.di.resp = true;\n this.di.waitingForResp = false;\n stimNum = this.di.stimMatrix(this.di.iTrial, this.di.iStimMat);\n isTarget = stimNum == this.di.targetStim;\n showMessage(this, sprintf('RESPONSE !! Trial %d: stimulus %d, target: %d, correct: %d...', this.di.iTrial, stimNum, isTarget, isTarget), 'yellow');\nend;\n\nif this.di.lockMouse;\n r = java.awt.Robot();\n lockCoords = this.GUI.pos(1:2) + this.GUI.pos(3:4) - [2 2];\n r.mouseMove(lockCoords(1), lockCoords(2)); \nend;\n\n\ncatch err;\n errStack = getStackText(err);\n showWarning(this, 'OCIA:DIUpdateGUI', sprintf('Problem in the discriminator GUI update function: \"%s\".', err.message));\n o(errStack, 0, 0);\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "DWFilterTable.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/DWFilterTable.m", "size": 9418, "source_encoding": "utf_8", "md5": "0487d32d14dbf96aa9d050a83844249d", "text": "function [filtTable, filtTableIndexes] = DWFilterTable(this, filtText, tableToUse, tIDs)\n% DWFilterTable - Filter the DataWatcher table and return the rows (and row indexes)\n%\n% [filtTable, filtTableIndexes] = DWFilterTable(this, filtText)\n% [filtTable, filtTableIndexes] = DWFilterTable(this, filtText, tableToUse)\n%\n% Filters the rows of the 'tableToUse' (or the DataWatcher's table if none provided) based on the column names \n% using the filternig string 'filtText'. The filtering string can be anything like: 'rowType = notebook' or \n% 'rowType ~= imgData' for regexp match or 'spot != spot01' for *not* matching or\n% 'spot = spot01 AND day = 2014_02_08' or 'rowType = imgData OR animal = mouse1', etc.\n% Sub-column names are also possible like 'data.rawImg.loadStatus = full' to get all the rows where the\n% data is fully loaded.\n\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n \n % if no table was provided, use the default table which is the DataWatcher's table\n if ~exist('tableToUse', 'var') || isempty(tableToUse);\n tableToUse = this.dw.table;\n end;\n % if no table IDs were provided, use the DataWatcher table's IDs\n if ~exist('tIDs', 'var') || isempty(tIDs);\n tIDs = this.dw.tableIDs;\n end;\n\n % separate the filter into parts at the join operators\n [filtParts, ~, ~, ~, ops] = regexp(filtText, '\\s(OR|AND)\\s', 'split');\n \n % holder for the filtered table indexes\n filtTableIndexes = [];\n \n % go through each filter pair\n for iPart = 1 : numel(filtParts);\n \n % match the filter string for: colName (column name), eq (equality), val (value)\n hit = regexp(filtParts{iPart}, '^(?[\\w\\.\\*]+)\\s+(?[!~]{0,2}\\=)\\s+(?.+)$', 'names');\n \n % cannot match the pair, skip it with warning\n if isempty(hit);\n showWarning(this, 'OCIA:DW:DWFilterTable:BadRegexp', ...\n sprintf('Cannot processed regular expression part: %s. Skipping it.', filtParts{iPart}));\n continue;\n end;\n \n % get the equality function\n switch hit.eq;\n % basic string comparison\n case '='; eqfun = @strcmp;\n % basic string comparison with negation\n case '!='; eqfun = @(varargin)~strcmp(varargin{:});\n % regular expression comparison\n case '~='; eqfun = @(varargin)~isempty(regexp(varargin{1}, varargin{2}, 'once'));\n % regular expression comparison with negation\n case '!~='; eqfun = @(varargin)isempty(regexp(varargin{1}, varargin{2}, 'once'));\n % unknown comparison sign\n otherwise\n showWarning(this, 'OCIA:DW:DWFilterTable:UnkownVar', ...\n sprintf('Unknown comparison sign requested for filtering: %s', hit.eq));\n continue;\n end;\n \n % extract the value and the filtering column's name\n val = hit.val;\n colName = hit.colName;\n \n % if the column name does not contain a sub-column\n if isempty(regexp(colName, '^[\\w\\*]+\\.[\\w\\*]+', 'once'));\n \n % if the requested filtering column is not part of the table's column list and is not the rowID\n if ~ismember(colName, tIDs) && ~strcmp(colName, 'rowID');\n % show a warning and skip\n showWarning(this, 'OCIA:DW:DWFilterTable:UnkownColName', ...\n sprintf('Unknown column name requested for filtering: %s', colName));\n continue;\n end;\n\n % special case for the row IDs\n if strcmp(colName, 'rowID');\n values = DWGetRowID(this, 1 : size(tableToUse, 1), tableToUse, tIDs); \n \n % otherwise get all the values from the table's column\n else\n values = get(this, 'all', colName, tableToUse, tIDs); \n end;\n \n % make sure values are cell\n if ~iscell(values); values = { values }; end;\n \n % make sure no cell is empty\n values(cellfun(@isempty, values)) = { '' };\n \n % if the variable name has a sub-variable name (like \"data.rawImg\"), extract the values differently\n else\n values = getSubColumnValues(this, tIDs, tableToUse, colName);\n end;\n \n % check if all values are strings and abort with a warning if it is not the case\n isAllCell = all(cellfun(@ischar, values)); \n if ~isAllCell; \n showWarning(this, 'OCIA:DW:DWFilterTable:NotCharCellFilter', 'Requested filtering on a non-string column. Aborting.');\n return;\n end;\n \n % remove the delete tag\n values = regexprep(values, ['^' this.GUI.dw.deleteTag], '');\n \n % get the rows where the requested values match (or not) the table's values\n tempTableIndexes = find(cellfun(@(valueTable) eqfun(valueTable, val), values));\n \n % if this is the first filter pair, use if as starting filtered table\n if iPart == 1;\n filtTableIndexes = tempTableIndexes;\n \n % if the previous filter was an 'AND' operator, only get the overlapping indexes\n elseif strcmp(ops{iPart - 1}, ' AND ');\n % only get the overlap of them\n filtTableIndexes(~ismember(filtTableIndexes, tempTableIndexes), :) = []; %#ok\n \n % if the previous filter was an 'OR' operator, get the unique concatenated indexes\n elseif strcmp(ops{iPart - 1}, ' OR ');\n % get the unique concatenated table\n filtTableIndexes = unique(vertcat(filtTableIndexes, tempTableIndexes), 'rows');\n end;\n \n end; % end of filter pairs looping\n \n % create the filtered table using the filtered indexes\n filtTable = tableToUse(filtTableIndexes, :); \n\nend\n\n% extract the values of a non-character column\nfunction newValues = getSubColumnValues(this, tIDs, tableToUse, colName)\n\n% get the column name \"parts\"\ncolNameParts = regexp(colName, '\\.', 'split');\n\n% get the values for the column name\nvalues = get(this, 'all', colNameParts{1}, tableToUse, tIDs);\n% make sure values are cell\nif ~iscell(values); values = { values }; end;\n% make sure no empty cells exist by filling them with empty structures\nvalues(cellfun(@isempty, values)) = { struct() };\n% create a new values cell-array which will have the extract sub-column values\nnewValues = cell(numel(values), 1);\n\n% go through each row of the table and asses whether the sub-column matches\nfor iRow = 1 : numel(values);\n \n % get a row validity tag\n isRowValid = true;\n % get the remaining column parts\n localColumnParts = colNameParts(2 : end);\n % get the current structure\n currentValue = values{iRow};\n \n % recursively get the right field from the current structure\n while ~isempty(localColumnParts); \n \n % if the current value is still a structure and it has the right sub-field\n if isstruct(currentValue) && isfield(currentValue, localColumnParts{1});\n % get the \"next\" sub-structure and move forward in the list of the column parts\n currentValue = currentValue.(localColumnParts{1});\n localColumnParts(1) = [];\n \n % if the current value is still a structure with at least one field and a numbered field was required\n elseif isstruct(currentValue) && numel(fieldnames(currentValue)) ...\n && ~isempty(regexp(localColumnParts{1}, '^\\s*\\d+\\s*$', 'once'));\n fNames = fieldnames(currentValue); % get the field names\n iField = str2double(localColumnParts{1}); % get the sub-field number\n % if the required number is not a number or exceeds the limit, abort\n if isnan(iField) || iField < 1 || iField > numel(fNames); \n % mark this row as non-valid and abort\n isRowValid = false;\n break; \n end;\n % otherwise get the \"next\" sub-structure by getting the right sub-field using the number given as input and\n % move forward in the list of the column parts\n currentValue = currentValue.(fNames{iField});\n localColumnParts(1) = [];\n \n % if the current value is still a structure with at least one field and any field was required\n elseif isstruct(currentValue) && numel(fieldnames(currentValue)) && strcmp(localColumnParts{1}, '*');\n % get the \"next\" sub-structure and move forward in the list of the column parts \n fNames = fieldnames(currentValue); % get the field names \n currentValue = currentValue.(fNames{1});\n localColumnParts(1) = [];\n \n % if the current value is still a structure but it does *not* have the right sub-field, abort\n elseif isstruct(currentValue);\n % mark this row as non-valid and abort\n isRowValid = false;\n break; \n end;\n end;\n \n % if the current row is already flagged as non-valid, do not continue\n if ~isRowValid;\n % fill the row with an empty string\n newValues{iRow} = '';\n continue;\n end;\n \n % store the extracted value\n newValues{iRow} = currentValue;\n \nend;\n\nend"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIACreateParamPanelControls.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/OCIACreateParamPanelControls.m", "size": 26865, "source_encoding": "utf_8", "md5": "96f2eed824df54d1d3e64fbb0b6a310d", "text": "\nfunction OCIACreateParamPanelControls(this, modeID, varargin)\n% OCIACreateParamPanelControls - Creates a parameter pannel menu\n%\n% OCIACreateParamPanelControls(this, modeID, optionalHandleOfNavButtons)\n%\n% Creates a parameter panel menu from a parameter panel configuration (\"this.GUI.(modeID).paramPanConfig\") and a\n% data structure (\"this.(modeID).(categ).(id)\"). If \"optionalHandleOfNavButtons\" exists and is a handle to the\n% parameter panel navigation buttons, the panel is not re-created but just updated to display the right page\n% (\"this.GUI.(modeID).paramPage\").\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\n% abort if no configuration provided\nif isempty(this.GUI.(modeID).paramPanConfig); return; end;\n\n%% init\nfontSizeAdjust = 1;\nlabelFontSizeAdjust = 1;\nswitch modeID;\n \n % Analyser mode\n case 'an';\n \n % define the updating function\n updateFunction = @ANUpdatePlot;\n % define the max number of rows and the number of items to place\n nMaxRows = 5; nMinRows = 5; nMaxCols = 2; nMinCols = 2; pad = 0.02; inPad = 0.01;\n% nMaxRows = 4; nMinRows = 4; nMaxCols = 4; nMinCols = 3; pad = 0.02; inPad = 0.01;\n% fontSizeAdjust = 3.0;\n \n % Intrinsic mode\n case 'in';\n \n % define the updating function\n updateFunction = @INUpdateParams;\n % define the max number of rows and the number of items to place\n nMaxRows = 10; nMinRows = 8; nMaxCols = 4; nMinCols = 3; pad = 0.025; inPad = 0.02;\n \n % Behavior mode\n case 'be';\n \n % define the updating function\n updateFunction = @BEUpdateParams;\n % define the max number of rows and the number of items to place\n nMaxRows = 15; nMinRows = 15; nMaxCols = 2; nMinCols = 2; pad = 0.02; inPad = 0.015;\n \n fontSizeAdjust = 0.5;\n \n % TrialView mode\n case 'tv';\n \n % define the updating function\n updateFunction = @TVUpdateParams;\n % define the max number of rows and the number of items to place\n nMaxRows = 10; nMinRows = 10; nMaxCols = 2; nMinCols = 2; pad = 0.02; inPad = 0.015;\n \n labelFontSizeAdjust = 1.1;\n fontSizeAdjust = 0.7;\n \n otherwise\n return;\nend;\n\n%% init the parameter pannel dimensions\n% common inputs\ncommons = { 'Parent', this.GUI.handles.(modeID).paramPan, 'Units', 'normalized', 'Enable', 'off' };\nUICommons = struct();\ncallBackFcn = { 'Callback', @(h, e) updateFunction(this, h, e) };\nUICommons.text = [ commons, { 'Background', 'white', 'Style', 'edit' }, callBackFcn ];\nUICommons.dropdown = [ commons, { 'Background', 'white', 'Style', 'popupmenu' }, callBackFcn ];\nUICommons.list = [ commons, { 'Background', 'white', 'Style', 'list', 'Min', 0, 'Max', 2 }, callBackFcn ];\nUICommons.button = [ commons, { 'Style', 'pushbutton' } ];\nUICommons.slider = [ commons, { 'Style', 'slider' } ];\nUICommons.lab = [ commons, { 'Background', 'white', 'Style', 'text' } ];\nUICommons.paramNav = [ commons, { 'Style', 'pushbutton', 'Enable', 'off', 'FontSize', ...\n round(this.GUI.pos(4) / 55 * fontSizeAdjust), 'Callback', @(h, e)OCIACreateParamPanelControls(this, modeID, h) } ];\n\n% define the max number of rows and the number of items to place\nnUICtrl = size(this.GUI.(modeID).paramPanConfig, 1);\nUISizes = this.GUI.(modeID).paramPanConfig{:, 5};\nnUICtrlRows = sum(UISizes(:, 1));\n\n% calculate the number of acutal columns and rows to use\nnRows = min(max(ceil(nUICtrlRows / nMaxCols), nMinRows), nMaxRows);\nnCols = min(max(ceil((nUICtrlRows / nRows)), nMinCols), nMaxCols) + 0.15;\nelemW = (1 - (nCols + 1) * pad) / nCols; % width depends on the number of columns\nelemH = (1 - (nRows + 1) * pad) / nRows; % height depends on the number of rows\niRow = 0; iCol = 0; %#ok, init the row and column indexes\n\n% part of the width that is allocated for the label if it is on the side\nlabelWidthRatio = 0.5;\n% height that is allocated for the label if it is on the top\nlabelHeight = 0.5;\n\n% if call was made by one of the navigate buttons\nif ~isempty(varargin) && (varargin{1} == this.GUI.handles.(modeID).nextParams...\n || varargin{1} == this.GUI.handles.(modeID).prevParams);\n % get all UI elements except the arrows\n UIElems = this.GUI.handles.(modeID).paramPanElems;\n % compute the minimum and maximum positions of the UIControls to desactivate the next/prev buttons\n minPos = Inf; maxPos = -Inf;\n % get the move direction\n direction = iff(varargin{1} == this.GUI.handles.(modeID).prevParams, 1, -1);\n % get the IDs and go through each elements\n UIIDs = fieldnames(UIElems);\n for iElem = 1 : numel(UIIDs);\n % get the position of this element \n pos = get(this.GUI.handles.(modeID).paramPanElems.(UIIDs{iElem}), 'Position');\n % update the position\n pos = pos + [nMaxCols * (elemW + pad) 0 0 0] .* direction;\n % move the element\n set(this.GUI.handles.(modeID).paramPanElems.(UIIDs{iElem}), 'Position', pos);\n % if the control is outside the visible area, hide them\n isOut = pos(1) > 0 && (pos(1) + pos(3)) < 1;\n set(this.GUI.handles.(modeID).paramPanElems.(UIIDs{iElem}), 'Visible', iff(isOut, 'on', 'off'));\n minPos = min(minPos, pos(1));\n maxPos = max(maxPos, pos(1) + pos(3));\n end;\n % enable/disable the navigating buttons\n set(this.GUI.handles.(modeID).prevParams, 'Enable', iff(minPos > 0, 'off', 'on'));\n set(this.GUI.handles.(modeID).nextParams, 'Enable', iff(maxPos < 1, 'off', 'on'));\n\n % update the page number\n this.GUI.(modeID).paramPage = this.GUI.(modeID).paramPage + direction;\n return;\nend;\n\n%% clear the parameters area\nparamPanChildren = get(this.GUI.handles.(modeID).paramPan, 'Children');\n% do not remove the navigating buttons\nif isfield(this.GUI.handles.(modeID), 'nextParams');\n paramPanChildren(paramPanChildren == this.GUI.handles.(modeID).nextParams) = [];\n paramPanChildren(paramPanChildren == this.GUI.handles.(modeID).prevParams) = [];\nend;\ndelete(paramPanChildren);\nthis.GUI.handles.(modeID).paramPanElems = struct();\n\n%% create the next previous settings buttons\n% calculate X and Y base positions\nprevButPosX = 0.25 * pad;\nprevButPosY = pad;\nthis.GUI.handles.(modeID).prevParams = uicontrol(UICommons.paramNav{:}, 'String', '<', ...\n 'Tag', sprintf('%sParamPrevParams', upper(modeID)), ...\n 'Position', [prevButPosX prevButPosY elemW * 0.1 (elemH + pad) * nRows - pad], ...\n 'ToolTipString', 'Previous parameter controls');\niRow = iRow + nRows;\niCol = 0.05 + pad;\nnextButPosX = (nCols - 0.1) * (pad + elemW) + 0.75 * pad;\nthis.GUI.handles.(modeID).nextParams = uicontrol(UICommons.paramNav{:}, 'String', '>', ...\n 'Tag', sprintf('%sParamNextParams', upper(modeID)), ...\n 'Position', [nextButPosX prevButPosY elemW * 0.1 (elemH + pad) * nRows], ...\n 'ToolTipString', 'Next parameter controls');\n \n%% create the UI elements with their labels\n% go through all elements, create them and place them\nfor iUICtrl = 1 : nUICtrl;\n \n % get the variables of the current control element\n rowParams = table2cell(this.GUI.(modeID).paramPanConfig(iUICtrl, :));\n [categ, id, UIType, valueType, UISize, isLabelAbove, label, tooltip] = rowParams{:};\n \n % adjust element height for multiple rows\n elemHLocal = (1 - (nRows - UISize(1) + 2) * pad) / nRows; % height depends on the number of rows\n \n % adjacent buttons\n if strcmp(UIType, 'button') && UISize(2) > 0 && iUICtrl > 1;\n rowParamsBef = table2cell(this.GUI.(modeID).paramPanConfig(iUICtrl - 1, :));\n [~, ~, UITypeBef, ~, UISizeBef] = rowParamsBef{:};\n % if this is the second button element that is not full width and total width is not exceeding 1\n if strcmp(UITypeBef, 'button') && UISizeBef(2) > 0 && UISize(2) + UISizeBef(2) <= 1;\n % put this button at the same row\n iRow = iRow - 1;\n end;\n end;\n \n % update row/column index\n iRow = iRow + UISize(1);\n % if max number of rows is reached, go to the next column update rows/columns\n if iRow > nRows;\n iRow = UISize(1);\n iCol = iCol + 1;\n end;\n\n % calculate X and Y base positions\n elemPosX = (iCol - 1) * (pad + elemW) + pad;\n if UISize(1) == nRows;\n elemPosY = 1 - iRow * elemHLocal - pad;\n elseif UISize(1) > 1;\n elemPosY = 1 - iRow * (elemHLocal + pad * (UISize(1) / nRows)) - pad;\n else\n elemPosY = 1 - iRow * (elemHLocal + pad) + pad;\n end;\n \n % font sizes\n ctrlElemFontSize = round(this.GUI.pos(4) / (105 - 3 * nRows)) * fontSizeAdjust;\n labFontSize = round(this.GUI.pos(4) / (115 - 3 * nRows + 0.1 * numel(label))) * fontSizeAdjust * labelFontSizeAdjust;\n \n % calculate positions, depending on whether the label is above or not:\n % if label is above\n if isLabelAbove;\n % position and size for label\n labElemX = elemPosX;\n% labElemY = elemPosY + (UISize(1)) * elemHLocal + (UISize(1) - 1) * pad;\n labElemY = elemPosY + (UISize(1) - labelHeight) * elemHLocal + 0.5 * pad;\n labElemW = elemW;\n labelemHLocal = labelHeight * elemHLocal;\n % position and size for GUI element\n ctrlElemX = elemPosX;\n ctrlElemW = elemW;\n ctrlElemY = elemPosY;\n ctrlelemHLocal = (UISize(1) - labelHeight) * elemHLocal + pad;\n labFontSize = round(this.GUI.pos(4) / (125 - 3 * nRows + 0.1 * numel(label))) * fontSizeAdjust * labelFontSizeAdjust;\n \n % if label is not above\n else\n % position and size for label\n labElemX = elemPosX;\n labElemY = elemPosY + (UISize(1) * 0.5 - 0.25) * elemHLocal;\n labElemW = elemW * (labelWidthRatio - inPad);\n labelemHLocal = elemHLocal * 0.5;\n % position and size for GUI element\n ctrlElemX = elemPosX + elemW * (labelWidthRatio + inPad);\n ctrlElemW = elemW * (1 - labelWidthRatio - inPad);\n ctrlElemY = elemPosY;\n ctrlelemHLocal = UISize(1) * elemHLocal + (UISize(1) - 1) * pad;\n \n end;\n \n % reduce a bit the size of the dropdown menus\n if strcmp(UIType, 'dropdown');\n labFontSize = round(labFontSize * 0.8);\n ctrlElemFontSize = round(ctrlElemFontSize * 0.8);\n labElemY = elemPosY + (UISize(1) * 0.5 - 0.1) * elemHLocal;\n \n % no label for buttons\n elseif strcmp(UIType, 'button');\n ctrlElemX = ctrlElemX - labElemW;\n ctrlElemW = ctrlElemW + labElemW;\n labElemW = 0;\n \n % special case of two buttons next to each other\n if UISize(2) > 0;\n ctrlElemW = ctrlElemW * UISize(2);\n \n % adjacent buttons\n if iUICtrl > 1;\n rowParamsBef = table2cell(this.GUI.(modeID).paramPanConfig(iUICtrl - 1, :));\n [~, ~, UITypeBef, ~, UISizeBef] = rowParamsBef{:};\n % if this is the second button element that is not full width and total width is not exceeding 1\n if strcmp(UITypeBef, 'button') && UISizeBef(2) > 0 && UISize(2) + UISizeBef(2) <= 1;\n % put this button to the right\n ctrlElemX = ctrlElemX + ctrlElemW;\n end;\n end;\n end;\n \n % process differently big lists\n elseif strcmp(UIType, 'list') && UISize(1) == nRows && isLabelAbove;\n labelHeightLocal = 0.8;\n % position and size for label\n labElemY = elemPosY + (UISize(1) - labelHeightLocal * 0.9) * elemHLocal + 0.5 * pad;\n labelemHLocal = labelHeightLocal * elemHLocal;\n % position and size for GUI element\n ctrlelemHLocal = (UISize(1) - labelHeightLocal) * elemHLocal + pad;\n labFontSize = round(this.GUI.pos(4) / (125 - 3 * nRows + 0.1 * numel(label))) * 1.5;\n \n \n % process differently big lists\n elseif strcmp(UIType, 'list') && UISize(1) > 1 && isLabelAbove;\n labelHeightLocal = 0.8;\n labElemY = elemPosY + (UISize(1) - labelHeightLocal * 0.5) * elemHLocal + 0.5 * pad;\n labFontSize = round(this.GUI.pos(4) / (125 - 3 * nRows + 0.1 * numel(label))) * 1.5;\n \n end;\n \n % create the label\n this.GUI.handles.(modeID).paramPanElems.([id '_label']) = uicontrol(UICommons.lab{:}, 'String', label, ...\n 'Position', [labElemX labElemY labElemW labelemHLocal], 'ToolTipString', tooltip, ... 'BackgroundColor', 'red', ...\n 'Tag', sprintf('%sParam%s', upper(modeID), id), 'FontSize', labFontSize);\n \n \n % get category parts\n categParts = regexp(categ, '\\.', 'split');\n if numel(categParts) > 1;\n categ = categParts{1};\n subCateg = categParts{2};\n else\n subCateg = [];\n end;\n % if the field does not exist, create it\n if (~isempty(subCateg) && ~isfield(this.(modeID).(categ).(subCateg), id)) ...\n || (isempty(subCateg) && ~isfield(this.(modeID).(categ), id));\n this.(modeID).(categ).(id) = '';\n end;\n \n callbackFcn = [];\n \n % process the different UI types\n switch UIType;\n \n % text controls\n case 'text'; \n % get the value from the storage variable\n if isempty(subCateg);\n storedValue = this.(modeID).(categ).(id);\n else\n storedValue = this.(modeID).(categ).(subCateg).(id);\n end;\n % if the value is not text and its an array, display as an array between brackets\n if numel(storedValue) > 1 && ~strcmp(valueType, 'text') && ~strcmp(valueType, 'cellArray'); \n % add semi colon at each line end\n stringValue = [ num2str(storedValue), repmat(';', size(storedValue, 1), 1)];\n % reshape as a single line\n stringValue = reshape(stringValue', 1, numel(stringValue));\n % replace all spaces by single space\n stringValue = regexprep(stringValue, '\\s+', ' ');\n % remove all starting spaces\n stringValue = regexprep(stringValue, '^\\s', '');\n stringValue = regexprep(stringValue, '; ', ';');\n % remove all empty spaces and replace them by commas\n stringValue = ['[', regexprep(stringValue, '\\s+', ','), ']'];\n % clean up: remove last semi colon\n stringValue = regexprep(stringValue, ';\\]$', ']');\n % clean up: remove starting comas\n stringValue = regexprep(stringValue, '[\\[;]$', ']');\n % clean up: add space after each colon or semi colon\n stringValue = regexprep(stringValue, '([,;])', '$1 ');\n \n % if the value is a text, keep it as a string so do nothing\n elseif numel(storedValue) > 1 && strcmp(valueType, 'text'); \n \n stringValue = storedValue;\n \n % if the value is a text, keep it as a cell array string so do nothing\n elseif iscell(storedValue) && strcmp(valueType, 'cellArray');\n \n % process each cell and transform it into a string\n for iCell = 1 : numel(storedValue);\n \n % if cell is already a string, skip\n if ischar(storedValue{iCell});\n continue;\n \n % if cell is an array, transform it into a string\n elseif isnumeric(storedValue{iCell});\n % add semi colon at each line end\n stringValue = [ num2str(storedValue{iCell}), repmat(';', size(storedValue{iCell}, 1), 1)];\n % reshape as a single line\n stringValue = reshape(stringValue', 1, numel(stringValue));\n % replace all spaces by single space\n stringValue = regexprep(stringValue, '\\s+', ' ');\n % remove all starting spaces\n stringValue = regexprep(stringValue, '^\\s', '');\n stringValue = regexprep(stringValue, '; ', ';');\n % remove all empty spaces and replace them by commas\n stringValue = ['[', regexprep(stringValue, '\\s+', ','), ']'];\n % clean up: remove last semi colon\n stringValue = regexprep(stringValue, ';\\]$', ']');\n % clean up: remove starting comas\n stringValue = regexprep(stringValue, '[\\[;]$', ']');\n % clean up: add space after each colon or semi colon\n storedValue{iCell} = regexprep(stringValue, '([,;])', '$1 ');\n \n % if just an empty cell\n elseif ~isempty(storedValue{iCell});\n storedValue{iCell} = '';\n \n % otherwise if not just and empty, abort conversion\n else\n storedValue{iCell} = 'unknownDataType';\n showWarning(this, 'OCIA:OCIACreateParamPanelControls:UnkownDataTypeInCellArray', sprintf( ...\n ['An unknown data type has been found in the cell array of the parameter control ', ...\n '\"%s\" of the mode \"%s\", class: %s! Skipping.'], id, modeID, class(storedValue)));\n \n end;\n end;\n \n % non-empty cell array\n if ~isempty(storedValue) && numel(storedValue) >= 1 && ~isempty(storedValue{1});\n % add a semi colon after each last cell\n storedValue(:, end) = arrayfun(@(iCell) [storedValue{iCell, end}, ';'], 1 : size(storedValue, 1), ...\n 'UniformOutput', false);\n % rearrange cell-array\n storedValue = storedValue';\n % add a coma after each cell\n storedValue = arrayfun(@(iCell) [storedValue{iCell}, ','], 1 : numel(storedValue), ...\n 'UniformOutput', false);\n % remove the useless commas\n storedValue = regexprep(storedValue, ';,$', ';');\n % create the string\n stringValue = ['{ ', regexprep(sprintf('%s ', storedValue{:}), ' $', '') ' }'];\n \n % cell-array is empty\n else\n stringValue = '';\n end;\n % otherwise the value is just a number\n else\n stringValue = num2str(storedValue);\n end;\n % leave value empty\n value = [];\n \n % substitue pi\n stringValue = regexprep(stringValue, '3\\.14', 'pi');\n stringValue = regexprep(stringValue, '6\\.28', '2pi');\n \n % drop down menu elements \n case 'dropdown';\n % if the value from the storage variable is empty\n if (isempty(subCateg) && isempty(this.(modeID).(categ).(id))) ...\n || (~isempty(subCateg) && isempty(this.(modeID).(categ).(subCateg).(id)));\n value = 1; % select the first item \n \n % otherwise if it is a boolean drop-down and there is a value in the storage variable\n elseif numel(valueType) == 2 && all(ismember(valueType, { 'true', 'false' }));\n % get the values to select\n if isempty(subCateg);\n valueString = iff(this.(modeID).(categ).(id), 'true', 'false');\n else\n valueString = iff(this.(modeID).(categ).(subCateg).(id), 'true', 'false');\n end;\n value = find(strcmp(valueType, valueString));\n \n % otherwise if there is a value in the storage variable\n else\n % get the values to select\n if isempty(subCateg);\n value = find(strcmp(valueType, this.(modeID).(categ).(id)));\n else\n value = find(strcmp(valueType, this.(modeID).(categ).(subCateg).(id)));\n end;\n end;\n % use a string the cell-array from the configuration\n stringValue = valueType;\n \n % list elements \n case 'list';\n % get the stored variable\n if isempty(subCateg);\n storedVariable = this.(modeID).(categ).(id);\n else\n storedVariable = this.(modeID).(categ).(subCateg).(id);\n end;\n % if the value from the storage variable is empty\n if isempty(storedVariable);\n value = []; % select nothing \n % otherwise if there is a value in the storage variable\n else\n % make sure the stored variable is a cell\n if ~iscell(storedVariable); storedVariable = { storedVariable }; end;\n % make sure the valueType is a cell\n if ~iscell(valueType); valueType = { valueType }; end;\n % make sure the valueType is a cell\n if ~isempty(valueType) && numel(valueType) == 1 && iscell(valueType{1});\n valueType = valueType{1};\n end;\n % get the values to select\n value = find(arrayfun(@(i)ismember(valueType{i}, storedVariable), 1 : numel(valueType)));\n end;\n % use a string the cell-array from the configuration\n stringValue = valueType;\n \n % buttons\n case 'button';\n stringValue = label;\n if iscell(valueType) && ~isempty(valueType) && isa(valueType{1}, 'function_handle');\n callbackFcn = valueType{1};\n elseif ~isempty(valueType) && isa(valueType, 'function_handle');\n callbackFcn = valueType;\n end;\n \n % sliders\n case 'slider';\n stringValue = label;\n if isempty(subCateg);\n value = this.(modeID).(categ).(id);\n else\n value = this.(modeID).(categ).(subCateg).(id);\n end;\n if iscell(valueType) && ~isempty(valueType) && isa(valueType{1}, 'function_handle');\n callbackFcn = valueType{1};\n\n elseif ~isempty(valueType) && isa(valueType(1), 'function_handle');\n callbackFcn = valueType;\n end;\n \n end; % end of GUI type switch\n \n \n % reduce a bit the size of the lists if there are a lot elements inside\n if strcmp(UIType, 'list') && ~strcmp(id, 'fileList');\n nElems = numel(stringValue);\n ctrlElemFontSize = min(max(round(ctrlElemFontSize * 1.2 - 0.07 * nElems), 6), 25);\n end;\n \n% % extract cell in cell\n% if iscell(stringValue) && ~isempty(stringValue) && numel(stringValue) == 1 && iscell(stringValue{1});\n% stringValue = stringValue{1};\n% end;\n \n % create the GUI element\n this.GUI.handles.(modeID).paramPanElems.(id) = uicontrol(UICommons.(UIType){:}, ...\n 'String', stringValue, 'Value', value, 'Tag', sprintf('%sParam%s', upper(modeID), id), ...\n 'Position', [ctrlElemX ctrlElemY ctrlElemW ctrlelemHLocal], 'ToolTipString', tooltip, ...\n 'FontSize', ctrlElemFontSize);\n\n % set a minimum and a maximum\n if strcmp(UIType, 'slider');\n set(this.GUI.handles.(modeID).paramPanElems.(id), 'Min', valueType{2}, 'Max', valueType{3}, 'SliderStep', ...\n [valueType{4}, valueType{5}]);\n end;\n \n % pushbuttons should not be presset\n if strcmp(UIType, 'button');\n set(this.GUI.handles.(modeID).paramPanElems.(id), 'Value', 0);\n end;\n \n if ~isempty(callbackFcn);\n % pass input arguments\n if strcmp(UIType, 'button') && numel(valueType) > 1;\n set(this.GUI.handles.(modeID).paramPanElems.(id), 'Callback', @(h, e) callbackFcn(this, valueType{2 : end}));\n else\n set(this.GUI.handles.(modeID).paramPanElems.(id), 'Callback', @(h, e) callbackFcn(this));\n end;\n % add a callback for the frame setter\n if strcmp(UIType, 'slider');\n jObj = findjobj(this.GUI.handles.(modeID).paramPanElems.(id));\n set(jObj, 'AdjustmentValueChangedCallback', @(h, e) callbackFcn(this));\n end;\n end;\n\n % if the controls are outside the visible area, hide them\n if iCol > nCols;\n set(this.GUI.handles.(modeID).paramPanElems.(id), 'Visible', 'off');\n set(this.GUI.handles.(modeID).paramPanElems.([id '_label']), 'Visible', 'off');\n % enable the navigating buttons\n set(this.GUI.handles.(modeID).nextParams, 'Enable', 'on');\n end;\n \nend;\n\n% refresh the GUI\ndrawnow();\n \n% go through all elements, to update those that need a Java-based update\nfor iUICtrl = 1 : nUICtrl; \n % get the variables of the current control element\n rowParams = table2cell(this.GUI.(modeID).paramPanConfig(iUICtrl, :));\n [~, id, UIType, valueType, UISize] = rowParams{:};\n % if the element is a list and the UISize setting requires some Java-based updating of the uicontrol\n if strcmp(UIType, 'list') && UISize(2) > 0;\n % launch a timer to update the control\n start(timer('StartDelay', 0.15, 'TimerFcn', @(~, ~) javaUpdateUIControl( ...\n this.GUI.handles.(modeID).paramPanElems.(id), round(numel(valueType) / UISize(2)))));\n end;\nend;\n\n% only show the parameter panel if there are some controls to display\nset(this.GUI.handles.(modeID).paramPan, 'Visible', iff(nUICtrl > 0, 'on', 'off'));\n\n% change the parameter page\nif this.GUI.(modeID).paramPage ~= 1;\n % reset to page 1\n this.GUI.(modeID).paramPage = 1;\n % update the pages\n for iPage = 1 : this.GUI.(modeID).paramPage;\n OCIACreateParamPanelControls(this, modeID, this.GUI.handles.(modeID).nextParams);\n end;\nend;\n\nend\n\n% little function to update an uicontrol\nfunction javaUpdateUIControl(handle, nRows)\n try \n visState = get(handle, 'Visible'); % get visibility state\n pos = get(handle, 'Position'); % get position\n % make visible\n set(handle, 'Position', pos + iff(strcmp(visState, 'off'), [10E5 10E5 0 0], [0 0 0 0]), 'Visible', 'on');\n jObj = findjobj(handle);\n jListbox = jObj.getViewport().getView();\n jListbox.setLayoutOrientation(jListbox.HORIZONTAL_WRAP);\n jListbox.setVisibleRowCount(nRows);\n set(handle, 'Visible', visState, 'Position', pos);\n catch err; %#ok \n % Nobody cares if this fails. At least not me >.<\n end;\nend"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "DIStartStopCamera.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/DIStartStopCamera.m", "size": 1247, "source_encoding": "utf_8", "md5": "72f49cb06536a9aff1927ea2ee8e228b", "text": "%% #DIStartStopCamera\nfunction DIStartStopCamera(this, commandString)\n\no('#%s() ...', mfilename, 3, this.verb);\n\ntry % capture display errors\n\nif strcmp(commandString, 'toggle') && strcmp(get(this.GUI.di.camHandle, 'Running'), 'on');\n commandString = 'stop';\nelseif strcmp(commandString, 'toggle') && strcmp(get(this.GUI.di.camHandle, 'Running'), 'off');\n commandString = 'start'; \nend;\n\nif strcmp(commandString, 'start');\n \n % make sure camera is stopped\n stop(this.GUI.di.camHandle);\n \n % add disk and memory logging options\n set(this.GUI.di.camHandle, 'LoggingMode', 'disk&memory');\n if exist(this.path.discrDataSave, 'dir') ~= 7; mkdir(this.path.discrDataSave); end;\n videoWriterHandle = VideoWriter(sprintf('%s%s.mp4', this.path.discrDataSave, datestr(now, 'yyyymmdd_HHMMSS')), 'MPEG-4');\n this.GUI.di.camHandle.DiskLogger = videoWriterHandle;\n\n % start the recording\n start(this.GUI.di.camHandle);\n \nelseif strcmp(commandString, 'stop');\n \n stop(this.GUI.di.camHandle);\n \nend;\n\ncatch err;\n errStack = getStackText(err);\n showWarning(this, 'OCIA:DIStartStopCamera', sprintf('Problem in the Discriminator camera start/stop function: \"%s\".', err.message));\n o(errStack, 0, 0);\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "INRunExp_trigInTTLOut.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/INRunExp_trigInTTLOut.m", "size": 5723, "source_encoding": "utf_8", "md5": "e2655bca7a3289d93c5abc75499bcb6b", "text": "function INRunExp_trigInTTLOut(this)\n% INRunExp_trigInTTLOut - [no description]\n%\n% INRunExp_trigInTTLOut(this)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\nparams = this.in.(this.in.expMode);\nif this.in.TTLOutStr.isWorking; return; end;\n\nif ~this.in.expRunning;\n exitTriggerMode(this, struct('identifier', 'OCIA:INRunExp_trigInTTLOut:Aborted', ...\n 'message', 'Error during stimulation (\"OCIA:INRunExp_trigInTTLOut:Aborted\"): aborted.'));\nend;\n\n% showMessage(this, sprintf('%s | Intrinsic: trigger time !', INGetTime(this)));\nthis.in.TTLOutStr.isWorking = true;\n\ntry \n\n this.in.TTLOutStr.trigTime = nowUNIXSec();\n iTrial = this.in.TTLOutStr.iTrial;\n stimNum = this.in.TTLOutStr.stimVect(iTrial);\n stimID = this.in.TTLOutStr.stimNames{iTrial};\n if isnumeric(stimID); stimID = sprintf('%d', stimID); end;\n showMessage(this, sprintf('%s | Intrinsic: trial %d / %d, current stimulus: %d (%s) ...', ...\n INGetTime(this), iTrial, this.in.TTLOutStr.nTrials, stimNum, stimID));\n\n % stimulation depends on current trial type\n switch stimID;\n \n case 'auditory';\n% % launch stimulus with software trigger\n% this.in.RP.SoftTrg(1);\n \n case 'visual';\n INSendTTLOutTrigger(this, [5 0], 1, [0.1, 0], this.in.trial.BLDur + this.in.TTLOutStr.fixedTrigDelay);\n \n case 'somatosensory';\n INSendTTLOutTrigger(this, [0 2], 2, [0.025, 0.025], this.in.trial.BLDur + this.in.TTLOutStr.fixedTrigDelay);\n \n case 'blank';\n % do nothing\n \n otherwise;\n % if it is a frequency\n if regexp(stimID, '\\d+');\n % launch stimulus with software trigger\n this.in.RP.SoftTrg(1);\n \n else\n exitTriggerMode(this, struct('identifier', 'OCIA:INRunExp_trigInTTLOut:UnknownStim', ...\n 'message', 'Error during stimulation (\"OCIA:INRunExp_trigInTTLOut:UnknownStim\"): unknown stimulus.'));\n end;\n end;\n \n this.in.TTLOutStr.iTrial = this.in.TTLOutStr.iTrial + 1;\n \n isMultiSensory = numel(params.stimIDs) == 4 ...\n && all(strcmp(params.stimIDs, { 'auditory', 'visual', 'somatosensory', 'blank' }));\n \n % if number of trials is reached\n if this.in.TTLOutStr.iTrial > this.in.TTLOutStr.nTrials;\n pauseTicToc(1);\n exitTriggerMode(this, []);\n return;\n \n % multi-sensory\n elseif isMultiSensory;\n % wait and prepare next stimulus\n pause(1.1 * (this.in.trial.BLDur + this.in.trial.triStimDur));\n iNextTrial = this.in.TTLOutStr.iTrial;\n stimNumNextTrial = this.in.TTLOutStr.stimVect(iNextTrial);\n stimIDNextTrial = this.in.TTLOutStr.stimNames{iNextTrial};\n if isnumeric(stimIDNextTrial); stimIDNextTrial = sprintf('%d', stimIDNextTrial); end;\n \n % next stim is auditory\n if strcmp(stimIDNextTrial, 'auditory');\n showMessage(this, sprintf('%s | Intrinsic: preparing next trial as auditory %d / %d, %d (%s) ...', ...\n INGetTime(this), iNextTrial, this.in.TTLOutStr.nTrials, stimNumNextTrial, stimIDNextTrial));\n % load sound stimulus\n this.in.RP = playTDTSound(this.in.TTLOutStr.soundsToPlay .* this.in.TTLOutStr.amplif, 0, this.GUI.figH, 0);\n else\n showMessage(this, sprintf('%s | Intrinsic: preparing next trial as no-sound %d / %d, %d (%s) ...', ...\n INGetTime(this), iNextTrial, this.in.TTLOutStr.nTrials, stimNumNextTrial, stimIDNextTrial));\n % load empty stimulus\n this.in.RP = playTDTSound([0 0], 0, this.GUI.figH, 0);\n end;\n \n % if not in multi-sensory mode \n elseif ~isMultiSensory;\n % wait and prepare next stimulus\n pause(1.1 * (this.in.trial.BLDur + this.in.trial.triStimDur));\n iNextTrial = this.in.TTLOutStr.iTrial;\n stimNumNextTrial = this.in.TTLOutStr.stimVect(iNextTrial);\n stimIDNextTrial = this.in.TTLOutStr.stimNames{iNextTrial};\n if isnumeric(stimIDNextTrial); stimIDNextTrial = sprintf('%d', stimIDNextTrial); end;\n showMessage(this, sprintf('%s | Intrinsic: preparing next trial with freq %d / %d, %d (%s) ...', ...\n INGetTime(this), iNextTrial, this.in.TTLOutStr.nTrials, stimNumNextTrial, stimIDNextTrial));\n % prepare next stimulus\n currentSoundToPlay = this.in.TTLOutStr.soundsToPlay(this.in.TTLOutStr.stimVect(this.in.TTLOutStr.iTrial), :);\n this.in.RP = playTDTSound(currentSoundToPlay .* this.in.TTLOutStr.amplif, 0, this.GUI.figH, 0);\n \n end;\n \n% if something failed\ncatch err;\n exitTriggerMode(this, err);\n \nend;\n\nthis.in.TTLOutStr.isWorking = false;\n\nend\n\nfunction exitTriggerMode(this, err)\n\nwarning('off', 'MATLAB:callback:error');\n\n% stop data aquisition\nstop(this.in.daq.sessHandle{1});\n\n% stop timer\nif isfield(this.in.TTLOutStr, 'timer');\n stop(this.in.TTLOutStr.timer);\nend;\nthis.in.TTLOutStr.isWorking = false;\n\nif ~isempty(err);\n showWarning(this, 'OCIA:INRunExp_trigInTTLOut:StimFailed', ...\n sprintf('Error during stimulation (\"%s\"): %s.', err.identifier, err.message));\n \nend;\n\n% release resources\nINCleanUp(this);\n\n% set flags, update counter and update GUI\nthis.in.expRunning = false;\nset(this.GUI.handles.in.runExpBut, 'BackgroundColor', 'red', 'Value', 0);\n\nif isempty(err);\n showMessage(this, sprintf('%s | Intrinsic: finished.', INGetTime(this)));\nelse\n showMessage(this, sprintf('%s | Intrinsic: aborted.', INGetTime(this)));\nend;\n\nwarning('on', 'MATLAB:callback:error');\n \nend\n\n\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "BERunTrial.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/BERunTrial.m", "size": 41549, "source_encoding": "utf_8", "md5": "0645e93632a4428e9495406823adfe13", "text": "function BERunTrial(this)\n% BERunTrial - [no description]\n%\n% BERunTrial(this)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\n% /!\\ NOTE: all times are in seconds (with decimals though) since trial start or trial init\n\n% init some variables\ntrainConf = this.be.config.training;\ntoneConf = this.be.config.tone;\nparams = this.be.params;\nBETimes = this.be.times;\niTrial = this.be.iTrial;\ntPhase = this.be.trialPhase;\nnTrials = this.be.config.training.nTrials;\n\n% check if experiment is paused/stopped\nif ~this.be.isRunning;\n return;\nend;\n\n\n%% PHASE SWITCH\n% what we have to do depends on which phase of the trial we are\nswitch tPhase;\n \n %% initialize trial\n % this is not the start of the trial yet\n case 'init';\n \n % clear previous data\n BEClearData(this);\n \n % get init time\n BETimes.init(iTrial) = roundn(nowUNIXSec(), -3);\n o('Times:init: %.3f', BETimes.init(iTrial), 2, this.verb); \n\n o('==================================================================', 1, this.verb);\n showMessage(this, sprintf('%s | Trial %03d/%03d - start ... ', datestr(now(), this.be.logDateFormat), ...\n iTrial, trainConf.nTrials), 'yellow');\n o('%s | start ...', datestr(now(), this.be.logDateFormat), 2, this.verb); \n\n % move to next phase\n this.be.trialPhase = 'moveSpot';\n \n %% move spots\n case 'moveSpot';\n \n o('%s | moveSpot ...', datestr(now(), this.be.logDateFormat), 2, this.verb); \n % if spot matrix is not empty, move spots\n if isfield(this.be, 'spotMatrix') && ~isempty(this.be.spotMatrix);\n \n % get the current spot for this trial\n currentSpot = this.be.spotMatrix(iTrial);\n \n % record time\n BETimes.ETLTrigStart(iTrial) = getTSinceInit();\n o('Times:ETLTrigStart: %.3f', BETimes.ETLTrigStart(iTrial), 3, this.verb);\n \n % select right spot and move there\n BEETLTableAction(this, [], [], 'select', currentSpot);\n BEETLTableAction(this, [], [], 'go'); \n \n % record time\n BETimes.ETLTrigEnd(iTrial) = getTSinceInit();\n o('Times:ETLTrigEnd: %.3f', BETimes.ETLTrigEnd(iTrial), 3, this.verb);\n \n end;\n \n % move to next phase\n this.be.trialPhase = 'vidRec';\n \n %% start video recording\n case 'vidRec';\n\n o('%s | vidRec ...', datestr(now(), this.be.logDateFormat), 2, this.verb); \n % if video recording is enabled\n if isfield(this.GUI.handles.be, 'vidRecEnableOn') && get(this.GUI.handles.be.vidRecEnableOn, 'Value') ...\n && (~isempty(regexp(this.be.phase, '^(LWP|QW)', 'once')) && iTrial == 1);\n \n % triggering not done yet\n if isnan(BETimes.vidStartTCPTrig(iTrial));\n \n showMessage(this, sprintf('%s | Trial %03d/%03d - video start trigger ... ', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');\n\n % record trigger time\n BETimes.vidStartTCPTrig(iTrial) = getTSinceInit();\n o('Times:vidStartTCPTrig: %.3f', BETimes.vidStartTCPTrig(iTrial), 3, this.verb);\n\n % send trigger and message for the behavior movie recording on the remote computer using a timer\n dateString = datestr(now, 'yyyy_mm_dd');\n trialName = sprintf('%s_%s_trial%02d.avi', regexprep(dateString, '_', ''), ...\n datestr(now, 'HHMMSS'), iTrial);\n set(this.GUI.be.vidTrigTimer, 'UserData', trialName);\n start(this.GUI.be.vidTrigTimer);\n \n % triggering done and wait time finished\n elseif getTSinceInit() > BETimes.vidStartTCPTrig(iTrial) + params.vidRecDelay(1);\n\n % move to next phase\n this.be.trialPhase = 'loadSound';\n \n % trigger sent but wait time not yet finished\n else\n \n o('#%s(): waiting for video start trigger ...', mfilename(), 3, this.verb);\n \n end;\n \n % no video triggering\n else\n \n % move to next phase\n this.be.trialPhase = 'loadSound';\n\n end;\n \n %% load sound\n case 'loadSound';\n\n o('%s | loadSound ...', datestr(now(), this.be.logDateFormat), 2, this.verb); \n showMessage(this, sprintf('%s | Trial %03d/%03d - loading sound ... ', datestr(now(), this.be.logDateFormat), ...\n iTrial, trainConf.nTrials), 'yellow');\n \n % load sound into the TDT if required\n if this.be.useTDT;\n \n TDTLoadTic = tic;\n BETimes.soundLoadStart(iTrial) = getTSinceInit();\n % attenuation = randi(4, 1) - 1; % randomized 0 - 3 dB SPL attenuation\n attenuation = 0;\n this.be.TDTRP = playTDTSound(this.be.toneArray{iTrial}, attenuation, this.GUI.figH, 1);\n BETimes.soundLoadEnd(iTrial) = getTSinceInit();\n o('#%s(): TDT loaded, attenuation: %d dB SPL (%.3f)', mfilename(), attenuation, toc(TDTLoadTic), ...\n 2, this.verb);\n% showMessage(this, sprintf('%s | Trial %03d/%03d - TDT loaded ... ', ...\n% datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');\n \n % initialize a standard audio player\n else\n \n BETimes.soundLoadStart(iTrial) = getTSinceInit();\n this.be.audioplayer = audioplayer(this.be.toneArray{iTrial}, toneConf.samplingFreq);\n BETimes.soundLoadEnd(iTrial) = getTSinceInit();\n o('#%s(): normal audioplayer loaded', mfilename(), 2, this.verb);\n \n end;\n \n % move to next phase\n this.be.trialPhase = 'start';\n\n %% start the trial (random start delay)\n case 'start'; \n \n % random start delay waiting not started yet\n if isnan(BETimes.startDelay(iTrial));\n \n % calculate a random delay for starting the sounds\n randomStartDelay = trainConf.startDelay + (rand - 0.5) * 2 * trainConf.startDelayRand;\n BETimes.startDelay(iTrial) = randomStartDelay;\n o('Times:startDelay: %.3f', BETimes.startDelay(iTrial), 3, this.verb);\n showMessage(this, sprintf('%s | Trial %03d/%03d - start delay: %.3f sec. ', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, BETimes.startDelay(iTrial)), ...\n 'yellow'); \n \n % mark trial as started\n BETimes.start(iTrial) = BETimes.init(iTrial) + size(this.be.anInData.piezo, 1) / this.be.hw.anInSampRate;\n o('Times:start: %.3f', BETimes.start(iTrial), 2, this.verb); \n\n % start the imaging before the random start delay\n BEImagingTTL(this, 1);\n BETimes.imgStart(iTrial) = getTSinceStart();\n o('Times:imgStart: %.3f', BETimes.imgStart(iTrial), 2, this.verb);\n \n % random start delay not finished and one second since imaging start\n elseif getTSinceStart() <= BETimes.startDelay(iTrial) && isnan(BETimes.trialStartCue(iTrial)) ...\n && getTSinceStart() > BETimes.imgStart(iTrial) + 1;\n \n BETimes.trialStartCue(iTrial) = getTSinceStart();\n % trial start cue\n o('#%s(): trial start cue at %.3f ...', mfilename(), getTSinceStart(), 2, this.verb);\n pulseParams = num2cell(trainConf.trialStartLightCueParams);\n BELightPulse(this, pulseParams{:});\n \n % random start delay waiting finished\n elseif getTSinceStart() > BETimes.startDelay(iTrial);\n \n % move to next phase\n this.be.trialPhase = 'playSound';\n\n % trigger sent but wait time not yet finished\n else\n \n o('#%s(): waiting for start delay ...', mfilename(), 3, this.verb);\n \n end;\n\n %% play sound\n case 'playSound';\n \n % play sound using TDT\n if this.be.useTDT;\n \n this.be.TDTRP.SoftTrg(1);\n BETimes.sound(iTrial) = getTSinceStart();\n o('Times:sound: %.3f', BETimes.sound(iTrial), 2, this.verb);\n \n % play sound without TDT\n else\n \n % play sound using standard audio player\n this.be.audioplayer.play();\n BETimes.sound(iTrial) = getTSinceStart();\n o('Times:sound: %.3f', BETimes.sound(iTrial), 2, this.verb);\n \n end;\n \n % move to next phase\n this.be.trialPhase = 'initWaitResp';\n \n %% initialize waiting response period\n case 'initWaitResp';\n \n % waiting starts now\n BETimes.respWaitStart(iTrial) = getTSinceStart();\n \n % random delay for the minimum response time (response window start)\n randomRespMinDelay = (rand - 0.5) * 2 * trainConf.minRespRand;\n o('randomRespMinDelay: %.3f', randomRespMinDelay, 3, this.verb);\n showMessage(this, sprintf('%s | Trial %03d/%03d - resp. window delay: %.3f sec (%.3f + %.3f).', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, trainConf.minRespTime ...\n + randomRespMinDelay, trainConf.minRespTime, randomRespMinDelay), 'yellow'); \n \n % init the minimum (start) and maximum (end) times for the response window\n BETimes.respMin(iTrial) = BETimes.respWaitStart(iTrial) + trainConf.minRespTime + randomRespMinDelay;\n BETimes.respMax(iTrial) = BETimes.respWaitStart(iTrial) + trainConf.maxRespTime + randomRespMinDelay;\n \n % initialize the time for the light cue to start and stop\n BETimes.lightIn(iTrial) = BETimes.respWaitStart(iTrial) + trainConf.lightInTime + randomRespMinDelay;\n BETimes.lightOut(iTrial) = BETimes.lightIn(iTrial) + trainConf.lightDur;\n \n % print out all this stuff\n o('Times:respWaitStart: %.3f', BETimes.respWaitStart(iTrial), 2, this.verb);\n o('Times:respMin: %.3f', BETimes.respMin(iTrial), 2, this.verb);\n o('Times:lightIn: %.3f', BETimes.lightIn(iTrial), 3, this.verb);\n o('Times:lightOut: %.3f', BETimes.lightIn(iTrial), 3, this.verb);\n o('Times:respMax: %.3f', BETimes.respMax(iTrial), 3, this.verb);\n\n % display message appropriate message depending on whether the animal has actually to respond or not:\n % presence of a GO stimulus means a response is expected\n if ~isempty(toneConf.goStim);\n \n showMessage(this, sprintf('%s | Trial %03d/%03d - waiting for response ... ', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');\n \n % do not set a time to wait for the sound to finish\n BETimes.soundDur(iTrial) = 0;\n \n % no go stim means response is not expected\n else\n \n % calculate sound duration in seconds using number of samples and sampling frequency of the TDT\n soundDur = numel(this.be.toneArray{iTrial}) / toneConf.samplingFreq;\n \n showMessage(this, sprintf('%s | Trial %03d/%03d - playing sound (%.2f sec duration) ... ', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, soundDur), 'yellow');\n \n % set a time to wait for the sound to finish\n BETimes.soundDur(iTrial) = soundDur;\n \n end;\n \n o('Times:soundDur: %.3f', BETimes.soundDur(iTrial), 3, this.verb);\n o('Times:sound+soundDur: %.3f', BETimes.sound(iTrial) + BETimes.soundDur(iTrial), 3, this.verb);\n \n % move to next phase\n this.be.trialPhase = 'waitResp';\n\n \n %% wait for response\n case 'waitResp';\n \n % if this is the first time we are waiting for response\n if isnan(BETimes.respWaitRealStart(iTrial));\n \n % real waiting starts now\n BETimes.respWaitRealStart(iTrial) = getTSinceStart();\n\n % init some variables for this trial\n this.be.lightCueGiven(iTrial) = 0;\n this.be.autoRewardGiven(iTrial) = 0;\n this.be.autoRewardModes{iTrial} = params.autoRewardMode;\n \n % check if auto-reward should be given because of misses\n if isfield(trainConf, 'NMissToGiveAutoRewardAfter') && ~isinf(trainConf.NMissToGiveAutoRewardAfter);\n lastHit = find(this.be.respTypes == 1, 1, 'last');\n if isempty(lastHit);\n lastHit = 1;\n end;\n nMisses = numel(this.be.respTypes((lastHit + 1) : (iTrial - 1)) == 4);\n if nMisses >= trainConf.NMissToGiveAutoRewardAfter;\n showMessage(this, sprintf(...\n '%s | Trial %03d/%03d - auto-reward because of %d miss ...', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, nMisses), 'yellow');\n this.be.autoRewardModes{iTrial} = 'EarlyOn';\n end;\n end;\n \n % determine whether earlies are allowed or not\n if trainConf.allowEarlyLicks >= 1;\n this.be.earlyAllowed(iTrial) = 1;\n showMessage(this, sprintf('%s | Trial %03d/%03d - earlies allowed by config.', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');\n\n elseif trainConf.allowEarlyLicks <= 0;\n this.be.earlyAllowed(iTrial) = 0;\n showMessage(this, sprintf('%s | Trial %03d/%03d - earlies *not* allowed by config.', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');\n\n % probabilistic\n else\n randNum = rand();\n this.be.earlyAllowed(iTrial) = randNum <= trainConf.allowEarlyLicks;\n showMessage(this, sprintf( ...\n '%s | Trial %03d/%03d - earlies given by probability of %.2f: rand = %.2f => %sallowed.', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, ...\n trainConf.allowEarlyLicks, randNum, iff(this.be.earlyAllowed(iTrial), '', '*not* ')), 'yellow');\n end;\n \n end;\n \n % if we are still within the waiting window\n if getTSinceStart() < (BETimes.respMax(iTrial) + BETimes.soundDur(iTrial));\n\n o('#%s: response waiting loop ... %.3f', mfilename(), getTSinceStart(), 4, this.verb);\n\n %% - wait for response: light on\n % only give reward cue if there is a reward, if light cue has not yet been given and \"lightIn\" is passed\n if params.rewDur > 0 && isnan(BETimes.lightCueOn(iTrial)) && getTSinceStart() > BETimes.lightIn(iTrial);\n\n % if light is not yet on, turn it on\n if isnan(BETimes.lightCueOn(iTrial));\n \n BETimes.lightCueOn(iTrial) = getTSinceStart();\n this.be.lightCueGiven(iTrial) = 1;\n o('#%s(): light cue on (%.3f) ...', mfilename(), BETimes.lightCueOn(iTrial), 3, this.verb);\n pulseParams = num2cell(trainConf.rewardPeriodLightCueParams);\n BELightPulse(this, pulseParams{:});\n\n % light cue on but light must still be on\n else\n \n o('#%s(): lightCueOn: %d, tDiff: %.3f, timeSinceStart: %.3f ...', mfilename(), lightCueOn, ...\n (BETimes.lightCueOn(iTrial) + lightOnDur) - getTSinceStart(), ...\n getTSinceStart(), 2, this.verb); \n \n end;\n \n end;\n\n %% - wait for response: light off\n % turn light off if needed\n if ~isnan(BETimes.lightCueOn(iTrial)) && isnan(BETimes.lightCueOff(iTrial)) && getTSinceStart() > BETimes.lightOut(iTrial);\n\n BELight(this, 0);\n BETimes.lightCueOff(iTrial) = getTSinceStart();\n o('#%s(): light cue off (%.3f) ...', mfilename(), BETimes.lightCueOff(iTrial), 3, this.verb);\n \n end;\n\n %% - wait for response: 'EarlyOn' reward\n % in 'EarlyOn' mode, reward happens at some fraction of time of the response window\n respWindowDur = BETimes.respMax(iTrial) - BETimes.respMin(iTrial);\n EORespTime = BETimes.respMin(iTrial) + params.autoRewardEarlyOnTimeFraction * respWindowDur;\n isEarlyOn = strcmp(this.be.autoRewardModes{iTrial}, 'EarlyOn') && (isempty(toneConf.goStim) ...\n || ismember(this.be.stims(iTrial), toneConf.goStim));\n \n % if 'EarlyOn' mode is on and reward has not yet been given and 'EarlyOn' time is passed and trial is target\n if params.rewDur > 0 && isEarlyOn && ~this.be.autoRewardGiven(iTrial) && getTSinceStart() > EORespTime;\n \n this.be.autoRewardGiven(iTrial) = 1; \n \n BETimes.rewTime(iTrial) = getTSinceStart();\n o('Times:rewTime: %.3f', BETimes.rewTime(iTrial), 3, this.verb);\n \n BEGiveReward(this);\n this.be.giveRewards(iTrial) = 1;\n showMessage(this, sprintf('%s | Trial %03d/%03d - ''EarlyOn'' reward !', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');\n \n % calc reward collection time\n BETimes.rewCollStart(iTrial) = BETimes.rewTime(iTrial);\n o('Times:rewCollStart: %.3f', BETimes.rewCollStart(iTrial), 3, this.verb);\n BETimes.rewCollEnd(iTrial) = BETimes.rewTime(iTrial) + trainConf.rewCollTime;\n o('Times:rewCollEnd: %.3f', BETimes.rewCollEnd(iTrial), 3, this.verb);\n \n end;\n \n %% - wait for response: sound detection\n % only search for sound if not already found and if required\n if isnan(BETimes.realSound(iTrial)) && this.be.params.adjustForDelayWithSound;\n \n % get microphone data\n micr = linScale(abs(this.be.anInData.micr))';\n % get the number of samples\n nSamples = size(micr, 2);\n % get a range for the begining of the signal\n begRange = round(nSamples * 0.01 : nSamples * 0.1);\n % get thresholds factor\n soundThreshFactor = 30;\n % get a threshold for the sound onset\n soundYThresh = soundThreshFactor * std(micr(begRange));\n % get the samples that exceeds the threshold, adding the first sample to catch the\n % start of the first sound\n upSamples = [0 find(micr > soundYThresh)];\n % get the derivative of the upSamples, drops in the sample indexes indicate interruption of upSamples,\n % which means that there is a sound start\n upSamplesDiff = diff(upSamples);\n % use the ISI to find peaks. If no ISI, use 0.5 second\n ISI = 0.5;\n % difference between detected upSample derivative's peaks must be at least half of the ISI\n minISI = ISI * 0.5 * this.be.hw.anInSampRate;\n % get the index of the peaks where the derivative exceeds the ISI threshold and increment\n % by one to get the sound start index\n soundStartIndex = upSamples(find(upSamplesDiff >= minISI) + 1);\n %{\n % debug plot\n plot((1 : nSamples) / this.be.hw.anInSampRate, micr, 'Color', 'green');\n xLims = get(gca, 'XLim');\n hold on;\n plot(xLims, repmat(soundYThresh, 1, 2), 'Color', 'red', 'LineStyle', ':');\n title(sprintf('soundYThresh: %.6f, soundStartIndex: %d\\nsoundStartTime: %.2f', soundYThresh, ...\n soundStartIndex, soundStartIndex / this.be.hw.anInSampRate));\n hold off;\n %}\n % if some start index found\n if ~isempty(soundStartIndex);\n % only keep the first sound start\n if numel(soundStartIndex > 1); soundStartIndex = soundStartIndex(1); end;\n % get the sound start time\n BETimes.realSound(iTrial) = (soundStartIndex / this.be.hw.anInSampRate) ...\n - getTSinceInit() + getTSinceStart();\n o('Times:realSound: %.3f sec ', BETimes.realSound(iTrial), 3, this.verb);\n \n % calculate delay with actual sound\n manualOffset = 0.15;\n BETimes.soundDelay(iTrial) = BETimes.realSound(iTrial) - BETimes.sound(iTrial) - manualOffset;\n o('Times:soundDelay: %.3f sec ', BETimes.soundDelay(iTrial), 3, this.verb);\n \n showMessage(this, sprintf('%s | Trial %03d/%03d - soundDelay: %.3f sec. ', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, ...\n BETimes.soundDelay(iTrial)), 'yellow');\n \n % remove delay data\n BEClearData(this, round(BETimes.soundDelay(iTrial) * this.be.hw.anInSampRate));\n end;\n \n end;\n \n %% - wait for response: response detection\n % no response by default\n this.be.resps(iTrial) = 0;\n \n if ~isempty(toneConf.goStim);\n % get the number of samples that we have\n if isfield(this.be.anInData, 'piezo')\n nSamples = size(this.be.procAnInData.piezo, 1);\n else\n nSamples = 0;\n end;\n\n % calculate the number of samples between init and start\n nSamplesOffset = round((BETimes.start(iTrial) - BETimes.init(iTrial)) * this.be.hw.anInSampRate);\n % get the indexes of the samples that are within the response window\n startEarlyRespIndex = round((BETimes.respWaitStart(iTrial)) * this.be.hw.anInSampRate) + nSamplesOffset;\n startRespIndex = round(BETimes.respMin(iTrial) * this.be.hw.anInSampRate) + nSamplesOffset;\n endRespIndex = min(round(BETimes.respMax(iTrial) * this.be.hw.anInSampRate) + nSamplesOffset, nSamples);\n \n % only check for responses if we have enought samples\n if startEarlyRespIndex <= nSamples;\n\n % earlies not allowed and detection *before* response time\n if ~this.be.earlyAllowed(iTrial) && getTSinceStart() < BETimes.respMin(iTrial);\n\n % get the piezo lick sensor data\n piezoData = this.be.procAnInData.piezo;\n % response is true if any value is above the threshold\n this.be.resps(iTrial) = sum(piezoData(startEarlyRespIndex : end) > params.piezoThresh) >= 1;\n % if lick detected, mark it as early\n if this.be.resps(iTrial);\n this.be.respTypes(iTrial) = 5;\n end;\n \n % earlies allowed or not and detection is *after* response time\n elseif getTSinceStart() >= BETimes.respMin(iTrial);\n\n % get the piezo lick sensor data\n piezoData = this.be.procAnInData.piezo;\n % response is true if any value is above the threshold\n this.be.resps(iTrial) = sum(piezoData(startRespIndex : endRespIndex) > params.piezoThresh) >= 1;\n \n % no response detected yet\n else\n\n this.be.resps(iTrial) = 0;\n\n end;\n \n% % plot things for debug purposes\n% if any(piezoData > params.piezoThresh);\n% this.be.isRunning = 0;\n% stop(this.GUI.be.updateTimer);\n% figure();\n% t = (1 : nSamples) / this.be.hw.anInSampRate;\n% plot(t, linScale(piezoData));\n% hold on;\n% line([startEarlyRespIndex, startEarlyRespIndex] / this.be.hw.anInSampRate, [0 1], 'Color', 'r');\n% line([startRespIndex, startRespIndex] / this.be.hw.anInSampRate, [0 1], 'Color', 'g');\n% line([endRespIndex, endRespIndex] / this.be.hw.anInSampRate, [0 1], 'Color', 'm');\n% o('plot done', 0, 0);\n% end;\n\n % if not enought sample yet, no response can be detected\n else\n\n this.be.resps(iTrial) = 0;\n\n end;\n \n % if there was a response within the response window\n if this.be.resps(iTrial);\n\n % mark down response time and delay compared to response window start\n BETimes.respTime(iTrial) = getTSinceStart(); % artifical delay correction\n o('Times:resp: %.3f', BETimes.respTime(iTrial), 3, this.verb); \n this.be.respDelays(iTrial) = BETimes.respTime(iTrial) - BETimes.respMin(iTrial);\n o('Times:respDelays: %.3f', this.be.respDelays(iTrial), 3, this.verb);\n\n if this.be.respTypes(iTrial) == 5;\n lickType = 'EARLY';\n \n % if not 'EarlyOn' mode or the auto-reward has not been given yet, it is a \"true\" lick\n elseif ~isEarlyOn || ~this.be.autoRewardGiven(iTrial);\n lickType = 'LICK';\n\n % if in 'EarlyOn' mode and the auto-reward has been given, it is a \"induced\" (post-reward) lick\n else\n lickType = 'INDUCED LICK';\n\n end;\n\n % show the message with the lick type and the delay\n showMessage(this, sprintf('%s | Trial %03d/%03d - %s! (%.3f sec)', datestr(now(), ...\n this.be.logDateFormat), iTrial, nTrials, lickType, this.be.respDelays(iTrial)), 'yellow'); \n\n % move to next phase\n this.be.trialPhase = 'processDecision';\n\n end;\n end;\n\n % if we are not anymore in the waiting window\n else\n \n o('#%s(): end of response wait ... (%.3f)', mfilename(), getTSinceStart(), 3, this.verb);\n \n % move to next phase\n this.be.trialPhase = 'processDecision';\n \n end;\n\n \n %% process the decision\n case 'processDecision';\n\n % if it was turned on and not yet off, make sure light is off\n if ~isnan(BETimes.lightCueOn(iTrial)) && isnan(BETimes.lightCueOff(iTrial)) ...\n && getTSinceStart() > BETimes.lightOut(iTrial);\n BELight(this, 0);\n BETimes.lightCueOff(iTrial) = getTSinceStart();\n o('#%s(): light cue off (late) (%.3f) ...', mfilename(), BETimes.lightCueOff(iTrial), 2, this.verb);\n end;\n \n % if no response set yet, then set it to 0 (no response)\n if isnan(this.be.resps(iTrial)); this.be.resps(iTrial) = 0; end;\n\n % if goStim is empty, it means no behavior decision had to be made (no response)\n if ~isempty(toneConf.goStim);\n \n % get whether this is the target stimulus\n isTargetStim = ismember(this.be.stims(iTrial), toneConf.goStim);\n\n % only create a response type if it is not already set to \"early\"\n if this.be.respTypes(iTrial) == 5;\n \n % set outcome variables\n this.be.punishTimeOuts(iTrial) = 1;\n this.be.giveRewards(iTrial) = 0;\n\n % response and it was a target: hit (correct response) (respType = 1)\n elseif this.be.resps(iTrial) && isTargetStim;\n showMessage(this, sprintf('%s | Trial %03d/%03d - HIT! (%.3f sec)', datestr(now(), ...\n this.be.logDateFormat), iTrial, nTrials, this.be.respDelays(iTrial)), 'green');\n \n % set outcome variables\n this.be.respTypes(iTrial) = 1;\n this.be.punishTimeOuts(iTrial) = 0;\n this.be.giveRewards(iTrial) = 1;\n\n % NO response and it was NOT a target: correct rejection (respType = 2)\n elseif ~this.be.resps(iTrial) && ~isTargetStim;\n showMessage(this, sprintf('%s | Trial %03d/%03d - CORRECT REJECT!', ...\n datestr(now(), this.be.logDateFormat), iTrial, nTrials), 'green');\n \n % set outcome variables\n this.be.respTypes(iTrial) = 2;\n this.be.punishTimeOuts(iTrial) = 0;\n this.be.giveRewards(iTrial) = 0;\n \n % response and it was NOT a target: false alarm (respType = 3)\n elseif this.be.resps(iTrial) && ~isTargetStim;\n showMessage(this, sprintf('%s | Trial %03d/%03d - FALSE ALARM! (%.3f sec)', ...\n datestr(now(), this.be.logDateFormat), iTrial, nTrials, ...\n this.be.respDelays(iTrial)), 'red');\n \n % set outcome variables\n this.be.respTypes(iTrial) = 3;\n this.be.punishTimeOuts(iTrial) = 1;\n this.be.giveRewards(iTrial) = 0;\n \n % NO response and it was a target: miss (respType = 4)\n elseif ~this.be.resps(iTrial) && isTargetStim;\n showMessage(this, sprintf('%s | Trial %03d/%03d - MISS!', ...\n datestr(now(), this.be.logDateFormat), iTrial, nTrials), 'red');\n \n % set outcome variables\n this.be.respTypes(iTrial) = 4;\n this.be.punishTimeOuts(iTrial) = 0;\n this.be.giveRewards(iTrial) = 0;\n \n end;\n\n % process the auto-reward modes for reward outcomes\n switch this.be.autoRewardModes{iTrial};\n % give reward only if target stim (or no targets) AND not early lick\n case 'EarlyOn'; this.be.giveRewards(iTrial) ...\n = (isempty(toneConf.goStim) || ismember(this.be.stims(iTrial), toneConf.goStim)) ...\n && this.be.respTypes(iTrial) ~= 5;\n \n % give reward only if target stim (or no targets)\n case 'On'; this.be.giveRewards(iTrial) ...\n = (isempty(toneConf.goStim) || ismember(this.be.stims(iTrial), toneConf.goStim)) ...\n && this.be.respTypes(iTrial) ~= 5;\n \n % never give reward\n case 'Off'; this.be.giveRewards(iTrial) = 0;\n \n % do nothing, rewarding depends on mouse's response\n case 'Auto';\n otherwise;\n showWarning(this, 'OCIA:RunTrial:UnknownAutoRewardMode', ...\n sprintf('Unknown auto-reward mode: %s. Using default \"auto\" (reward: %d).', ...\n this.be.autoRewardModes{iTrial}, this.be.giveReards(iTrial)));\n end;\n \n % move to next phase\n this.be.trialPhase = 'reward';\n \n % no behavior decision (no response), skip to final wait time\n else\n \n % move to next phase\n this.be.trialPhase = 'finalWait';\n \n end;\n \n %% reward\n case 'reward';\n\n if ~this.be.giveRewards(iTrial);\n \n % move to next phase\n this.be.trialPhase = 'finalWait';\n \n % if reward was not already given for this phase\n elseif isnan(BETimes.rewCollStart(iTrial)) && this.be.giveRewards(iTrial);\n \n % only give reward if deserved and if not already given by auto-reward\n if this.be.giveRewards(iTrial) && ~this.be.autoRewardGiven(iTrial) && isnan(BETimes.rewTime(iTrial));\n BETimes.rewTime(iTrial) = getTSinceStart();\n o('Times:rewTime: %.3f', BETimes.rewTime(iTrial), 3, this.verb);\n showMessage(this, sprintf('%s | Trial %03d/%03d - reward !', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow'); \n BEGiveReward(this);\n end;\n \n % give time to collect it\n BETimes.rewCollStart(iTrial) = BETimes.rewTime(iTrial);\n o('Times:rewCollStart: %.3f', BETimes.rewCollStart(iTrial), 3, this.verb);\n BETimes.rewCollEnd(iTrial) = BETimes.rewTime(iTrial) + trainConf.rewCollTime;\n o('Times:rewCollEnd: %.3f', BETimes.rewCollEnd(iTrial), 3, this.verb);\n \n % prolongate light until the end of the collection period if needed\n BETimes.lightOut(iTrial) = max(BETimes.rewCollEnd(iTrial), BETimes.lightOut(iTrial));\n o('Times:lightOut: %.3f (prolongated (2))', BETimes.lightOut(iTrial), 3, this.verb);\n \n \n % if reward was already given for this phase and reward collection is done but spout is still in\n elseif ~isnan(BETimes.rewCollStart(iTrial)) && this.be.giveRewards(iTrial) ...\n && getTSinceStart() > BETimes.rewCollEnd(iTrial) && isnan(BETimes.spoutOut(iTrial));\n \n % calculate spout out time\n BETimes.spoutOut(iTrial) = getTSinceStart() + params.spoutDelay(2);\n \n % if reward was already given for this phase and reward collection is done and spout should be out\n elseif ~isnan(BETimes.rewCollStart(iTrial)) && this.be.giveRewards(iTrial) ...\n && getTSinceStart() > BETimes.rewCollEnd(iTrial) && ~isnan(BETimes.spoutOut(iTrial)) ;\n \n % remove spout\n% BESpoutPos(this, 0);\n\n % move to next phase\n this.be.trialPhase = 'finalWait';\n \n % spout time not yet defined means it is still reward collection\n elseif isnan(BETimes.spoutOut(iTrial));\n\n o('#%s(): waiting for reward collection ...', mfilename(), 3, this.verb); \n \n % spout time defined means it is still spout delay wait\n else\n \n o('#%s(): waiting for spout delay ...', 3, this.verb);\n \n end;\n \n \n % if it was turned on and not yet off, make sure light is off\n if ~isnan(BETimes.lightCueOn(iTrial)) && isnan(BETimes.lightCueOff(iTrial)) ...\n && getTSinceStart() > BETimes.lightOut(iTrial);\n BELight(this, 0);\n BETimes.lightCueOff(iTrial) = getTSinceStart();\n o('#%s(): light cue off (late (2)) (%.3f) ...', mfilename(), BETimes.lightCueOff(iTrial), 2, this.verb);\n end;\n \n %% final end wait (punishment & others)\n case 'finalWait';\n\n \n % no punishmend time yet\n if isnan(BETimes.endPunish(iTrial));\n \n % if no punish setting is not set yet, set it to 0 (no punish)\n if isnan(this.be.punishTimeOuts(iTrial)); this.be.punishTimeOuts(iTrial) = 0; end;\n \n % calculate the punishment delay\n punishDelay = iff(this.be.punishTimeOuts(iTrial), trainConf.timeoutPunish, 0);\n \n % play punishment sound\n if punishDelay > 0;\n o('Playing punishment sound ...', 3, this.verb);\n nLoops = round(min(trainConf.endDelay + punishDelay, 3) / 0.5);\n this.be.TDTRP.Halt();\n this.be.TDTRP = playTDTSound(this.be.punishSound, 0, this.GUI.figH, nLoops);\n this.be.TDTRP.SoftTrg(1);\n end;\n\n % calculate the end of punishment time\n BETimes.endPunish(iTrial) = getTSinceStart() + trainConf.endDelay + punishDelay;\n o('Times:endPunish: %.3f', BETimes.endPunish(iTrial), 3, this.verb);\n\n % calculate the expected end of the imaging\n BETimes.imgStopExp(iTrial) = BETimes.endPunish(iTrial) - punishDelay - params.imgEndStopTime;\n o('Times:imgStopExp: %.3f', BETimes.imgStopExp(iTrial), 3, this.verb);\n \n end;\n \n % set a minimum trial duration\n minTrialDuration = 13;\n if (getTSinceStart() - BETimes.imgStopExp(iTrial)) < minTrialDuration;\n BETimes.imgStopExp(iTrial) = minTrialDuration;\n end;\n\n % if imaging still runing and time to stop it has passed\n if getTSinceStart() > BETimes.imgStopExp(iTrial);\n \n % stop imaging\n if isnan(BETimes.imgStopObs(iTrial));\n \n % stop imaging\n BEImagingTTL(this, 0);\n BETimes.imgStopObs(iTrial) = getTSinceStart();\n o('Times:imgStopObs: %.3f', BETimes.imgStopObs(iTrial), 3, this.verb);\n \n end;\n \n % if time to finish trial has passed\n if getTSinceStart() > BETimes.endPunish(iTrial);\n \n showMessage(this, sprintf('%s | Trial %03d/%03d - done. ', datestr(now(), this.be.logDateFormat), ...\n iTrial, trainConf.nTrials), 'green');\n \n % move out from the trial running\n this.be.trialPhase = 'stopVidRec';\n \n % trial still runing but stop time is not yet arrived\n else\n\n o('#%s(): waiting for trial stop ...', mfilename(), 4, this.verb);\n\n end;\n \n % imaging is still runing but stop time is not yet arrived\n else\n \n o('#%s(): waiting for imaging stop ...', mfilename(), 4, this.verb);\n \n end;\n \n % if it was turned on and not yet off, make sure light is off\n if ~isnan(BETimes.lightCueOn(iTrial)) && isnan(BETimes.lightCueOff(iTrial)) ...\n && getTSinceStart() > BETimes.lightOut(iTrial);\n BELight(this, 0);\n BETimes.lightCueOff(iTrial) = getTSinceStart();\n o('#%s(): light cue off (late (3)) (%.3f) ...', mfilename(), BETimes.lightCueOff(iTrial), 2, this.verb);\n end;\n \n %% stop video recording\n case 'stopVidRec';\n\n % if video recording is enabled\n if isfield(this.GUI.handles.be, 'vidRecEnableOn') && get(this.GUI.handles.be.vidRecEnableOn, 'Value') ...\n && (~isempty(regexp(this.be.phase, '^(LWP|QW)', 'once')) && iTrial == trainConf.nTrials);\n \n % triggering not done yet\n if isnan(BETimes.vidEndTCPTrig(iTrial));\n \n showMessage(this, sprintf('%s | Trial %03d/%03d - video stop trigger ... ', ...\n datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');\n\n % record trigger time\n BETimes.vidEndTCPTrig(iTrial) = getTSinceStart();\n o('Times:vidEndTCPTrig: %.3f', BETimes.vidEndTCPTrig(iTrial), 3, this.verb);\n \n % send trigger to stop the behavior movie recording using a timer\n set(this.GUI.be.vidTrigTimer, 'UserData', 'stop');\n start(this.GUI.be.vidTrigTimer);\n \n % triggering done and wait time finished\n elseif getTSinceStart() > BETimes.vidEndTCPTrig(iTrial) + params.vidRecDelay(2);\n\n % move to next phase\n this.be.trialPhase = 'finished';\n \n % trigger sent but wait time not yet finished\n else\n \n o('#%s(): waiting for video stop trigger ...', mfilename(), 3, this.verb);\n \n end;\n \n % no video triggering\n else\n \n % move to next phase\n this.be.trialPhase = 'finished';\n\n end;\n\n %% paused\n case 'paused';\n \n % do nothing\n \n %% unknown phase\n otherwise;\n \n showMessage(this, sprintf('%s | Trial %03d/%03d: unknown phase \"%s\" ... ', datestr(now(), ...\n this.be.logDateFormat), iTrial, trainConf.nTrials, this.be.trialPhase), 'yellow');\n\nend;\n\n% store back the times\nthis.be.times = BETimes;\n\nfunction t = getTSinceStart()\n t = roundn(nowUNIXSec() - BETimes.start(iTrial), -3);\nend\n\nfunction t = getTSinceInit()\n t = roundn(nowUNIXSec() - BETimes.init(iTrial), -3);\nend\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "DWMatchROISetsToData.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/DWMatchROISetsToData.m", "size": 7461, "source_encoding": "utf_8", "md5": "7149efd47267f932563694835593decb", "text": "%% - #DWMatchROISetsToData\nfunction DWMatchROISetsToData(this)\n\n% update the wait bar\nDWWaitBar(this, 0);\n\n% get the list of all animals\nuniqueAnimals = get(this, 'animal');\nif ~isempty(uniqueAnimals) && ~iscell(uniqueAnimals); uniqueAnimals = { uniqueAnimals }; end;\nif isempty(uniqueAnimals); uniqueAnimals = { '' }; end;\nuniqueAnimals(cellfun(@isempty, uniqueAnimals)) = [];\nuniqueAnimals = unique(uniqueAnimals);\nnAnim = numel(uniqueAnimals);\n\n% get the list of all days\nuniqueDays = get(this, 'day');\nif ~isempty(uniqueDays) && ~iscell(uniqueDays); uniqueDays = { uniqueDays }; end;\nif isempty(uniqueDays); return; end;\nuniqueDays(cellfun(@isempty, uniqueDays)) = [];\nuniqueDays = unique(uniqueDays);\nnDays = numel(uniqueDays);\n\n% get the selected animal IDs\nselectedAnimalIDs = this.dw.animalIDs(get(this.GUI.handles.dw.filt.animalID, 'Value'));\n% if the dash '-' is selected, select all IDs\nif numel(selectedAnimalIDs) == 1 && strcmp(selectedAnimalIDs{1}, '-');\n selectedAnimalIDs = uniqueAnimals;\nend;\n\n% get the selected day IDs\nselectedDayIDs = this.dw.dayIDs(get(this.GUI.handles.dw.filt.dayID, 'Value'));\n% if the dash '-' is selected, select all IDs\nif numel(selectedDayIDs) == 1 && strcmp(selectedDayIDs{1}, '-');\n selectedDayIDs = uniqueDays;\nend;\n\n% go through each animal\nfor iAnim = 1 : nAnim; \n animalID = uniqueAnimals{iAnim}; % get the current animal\n\n % skip irrelevant animal IDs\n if ~ismember(animalID, selectedAnimalIDs);\n % update wait bar\n DWWaitBar(this, 100 * (iAnim / nAnim));\n continue;\n end;\n \n % go through each day\n for iDay = 1 : nDays; \n dayID = uniqueDays{iDay}; % get the current day\n\n % skip irrelevant days\n if ~ismember(dayID, selectedDayIDs);\n % update wait bar\n DWWaitBar(this, 100 * ((iDay / (nDays * nAnim)) + (iAnim - 1) / nAnim));\n continue;\n end;\n \n % get the ROISet rows\n ROISetRows = DWFilterTable(this, sprintf('animal = %s AND day = %s AND rowType = ROISet', animalID, dayID));\n nROISets = size(ROISetRows, 1); % count them\n % if no ROISets have been found, try without animal ID filtering\n if nROISets == 0;\n ROISetRows = DWFilterTable(this, sprintf('animal !~= \\\\w+ AND day = %s AND rowType = ROISet', dayID));\n nROISets = size(ROISetRows, 1); % count them\n end;\n % get the imaging rows\n imTypeFilter = iff(ismember(this.dw.tableIDs, 'imType'), ' AND imType = movie', '');\n imagingRows = DWFilterTable(this, sprintf('animal = %s AND day = %s AND rowType = Imaging data%s', ...\n animalID, dayID, imTypeFilter));\n nImagingRows = size(imagingRows, 1); % count them\n\n % go through each ROISet\n for iROISet = 1 : nROISets; \n\n % get the DataWatcher table's row index for this ROISet row\n iDWRowROISet = str2double(get(this, iROISet, 'rowNum', ROISetRows));\n % get the ROISet's row ID\n ROISetRowID = DWGetRowID(this, iDWRowROISet);\n % make sure the ROISet is loaded\n DWLoadRow(this, iDWRowROISet, 'full');\n % extract the data\n ROISetData = getData(this, iDWRowROISet, 'ROISets', 'data');\n % abort if the data cannot be found\n if isempty(ROISetData);\n showWarning(this, 'OCIA:DWMatchROISetsToData:ROISetDataNotFound', ...\n sprintf('Could not find ROISet data for %s (row %03d). Skipping it.', ROISetRowID, iDWRowROISet)); \n % update wait bar\n DWWaitBar(this, 100 * ((iROISet / (nROISets * nDays * nAnim)) + ((iDay - 1) / (nDays * nAnim)) + (iAnim - 1) / nAnim));\n continue;\n end;\n % get the ROISet's \"runsValidity\", which tells which trials/runs are valid for this ROISet\n runsValidity = ROISetData.runsValidity;\n if ~iscell(runsValidity) && ~isempty(runsValidity); runsValidity = { runsValidity }; end;\n % if the runsValidity are in the old format 'YYYY_MM_DD__hh_mm_ss', convert them to the new 'YYYYMMDD_hhmmss' format\n if ~isempty(runsValidity) && ~isempty(regexp(runsValidity{1}, '\\d{4}_\\d{2}_\\d{2}__\\d{2}_\\d{2}_\\d{2}', 'once'));\n runsValidity = cellfun(@(id)id([1 : 4, 6 : 7, 9 : 10, 12 : 14, 16 : 17, 19 : 20]), runsValidity, ...\n 'UniformOutput', false);\n end;\n\n % if no imaging rows, try to figure out the spot identity of this ROISet\n if nImagingRows <= 0;\n\n % get the ROISet's path\n ROISetPath = get(this, iDWRowROISet, 'path');\n % go through each possible spot\n for iSpot = 1 : 10;\n % get the spot folder's path\n spotPath = regexprep(regexprep(ROISetPath, '/[^/]+$', '/'), 'ROISets', sprintf('spot%02d', iSpot));\n\n % go through each possible row\n for iRun = 1 : numel(runsValidity);\n % get the spot folder's path\n dataPath = sprintf('%s%s_%s_%s__%s_%s_%sh/', spotPath, runsValidity{iRun}(1:4), runsValidity{iRun}(5:6), ...\n runsValidity{iRun}(7:8), runsValidity{iRun}(10:11), runsValidity{iRun}(12:13), runsValidity{iRun}(14:15));\n\n % check if the data exists\n if exist(dataPath, 'dir');\n set(this, iDWRowROISet, 'spot', sprintf('spot%02d', iSpot)); \n break;\n end;\n end;\n\n % if spot was found, interrupt search\n if ~isempty(get(this, iDWRowROISet, 'spot')); break; \n end;\n end;\n continue;\n end;\n\n % go through each imaging row\n for iImagingRow = 1 : nImagingRows;\n\n % get the DataWatcher table's row index for this imaging row\n iDWRowImaging = str2double(get(this, iImagingRow, 'rowNum', imagingRows));\n % get the row ID for the current imaging row\n imagingRowID = DWGetRowID(this, iDWRowImaging);\n\n % if there is a match compare the runs validity of the ROISet with this row's ID\n if any(strcmp(runsValidity, imagingRowID)); \n % label the current imaging row as belonging to the current ROISet\n set(this, iDWRowImaging, 'ROISet', ROISetRowID);\n % if the ROISet does not have a spot ID specified, add the one from the imaging row\n if isempty(get(this, iDWRowROISet, 'spot'));\n set(this, iDWRowROISet, 'spot', get(this, iDWRowImaging, 'spot')); \n end;\n % if there is a GUI and the ROISet's reference image is from the current imaging row\n if isGUI(this) && strcmp(imagingRowID, ROISetRowID);\n set(this, iDWRowImaging, 'ROISet', sprintf('%s', ROISetRowID));\n end;\n end;\n end;\n\n % update wait bar\n DWWaitBar(this, 100 * ((iROISet / (nROISets * nDays * nAnim)) + ((iDay - 1) / (nDays * nAnim)) + (iAnim - 1) / nAnim));\n\n end; \n end; \nend;\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/OCIA.m", "size": 77388, "source_encoding": "utf_8", "md5": "77043c2f7b13e21ffd1f9a11c36961a1", "text": "classdef OCIA < handle\r\n% OCIA - Online Calcium Imaging Assistant\r\n%\r\n% this = OCIA()\r\n% this = OCIA(configName)\r\n% this = OCIA(configName, DWFilt)\r\n%\r\n% Returns an OCIA object 'this', using the configuration file specified by 'configName' using the syntax\r\n% \"OCIA_config_[configName].m\". If no configuration is specified, \"OCIA_config_default.m\" is used. Starting filters\r\n% for the DataWatcher can be specified using the 'DWFilt', either as a string ('all', etc.) or cell-array of strings\r\n% ( {'animalID1', '2014_10_30', 'spot03', ... } ). The file 'OCIA_config_generic' contains all the parameters that\r\n% can be changed in a custom config file.\r\n\r\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n% % Originally created on 08 / 10 / 2013 %\r\n% % Modified to v2.0 on 20 / 12 / 2013 %\r\n% % Modified to v3.0 on 21 / 02 / 2014 %\r\n% % Modified to v4.0 on 19 / 06 / 2014 %\r\n% % Modified to v5.0 on 15 / 09 / 2014 %\r\n% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\n%\r\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\r\n\r\n\r\n%% TODO list\r\n%{\r\n\r\n- General\r\n -- add the possibility to have a type of folder in multiple locations (e.g. parent of imgData could be spot OR day)\r\n -- frame jitter, motion correction and motion detection should be independent of a ROISet\r\n -- OCIA_config_default should not initiate the default config itself but call an initiator function \"this =\r\n initDefault(this)\" or something otherwise the names are confusing\r\n -- add icons to buttons for easier recognition\r\n -- pre-processing GUI: uipanel with options for nFrameSkip(default=0)/fShift/fJitt/moCorr/moDet\r\n options as checkboxes, and a \"pre-process rows\" button (ANPreProcRows). DWLoad('prev') should do none\r\n of these corrections, except frameShift and frameSkip.\r\n Add a display fig checkbox linked to the doPlots of the pre-processing functions.\r\n -- save load modularity:\r\n --- make the GUI dynamic for the saving options, based on the data's field and configuration\r\n --- adapt the saving code so that it saves the right things at the right place\r\n --- fix the save/load/reset options\r\n -- check that flushdata works properly\r\n\r\n- DataWatcher\r\n -- add a \"delete rows\" function (hides the unwanted rows from the DataWatcher), also useful for the imagingWatcher mode\r\n -- intrinsic imaging: access binary file content, show vessels tif files,\r\n eventually overlap them with expression image using stiching algorithm\r\n -- behavior movie: read the video with 'video2mat.m' and eventually match frames to trials\r\n -- small thumbnail of the currently selected row(s) also for other data types (behavior, intrinsic, behavMovie)\r\n --- requires frame grouping (? la imageJ ...)\r\n -- only load imaging data once from the DataWatcher's table and then re-use it for analysis and ROI drawing\r\n -- enable the \"real\" analysis pipeline support : load imaging data files (.bin)(HDF5?)\r\n -- implement GUI items/config file for analysis parameters\r\nNO -- add a load metadata button to avoid re-processing all folders just for the metadata\r\nNO -- make the loaded rows' background green to show the data is loaded\r\nNO -- store where each behavior/data file was found and dont reload it if not necessary\r\n\r\n- ImagingWatcher\r\n -- create a new imaging assistant mode or extend the data-watcher to help with online analysis of the imaging\r\n --- could be on a different computer/matlab session for lower CPU on imaging computer and\r\n eventually parallel computing for faster loading/processing\r\n -- features:\r\n --- loading last recorded data\r\n --- \"quick\" ROIDrawing (semi-auto)\r\n --- \"quick\" DRR extract\r\n --- bleaching quantifier\r\n --- previous days data and metadata (laser, depth, location, surface image, etc.)\r\n\r\n- ROIDrawer\r\n -- modularity in ROISet saving location\r\n -- bug: remove old position callback in RDRenameROI\r\n -- channel selection for ROI drawing, gray scale image of one channel\r\n -- move all ROIs with small arrow GUI pushbuttons <- ^ ->\r\n -- implement an semi-automatic segmentation tool based on cell centers and ring/filled cell body detection\r\n -- cell identity labeling tool\r\n\r\n- Analyser\r\n -- implement a feature of analysing whole day/whole mice with analysRow button and watchType of only day or only animal\r\n -- resizing of the whole panel bug, probably when saving (or plotting?) plots\r\n -- enable the \"real\" analysis pipeline support (load imaging data files (HDF5?))\r\n -- check for colorbar plot saving (resizing issue)\r\n -- check for time-consuming sem calculation problem\r\n -- add plots for several mice\r\n -- implement a bleaching quantifier over multiple runs\r\n -- fix the colorbar saving problem\r\n -- fix the colormap problem\r\n -- fix the analyser plotting ROISet mismatch/non-unique problem\r\n -- when loading data in 'full' mode that was already loaded in 'prev', skip re-loading of 'prev' frames\r\n\r\n- Behavior\r\n -- check sound amplitude (SPL) *randomization*\r\n -- fix licking detection or switch to lick rate\r\n -- implement *alternative* detection system: lick rate\r\n -- introduce a configuration editor or GUI items for mainConf.mat elements\r\n -- save threshold and rewDur for each trial\r\n -- perf analysis: exclude first 3-10 trials + non-responsive regions\r\n -- auto-connect behavior box with COM port communication\r\n\r\n- JointTracker\r\n -- add coordinates display on mouse move\r\n -- load X frames until memory is full and then just load frames on the fly while changing frames\r\n -- when doing the sliding average, remove the existing frames and store them in the temp and then put it back\r\n -- re-process on the fly the subsequent joints when placing a joint (when placing wrist, re-find the MCP)\r\n -- crop function\r\n -- image pre-processing not everywhere but defined by ROI\r\n -- iJoint and iJointType from selection listbox should not be single values but must be arrays (multiple joint\r\n manipulation)\r\n -- prediction reaffinement\r\n --- define an \"area mask\" for each joint (or each group of joints), using imfreehand, to constraint their position\r\n --- use angles and joint distances to constraint the position of the joints\r\n --- use field flow technique to predict where the joint will move\r\n --- use correlation dip to change bounding box size (with a minimal box size setting)\r\n -- improve debug plot display so that one can actually see what is going on (nJoints x nProcessSteps image with labeld axes)\r\n -- create a progress bar to show how far we are and how is each frame annotated (manual, semi-auto validated, semi-auto not yet checked, etc.)\r\n -- correlation frame-to-frame or frame-wise only on the bounding boxes\r\n -- base frames pre-processing for better computer and/or manual annotation\r\n --- subtract sliding window avg image\r\n --- flatfield\r\n --- contrast enhancement\r\n -- base frames pre-processing might also only be applied to parts of the frame (like the sliding average only on the\r\n lower part of the frame)\r\n -- post-hoc evaluation method to get which joints are misplaced, based on:\r\n --- interpolation of the data points from next and previous joint coordinate ('outlier' detection)\r\n --- skelton distances\r\n --- angle-change vs frame-to-frame correlation\r\n -- post-hoc refinement of the match using smaller bounding box\r\n -- computer vision algorithms / ideas\r\n \r\n%}\r\n\r\n%% properties\r\nproperties\r\n\r\n % verbosity: number telling how much output should be printed out. The higher the more verbose.\r\n verb = 2;\r\n % general parameters: version number, start function name, modes, etc.\r\n main = struct( ...\r\n... software version\r\n 'version', '5.1.10', ...\r\n... start function name\r\n 'startFunctionName', 'default', ...\r\n... \"modules\" of the software that need to be included in the current instance\r\n 'modes', {{ ...\r\n % mode name short name\r\n 'DataWatcher', 'dw';\r\n 'ROIDrawer', 'rd';\r\n 'Analyser', 'an';\r\n 'Behavior', 'be';\r\n 'Intrinsic', 'in';\r\n 'JointTracker', 'jt';\r\n 'TrialView', 'tv';\r\n }}, ...\r\n... data types/modes that need to be included in the current instance\r\n 'dataModes', {{ 'img', 'behav' }}, ...\r\n... defines whether to show or hide the stack trace upon throwing a warning with the \"#showWarning\" method\r\n 'showWarningStackTraces', false ...\r\n );\r\n \r\n % paths used by the OCIA\r\n path = struct();\r\n \r\n % GUI related elements\r\n GUI = struct( 'noGUI', false );\r\n \r\n % - Data storage mode\r\n data = struct();\r\n \r\n % - DataWatcher mode\r\n dw = struct();\r\n % - ROIDrawer mode\r\n rd = struct();\r\n % - Analyser mode\r\n an = struct();\r\n % - Behavior mode\r\n be = struct();\r\n % - Intrinsic mode\r\n in = struct();\r\n % - JointTracker mode\r\n jt = struct();\r\n % - Discriminator mode\r\n di = struct();\r\n % - Discriminator mode\r\n tv = struct();\r\n\r\nend\r\n\r\n%% methods - public\r\nmethods\r\n\r\n%% - #OCIA - constructor\r\nfunction this = OCIA(varargin)\r\n% OCIA - Constructor\r\n%\r\n% this = OCIA()\r\n% this = OCIA(configName)\r\n% this = OCIA(configName, DWFilt)\r\n% this = OCIA(configName, DWFilt, startFunctionName)\r\n%\r\n% Returns an OCIA object 'this', using the configuration file specified by 'configName' using the syntax\r\n% \"OCIA_config_[configName].m\". If no configuration is specified, \"OCIA_config_default\" is used. Starting filters\r\n% for the DataWatcher can be specified using the 'DWFilt', either as a string ('all', etc.) or cell-array of strings\r\n% ( {'animalID1', '2014_10_30', 'spot03', ... } ). The file 'OCIA_config_generic' contains all the parameters that\r\n% can be changed in a custom config file. Optional 'startFunctionName' string can be provided.\r\n\r\n% Order of function calls for the creation of the object:\r\n% - parsing inputs ('configName' and 'DWFilt')\r\n% - call of the config specified by 'configName' (or 'default' if none provided)\r\n% - first, the \"modes\" that need to be included in the OCIA should be selected in the \"this.main.modes\", as a\r\n% N_MODES x 2 cell-array of strings, with first column being the mode's name ('DataWatcher') and the second\r\n% column the short name ('dw'). This needs to be done before the call to the 'OCIA_config_default' because\r\n% that function initializes the different modes.\r\n% - the \"data modes\" that need to be included in the OCIA should also be selected in the \"this.main.dataModes\",\r\n% as a cell-array of strings before the call to the 'OCIA_config_default' for the same reasons as above.\r\n% - then, 'OCIA_config_default.m' is called. It initiates the OCIA object ('this') with default configuration\r\n% values to start OCIA:\r\n% - path (local, raw, ...)\r\n% - modes (in case not initiated or dataWatcher mode not included)\r\n% - GUI variables (window position, etc.)\r\n% - initiate the different modes using their custom configuration functions: \r\n% 'OCIA_modeConfig_[modeName].m'. These will initiate each mode with the default values for the\r\n% variables needed to run those modes. For example in DataWatcher mode, the table's display, etc.\r\n% - initiate the different data modes using their custom configuration functions:\r\n% 'OCIA_dataConfig_[dataModeName].m'. These will initiate the 'this.main.dataConfig' cell-array which\r\n% describes what kind of data types need to be used/stored. These custom configuration function\r\n% can also eventually initiate some variables in the Analyser mode ('this.an.img' or 'this.an.be')\r\n% for the analysis of those data types (for example 'this.an.img.defaultFrameRate').\r\n% - initialization of the drop-down IDs of the DataWatcher to an empty dash ('-')\r\n% - Java path update for Java classes\r\n% - creation of the window\r\n% - creation of each panel using the custom 'OCIA_createWindow_[modeName].m' functions\r\n% - update of drop-down filters IDs based on the GUI values, which are initialized based on the 'DWFilt' input\r\n% ('OCIA_createWindow_dataWatcher.m' calls 'DWUpdateFiltersAndWatchTypes' to do this)\r\n% - window is made visible ('OCIA.show')\r\n% - custom start function is called 'OCIA_startFunction_[functionName].m' based on the config file's setting stored\r\n% under 'this.main.startFunctionName' \r\n \r\n o('#%s(): constructor ...', mfilename, 4, this.verb);\r\n o('Launching OCIA v%s ...', this.main.version, 0, this.verb);\r\n \r\n %% -- #OCIA: parse inputs and load config file\r\n o('#%s(): parsing inputs ...', mfilename, 4, this.verb);\r\n % prepare the input parser object with the requested inputs\r\n IP = inputParser;\r\n addOptional(IP, 'configName', 'default', @ischar);\r\n addOptional(IP, 'DWFilt', 'empty', @(x)isempty(x) || ischar(x) || iscell(x));\r\n addOptional(IP, 'startFunctionName', 'empty', @(x)ischar(x));\r\n parse(IP, varargin{:});\r\n \r\n % get the config function's name and call it\r\n configName = IP.Results.configName;\r\n o('#%s(): using config file \"%s\" ...', mfilename, configName, 4, this.verb);\r\n [~, thisNew] = OCIAGetCallCustomFile(this, 'config', configName, 1, { this }, 1);\r\n % abort if no \"this\" anymore\r\n if isempty(thisNew); return; end;\r\n % otherwise go on\r\n this = thisNew;\r\n \r\n % if DataWatcher filtering was provided as input, overwrite config's parameter with input parameter\r\n if ~strcmp(IP.Results.DWFilt, 'empty') && ~isempty(IP.Results.DWFilt);\r\n this.GUI.dw.DWFilt = IP.Results.DWFilt;\r\n end;\r\n o('#%s(): filtering elements: \" %s\" ...', mfilename, sprintf('%s - ', this.GUI.dw.DWFilt{:}), 4, this.verb);\r\n \r\n % if alternate start function name was provided\r\n if ~strcmp(IP.Results.startFunctionName, 'empty');\r\n this.main.startFunctionName = IP.Results.startFunctionName;\r\n end;\r\n o('#%s(): filtering elements: \" %s\" ...', mfilename, sprintf('%s - ', this.GUI.dw.DWFilt{:}), 4, this.verb);\r\n %% -- #OCIA: update the drop-down filters and table IDs\r\n % define the \"IDs\" field for each drop-down DataWatcher filter element\r\n dropDownFiltersIDs = this.GUI.dw.filtElems{strcmp(this.GUI.dw.filtElems.GUIType, 'dropdown'), 'id'};\r\n for iFilter = 1 : numel(dropDownFiltersIDs);\r\n % create a list with only a dash element, which corresponds to no filtering\r\n this.dw.([dropDownFiltersIDs{iFilter} 'IDs']) = {'-'};\r\n end;\r\n\r\n % fetch IDs\r\n this.dw.tableIDs = this.GUI.dw.tableDisplay.id;\r\n % init table to the right size\r\n this.dw.table = cell(300, numel(this.dw.tableIDs));\r\n \r\n % create order column if not yet present\r\n if ~ismember('order', this.GUI.dw.tableDisplay.Properties.VariableNames)\r\n this.GUI.dw.tableDisplay.order = (1 : size(this.GUI.dw.tableDisplay, 1))';\r\n end;\r\n \r\n %% -- #OCIA: turn warnings off\r\n warning('off', 'images:imshow:magnificationMustBeFitForDockedFigure');\r\n warning('off', 'MATLAB:hg:gltexture:TextureDataTooLargeForDevice');\r\n warning('off', 'YMA:FindJObj:invisibleHandle');\r\n warning('off', 'MATLAB:JavaEDTAutoDelegation');\r\n \r\n %% --#OCIA: clean up paths\r\n pathFields = fieldnames(this.path);\r\n for iField = 1 : numel(pathFields);\r\n fieldName = pathFields{iField};\r\n this.path.(fieldName) = regexprep([regexprep(this.path.(fieldName), '\\\\', '/'), '/'], '//$', '/');\r\n this.path.(fieldName) = regexprep(this.path.(fieldName), '(\\.\\w+)/', '$1');\r\n end;\r\n \r\n %% -- #OCIA: add java folders\r\n OCIAPath = regexprep(which('OCIA'), '\\\\', '/');\r\n OCIAPath = regexprep(OCIAPath, '/@OCIA/OCIA.m$', '');\r\n javaaddpath([OCIAPath '/java/ij.jar']);\r\n javaaddpath([OCIAPath '/java/TurboRegJava']);\r\n o('#%s(): added Java path at \"%s\" ...', mfilename, OCIAPath, 4, this.verb);\r\n \r\n %% -- #OCIA: create the window and show it\r\n o('Creating window ...', 0, this.verb);\r\n OCIACreateWindow(this); % create the GUI window\r\n pause(0.5);\r\n show(this); % make the GUI window visible\r\n\r\n %% -- #OCIA: process start function\r\n % process the start function\r\n showMessage(this, sprintf('Initializing using start function \"%s\" ...', this.main.startFunctionName), 'yellow');\r\n OCIAGetCallCustomFile(this, 'startFunction', this.main.startFunctionName, 1, { this }, 1); % use default if none provided\r\n\r\nend\r\n\r\n\r\n%% - #delete (destructor)\r\nfunction delete(this)\r\n \r\n o('#delete()', 4, this.verb);\r\n \r\n delete(this.GUI.figH);\r\n \r\nend\r\n\r\n%% - GUI methods\r\n%% -- #show\r\nfunction show(this)\r\n% show - Show the window\r\n%\r\n% show(this)\r\n%\r\n% Makes the OCIA window visible. \r\n \r\n % do nothing if there is no GUI\r\n if ~isGUI(this); return; end;\r\n \r\n o('#show()', 4, this.verb);\r\n \r\n showTic = tic; % for performance timing purposes\r\n set(this.GUI.figH, 'Visible', 'on');\r\n pause(0.1);\r\n o('#show(): done (%.4f sec)', toc(showTic), 4, this.verb);\r\n \r\nend;\r\n\r\n%% -- #hide\r\nfunction hide(this)\r\n% hide - Hides the window\r\n%\r\n% hide(this)\r\n%\r\n% Makes the OCIA window invisible. \r\n\r\n % do nothing if there is no GUI\r\n if ~isGUI(this); return; end;\r\n \r\n o('#hide()', 4, this.verb);\r\n \r\n set(this.GUI.figH, 'Visible', 'off');\r\n \r\nend;\r\n\r\n%% -- #printWindowPosition\r\nfunction printWindowPosition(this)\r\n% printWindowPosition - Prints out the window's position\r\n%\r\n% printWindowPosition(this)\r\n%\r\n% Prints out the window's current position.\r\n\r\n showMessage(this, 'Printing current window''s position:');\r\n showMessage(this, sprintf('this.GUI.pos = [%s];', regexprep(sprintf('%.0f, ', get(this.GUI.figH, 'Position')), ', $', '')));\r\n \r\nend;\r\n\r\n%% -- #isGUI\r\nfunction isGUIBool = isGUI(this)\r\n% isGUI - GUI-mode check\r\n%\r\n% isGUIBool = isGUI(this)\r\n%\r\n% Returns the logical 'isGUIBool' telling whether the current instance of the OCIA ('this') is running in a \r\n% windowed mode or not.\r\n\r\n % if not in no-GUI mode and either in deployed mode or not in a matlab worker (parallel computing)\r\n isGUIBool = ~this.GUI.noGUI && (isdeployed || isempty(javachk('desktop')));\r\n \r\nend;\r\n\r\n%% -- #showMessage\r\nfunction showMessage(this, messageTxt, bgColor)\r\n% showMessage - Display a message\r\n%\r\n% showMessage(this, messageTxt, bgColor)\r\n%\r\n% Displays the message 'messageTxt' (char) in the log bar and in the command window. If the variable 'bgColor' is\r\n% specified, the background of the log bar is set to the color specified either as a color string (\"red\", \"blue\",\r\n% etc.) or as an array of 3 values between 0.0 and 1.0 (RGB). Otherwise the default color (green) is used.\r\n\r\n % print out the message in the command window\r\n o(regexprep(messageTxt, '%', '%%'), 1, this.verb);\r\n \r\n % do nothing if there is no GUI\r\n if ~isGUI(this); return; end;\r\n \r\n % if variable color not specified or neither a string nor a 3-elements RGB array\r\n if ~exist('bgColor', 'var') || (~ischar(bgColor) && numel(bgColor) > 3);\r\n % use the default green color\r\n bgColor = 'green';\r\n end;\r\n \r\n % display the message and set the background\r\n set(this.GUI.handles.logBar, 'String', messageTxt, 'Background', bgColor);\r\n \r\nend;\r\n\r\n%% -- #showWarning\r\nfunction showWarning(this, warnID, warningText, bgColor)\r\n% showMessage - Display a warning\r\n%\r\n% showWarning(this, warnID, warningText, bgColor)\r\n%\r\n% Displays the warning 'warningText' (char) with the ID 'warningID' (char) in the log bar and in the command window.\r\n% If the variable 'bgColor' is specified, the background of the log bar is set to the color specified either as a\r\n% color string (\"red\", \"blue\", etc.) or as an array of 3 values between 0.0 and 1.0 (RGB). Otherwise the default\r\n% color (yellow) is used.\r\n \r\n \r\n % if variable color not specified or neither a string nor a 3-elements RGB array\r\n if ~exist('bgColor', 'var') || (~ischar(bgColor) && numel(bgColor) > 3);\r\n % use the default green color\r\n bgColor = 'yellow';\r\n end;\r\n \r\n % show the warning but without the stack trace\r\n if ~this.main.showWarningStackTraces;\r\n warning off backtrace;\r\n end;\r\n warning(warnID, [strrep(warningText, '\\', '\\\\') ' (' warnID ')']);\r\n if ~this.main.showWarningStackTraces;\r\n warning on backtrace;\r\n end;\r\n \r\n % do nothing if there is no GUI or if warning is disabled\r\n warnState = warning('query', warnID);\r\n if ~isfield(this.GUI, 'noGUI') || ~isfield(this.GUI, 'figH') || ~isfield(this.GUI, 'handles') ...\r\n || ~isfield(this.GUI.handles, 'logBar') || ~isGUI(this) || strcmp(warnState.state, 'off'); return; end;\r\n \r\n % split the warning text at end-of-line characters\r\n warningTextSplit = regexp(warningText, '\\n', 'split');\r\n % only display the first line of the warning text and set the background\r\n set(this.GUI.handles.logBar, 'String', warningTextSplit{1}, 'Background', bgColor); \r\n \r\nend;\r\n\r\n%% -- #getJTable\r\nfunction jTable = getJTable(this, hTable)\r\n% getJTable - Get a Java table\r\n%\r\n% jTable = getJTable(this, hTable)\r\n%\r\n% Returns the Java object 'jTable' associated with the uitable specified by 'hTable'. 'hTable' can be either a\r\n% string ('DWTable', etc.) or as a uitable handle.\r\n\r\n jTable = []; % return empty in case there is a problem\r\n tableName = '';\r\n \r\n % if handle is actually a string, get the appropriate uitable handle first\r\n if ischar(hTable);\r\n \r\n % store the table's name\r\n tableName = hTable;\r\n \r\n % check if the table was not already stored in memory\r\n if isfield(this.GUI, 'jTables') && isfield(this.GUI.jTables, tableName);\r\n jTable = this.GUI.jTables.(tableName);\r\n return;\r\n end;\r\n \r\n % get the appropriate handle for the table\r\n switch tableName;\r\n case 'DWTable';\r\n hTable = this.GUI.handles.dw.table;\r\n case 'BEConfTable';\r\n hTable = this.GUI.handles.be.confTable;\r\n case 'BEETLTable';\r\n hTable = this.GUI.handles.be.ETLTable;\r\n case 'BEExpTable';\r\n hTable = this.GUI.handles.be.expTable;\r\n otherwise;\r\n showWarning(this, 'OCIA:getJTable:UnknownTable', sprintf('Cannot find JTable for \"%s\".', hTable));\r\n return;\r\n end;\r\n end;\r\n \r\n % sometimes the Java-object fetching fails on first attempt, so try a second time\r\n try\r\n % get the actual java table underlying the requested uitable\r\n jTable = findjobj(hTable); jTable = jTable.getComponents();\r\n jTable = jTable(1); jTable = jTable.getComponents();\r\n jTable = jTable(1);\r\n \r\n % try a second time\r\n catch e; %#ok\r\n pause(0.5);\r\n % get the actual java table underlying the requested uitable\r\n jTable = findjobj(hTable); jTable = jTable.getComponents();\r\n jTable = jTable(1); jTable = jTable.getComponents();\r\n jTable = jTable(1);\r\n end;\r\n \r\n % if the table was acced by a name, store the jtable\r\n if ~isempty(tableName);\r\n this.GUI.jTables.(tableName) = jTable;\r\n end;\r\nend;\r\n\r\n\r\n%% -- #getData\r\nfunction data = getData(this, varargin)\r\n% getData - Get data or load status from the DataWatcher's table\r\n%\r\n% data = getData(this, rows, dataType)\r\n% data = getData(this, rows, dataType, subFieldName)\r\n%\r\n% Returns the requested data type from the DataWatcher's table data. \"rows\" should be a double or an array of double and\r\n% \"columns\" a string or a cell-array of string, \"dataType\" a string. \"subFieldName\" should be a string that specifies\r\n% which sub-field ('data', 'loadStatus', 'procState') should be returned.\r\n\r\n% by default or in case of error, return nothing\r\ndata = [];\r\n\r\n% all columns for specified row(s)\r\nif numel(varargin) == 2 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && ischar(varargin{2});\r\n rows = varargin{1};\r\n dataType = varargin{2};\r\n subFieldName = [];\r\n \r\n% specified rows and specified column(s)\r\nelseif numel(varargin) == 3 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && ischar(varargin{2}) && ischar(varargin{3});\r\n rows = varargin{1};\r\n dataType = varargin{2};\r\n subFieldName = varargin{3};\r\n \r\n% otherwise: bad input arguments\r\nelse\r\n rows = [];\r\n dataType = [];\r\n subFieldName = [];\r\nend;\r\n\r\n% if all rows are required to be selected using the 'all' command\r\nif ischar(rows) && strcmp(rows, 'all');\r\n rows = 1 : size(this.dw.table, 1);\r\nend;\r\n\r\n% if the parameters where not all provided or could not be figured out, abort with warning\r\nif isempty(rows) || isempty(dataType);\r\n showWarning(this, 'OCIA:getData:BadInputArguments', 'Bad input arguments for function getData, please read the help.'); \r\n return;\r\nend;\r\n\r\n% get the data structure\r\ndataStruct = getR(this, rows, 'data');\r\n\r\n% if no data structure found, return nothing\r\nif isempty(dataStruct);\r\n return;\r\nend;\r\n\r\n% allocate the data as a cell array\r\ndata = cell(size(dataStruct));\r\n% go through each fetched sub-structure\r\nfor iStruct = 1 : numel(dataStruct); \r\n % if the dataType exists\r\n if isfield(dataStruct{iStruct}, dataType);\r\n % if no sub-field name provided, return the data structures themselves\r\n if isempty(subFieldName);\r\n data{iStruct} = dataStruct{iStruct}.(dataType);\r\n % if the sub-field name is required and exists, return it\r\n elseif isfield(dataStruct{iStruct}.(dataType), subFieldName);\r\n data{iStruct} = dataStruct{iStruct}.(dataType).(subFieldName);\r\n end;\r\n end; \r\nend;\r\n\r\n% do not return a single empty cell, return an empty array instead\r\nif iscell(data) && numel(data) == 1;\r\n data = data{1};\r\nend;\r\n\r\nend\r\n\r\n\r\n%% -- #setData\r\nfunction data = setData(this, varargin)\r\n% getData - Get data or load status from the DataWatcher's table\r\n%\r\n% setData(this, rows, dataType, data)\r\n% setData(this, rows, dataType, subFieldName, data)\r\n%\r\n% Stores the specified data in the DataWatcher's table specified data type. \"rows\" should be a double or an array of double and\r\n% \"columns\" a string or a cell-array of string, \"dataType\" a string. \"subFieldName\" should be a string that specifies\r\n% which sub-field ('data', 'loadStatus', 'procState') should be returned. \"data\" is the data to store, can be a cell\r\n% array.\r\n\r\n% all columns for specified row(s)\r\nif numel(varargin) == 3 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && ischar(varargin{2});\r\n rows = varargin{1};\r\n dataType = varargin{2};\r\n subFieldName = [];\r\n data = varargin{3};\r\n \r\n% specified rows and specified column(s)\r\nelseif numel(varargin) == 4 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && ischar(varargin{2}) && ischar(varargin{3});\r\n rows = varargin{1};\r\n dataType = varargin{2};\r\n subFieldName = varargin{3};\r\n data = varargin{4};\r\n \r\n% otherwise: bad input arguments\r\nelse\r\n rows = [];\r\n dataType = [];\r\n subFieldName = [];\r\n data = [];\r\nend;\r\n\r\n% if all rows are required to be selected using the 'all' command\r\nif ischar(rows) && strcmp(rows, 'all');\r\n rows = 1 : size(tableToUse, 1);\r\nend;\r\n\r\n% if the parameters where not all provided or could not be figured out, abort with warning\r\nif isempty(rows) || isempty(dataType);\r\n showWarning(this, 'OCIA:setData:BadInputArguments', 'Bad input arguments for function setData, please read the help.'); \r\n return;\r\nend;\r\n\r\n% make sure the data's format is a cell-array\r\nif ~iscell(data) || numel(rows) == 1;\r\n data = { data };\r\nend;\r\n\r\n% if the number of rows is too big, abort with warning\r\nif numel(rows) ~= numel(data);\r\n showWarning(this, 'OCIA:setData:NumberOfRowsMismatch', ...\r\n sprintf('Number of rows specified (%02d) is not equal to the size of the input data (%02d).', ...\r\n numel(rows), numel(data))); \r\n return;\r\nend;\r\n\r\n% go through each row\r\nfor iRow = 1 : numel(rows); \r\n % get the data for this row\r\n dataStruct = get(this, rows(iRow), 'data');\r\n % if the dataType exists\r\n if isfield(dataStruct, dataType);\r\n % if no sub-field name provided, store the whole data data type\r\n if isempty(subFieldName);\r\n dataStruct.(dataType) = data{iRow};\r\n % otherwise just set the field\r\n else\r\n dataStruct.(dataType).(subFieldName) = data{iRow};\r\n end;\r\n end; \r\n % set the data for this row\r\n set(this, rows(iRow), 'data', dataStruct); \r\nend;\r\n\r\nend\r\n\r\n\r\n%% -- #get\r\nfunction values = get(this, varargin)\r\n% get - Get values from table\r\n%\r\n% values = get(this, rows)\r\n% values = get(this, columns)\r\n% values = get(this, rows, columns)\r\n% values = get(this, rows, columns, tableToUse)\r\n% values = get(this, rows, columns, tableToUse, tableIDs)\r\n%\r\n% Returns the requested rows/columns from the DataWatcher's table. \"rows\" should be a double or an array of double and\r\n% \"columns\" a string or a cell-array of string. Optionnally, an alternative table \"tableToUse\" can be provided with\r\n% its own columns names \"tableIDs\".\r\n\r\n% get the raw values\r\nvalues = getR(this, varargin{:});\r\n\r\n% do some post-process tasks if there are some cells\r\nif ~isempty(values);\r\n \r\n % filter for the delete tag\r\n charCells = cellfun(@ischar, values);\r\n values(charCells) = regexprep(values(charCells), ['^' this.GUI.dw.deleteTag], '');\r\n values(charCells) = regexprep(values(charCells), '^(<[^>]+>)?(<[^>]+>)?([^<]+)(<[^>]+>)*', '$3');\r\n\r\n % do not return a single cell, return the value it contains instead\r\n if iscell(values) && numel(values) == 1;\r\n values = values{1};\r\n end;\r\n\r\nend;\r\n\r\nend\r\n\r\n%% -- #getR\r\nfunction values = getR(this, varargin)\r\n% getR - Get raw values from table (no post-processing)\r\n%\r\n% values = getR(this, rows)\r\n% values = getR(this, columns)\r\n% values = getR(this, rows, columns)\r\n% values = getR(this, rows, columns, tableToUse)\r\n% values = getR(this, rows, columns, tableToUse, tableIDs)\r\n%\r\n% Returns the requested rows/columns from the DataWatcher's table without any further modification (delete tag removal).\r\n% \"rows\" should be a double or an array of double and \"columns\" a string or a cell-array of string. Optionnally, \r\n% an alternative table \"tableToUse\" can be provided with its own columns names \"tableIDs\".\r\n\r\n% get the default table and its IDs\r\ntableToUse = this.dw.table;\r\ntIDs = this.dw.tableIDs;\r\n\r\n% by default or in case of error, return nothing\r\nvalues = [];\r\n\r\n% all columns for specified row(s)\r\nif numel(varargin) == 1 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all')));\r\n rows = varargin{1};\r\n columns = tIDs;\r\n \r\n% all rows for specified column(s)\r\nelseif numel(varargin) == 1 && (ischar(varargin{1}) || iscell(varargin{1}));\r\n rows = 'all';\r\n columns = varargin{1};\r\n \r\n% specified rows and specified column(s)\r\nelseif numel(varargin) == 2 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && (ischar(varargin{2}) || iscell(varargin{2}));\r\n rows = varargin{1};\r\n columns = varargin{2};\r\n \r\n% specified rows and specified column(s) with a custom table\r\nelseif numel(varargin) == 3 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && (ischar(varargin{2}) || iscell(varargin{2})) ...\r\n && iscell(varargin{3});\r\n rows = varargin{1};\r\n columns = varargin{2};\r\n tableToUse = varargin{3};\r\n \r\n% specified rows and specified column(s) with a custom table and table IDs\r\nelseif numel(varargin) == 4 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && (ischar(varargin{2}) || iscell(varargin{2})) ...\r\n && iscell(varargin{3}) && iscell(varargin{4});\r\n rows = varargin{1};\r\n columns = varargin{2};\r\n tableToUse = varargin{3};\r\n tIDs = varargin{4};\r\n \r\n% otherwise: bad input arguments\r\nelse\r\n rows = [];\r\n columns = []; \r\nend;\r\n\r\n% if all rows are required to be selected using the 'all' command\r\nif ischar(rows) && strcmp(rows, 'all');\r\n rows = 1 : size(tableToUse, 1);\r\nend;\r\n\r\n% make sure the column name(s)'format is a cell-array\r\nif ischar(columns) && ~isempty(columns);\r\n columns = { columns };\r\nend;\r\n\r\n% if no rows selected, abort\r\nif isempty(rows);\r\n return;\r\nend;\r\n\r\n% if the parameters where not all provided or could not be figured out, abort with warning\r\nif isempty(columns) || isempty(tableToUse) || isempty(tIDs);\r\n showWarning(this, 'OCIA:getR:BadInputArguments', 'Bad input arguments for function get, please read the help.'); \r\n return;\r\nend;\r\n\r\n% if the number of rows is too big, abort with warning\r\nif numel(rows) > size(tableToUse, 1);\r\n showWarning(this, 'OCIA:getR:NumberOfRowsExceeded', ...\r\n sprintf('Number of rows specified (%02d) exceeds table''s dimensions (%02d).', numel(rows), size(tableToUse, 1))); \r\n return;\r\nend;\r\n\r\n% if all is good, then fetch the values:\r\n% get the indexes of the columns that are in the IDs, in the same order as requested\r\n[~, b] = ismember(columns(ismember(columns, tIDs)), tIDs);\r\n% fetch the values\r\nvalues = tableToUse(rows, b);\r\n\r\n% post-process the column names\r\nfor iCol = 1 : numel(columns);\r\n switch columns{iCol};\r\n case 'rowID';\r\n rowID = DWGetRowID(this, rows);\r\n if ~iscell(rowID); rowID = { rowID }; end;\r\n values(:, iCol) = rowID;\r\n case 'rowTypeID';\r\n rowTypeID = DWGetRowTypeID(this, rows);\r\n if ~iscell(rowTypeID); rowTypeID = { rowTypeID }; end;\r\n values(:, iCol) = rowTypeID;\r\n otherwise;\r\n % do nothing\r\n end;\r\nend;\r\n\r\nend\r\n\r\n%% -- #set\r\nfunction varargout = set(this, varargin)\r\n% set - set values in table\r\n%\r\n% set(this, rows, values)\r\n% set(this, columns, values)\r\n% set(this, rows, columns, values)\r\n% tableToUse = set(this, rows, columns, values, tableToUse)\r\n% tableToUse = set(this, rows, columns, values, tableToUse, tableIDs)\r\n%\r\n% Stores the specified values in the rows/columns from the DataWatcher's table. \"rows\" should be a double or an \r\n% array of double and \"columns\" a string or a cell-array of string. Optionnally, an alternative table \"tableToUse\" \r\n% can be provided with its own columns names \"tableIDs\", in which case the new table is returned.\r\n\r\n% by default, no output\r\nvarargout = {};\r\n\r\n% get the default table and its IDs\r\ntableToUse = this.dw.table;\r\ntIDs = this.dw.tableIDs;\r\n% set the flag specifying if the table used was from input, by default \"false\"\r\ntableFromInput = false;\r\n\r\n% all columns for specified row(s)\r\nif numel(varargin) == 2 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all')));\r\n rows = varargin{1};\r\n columns = tIDs;\r\n values = varargin{2};\r\n \r\n% all rows for specified column(s)\r\nelseif numel(varargin) == 2 && (ischar(varargin{1}) || iscell(varargin{1}));\r\n rows = 'all';\r\n columns = varargin{1};\r\n values = varargin{2};\r\n \r\n% specified rows and specified column(s)\r\nelseif numel(varargin) == 3 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && (ischar(varargin{2}) || iscell(varargin{2}));\r\n rows = varargin{1};\r\n columns = varargin{2};\r\n values = varargin{3};\r\n \r\n% specified rows and specified column(s) with a custom table\r\nelseif numel(varargin) == 4 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && (ischar(varargin{2}) || iscell(varargin{2})) ...\r\n && iscell(varargin{4});\r\n rows = varargin{1};\r\n columns = varargin{2};\r\n values = varargin{3};\r\n tableToUse = varargin{4};\r\n % set the flag specifying that the table used was from input\r\n tableFromInput = true;\r\n \r\n% specified rows and specified column(s) with a custom table and table IDs\r\nelseif numel(varargin) == 5 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...\r\n && (ischar(varargin{2}) || iscell(varargin{2})) ...\r\n && iscell(varargin{4}) && iscell(varargin{5});\r\n rows = varargin{1};\r\n columns = varargin{2};\r\n values = varargin{3};\r\n tableToUse = varargin{4};\r\n tIDs = varargin{5};\r\n % set the flag specifying that the table used was from input\r\n tableFromInput = true;\r\n \r\n% otherwise: bad input arguments\r\nelse\r\n columns = []; \r\nend;\r\n\r\n% if all rows are required to be selected using the 'all' command\r\nif ischar(rows) && strcmp(rows, 'all');\r\n rows = 1 : size(tableToUse, 1);\r\nend;\r\n\r\n% make sure the column name(s)'format is a cell-array\r\nif ischar(columns) && ~isempty(columns);\r\n columns = { columns };\r\nend;\r\n\r\n% if the parameters where not all provided or could not be figured out, abort with warning\r\nif isempty(rows) || isempty(columns) || isempty(tableToUse) || isempty(tIDs);\r\n showWarning(this, 'OCIA:set:BadInputArguments', 'Bad input arguments for function set, please read the help.'); \r\n return;\r\nend;\r\n\r\n% if the number of rows is too big, abort with warning\r\nif numel(rows) > size(tableToUse, 1);\r\n showWarning(this, 'OCIA:set:NumberOfRowsExceeded', ...\r\n sprintf('Number of rows specified (%02d) exceeds table''s dimensions (%02d).', numel(rows), size(tableToUse, 1))); \r\n return;\r\nend;\r\n\r\n% make sure the values' format is a cell-array\r\nif ~iscell(values);\r\n values = { values };\r\nend;\r\n\r\n% if the size of the values does not match exactly the size of what needs to be replaced, try to extend the values\r\ntableToReplace = tableToUse(rows, ismember(tIDs, columns));\r\nif ~all(size(values) == size(tableToReplace));\r\n \r\n % if inputs are just transposed, transposed them back\r\n if all(size(values') == size(tableToReplace));\r\n values = values';\r\n \r\n % if the values are a vector and can be expanded on one dimension to fit the right size\r\n elseif size(values, 1) == 1 && size(values, 2) == size(tableToReplace, 2);\r\n values = repmat(values, size(tableToReplace, 1), 1);\r\n % if the values are a vector and can be expanded on one dimension to fit the right size\r\n elseif size(values, 1) == 1 && size(values, 2) == size(tableToReplace, 1);\r\n values = repmat(values', 1, size(tableToReplace, 2));\r\n % if the values are a vector and can be expanded on one dimension to fit the right size\r\n elseif size(values, 2) == 1 && size(values, 1) == size(tableToReplace, 1);\r\n values = repmat(values, 1, size(tableToReplace, 1));\r\n % if the values are a vector and can be expanded on one dimension to fit the right size\r\n elseif size(values, 2) == 1 && size(values, 1) == size(tableToReplace, 2);\r\n values = repmat(values', size(tableToReplace, 1), 1);\r\n % if the values are a vector and can be expanded on one dimension to fit the right size\r\n elseif size(values, 2) == 1 && size(values, 1) == 1;\r\n values = repmat(values', size(tableToReplace, 1), size(tableToReplace, 2));\r\n % if nothing can be done, abort\r\n else\r\n showWarning(this, 'OCIA:set:BadSizeInputValues', ...\r\n sprintf('Input values have bad size: provided size: %d x %d, required size: %d x %d.', ...\r\n size(values), size(tableToReplace))); \r\n return;\r\n end;\r\nend;\r\n\r\n% set the values\r\ntableToUse(rows, ismember(tIDs, columns)) = values;\r\n\r\n% if the table comes from input arguments, return it\r\nif tableFromInput;\r\n varargout = { tableToUse };\r\n% otherwise, update the data watcher table\r\nelse\r\n this.dw.table = tableToUse;\r\nend;\r\n\r\nend\r\n\r\n%% - #event handlers\r\n%% -- #keyPressed\r\nfunction keyPressed(this, ~, e)\r\n \r\n% get the current mode\r\ncurrentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};\r\n% get whether a mode change was requested\r\nisChangeMode = 0;\r\n% if ismember('shift', e.Modifier);\r\n% switch e.Key;\r\n% case {'1', '2', '3', '4', '5', '6', '7', '8', '9'};\r\n% if str2double(e.Key) <= size(this.main.modes, 1);\r\n% OCIAChangeMode(this, this.main.modes{str2double(e.Key), 1});\r\n% end;\r\n% isChangeMode = 1;\r\n% end;\r\n% end;\r\n\r\nif ~isChangeMode;\r\n switch currentMode\r\n \r\n %% --- #keyPressed : ROIDrawer\r\n case 'TrialView';\r\n % get current object\r\n currObj = get(this.GUI.figH, 'CurrentObject');\r\n \r\n % check for key presses not while inside a text uicontrol element\r\n if ~isa(currObj, 'matlab.ui.control.UIControl') || ~ismember(get(currObj, 'Style'), { 'edit' });\r\n switch e.Key;\r\n\r\n % print help for shortcuts\r\n case 'h';\r\n msgCellArray = { ...\r\n 'This is the \\bfhelp\\rm for the \\bfshortcuts\\rm of the TrialView mode of OCIA.', ...\r\n 'Following shortcuts can be used:', ...\r\n '\\bf [H] \\rmdisplay this help', ...\r\n '\\bf [up/down arrows] \\rmmove up/down in the file selection', ...\r\n '\\bf [left/right arrows] \\rmmove 1 frame backward or forward', ...\r\n '\\bf [SHIFT] + [left/right arrows] \\rmmove 3 frames backward or forward', ...\r\n '\\bf [space] \\rmadd a movement point', ...\r\n '\\bf [R] \\rmreset GUI', ...\r\n '\\bf [CTRL] + [R] \\rmreset movement points for current trial', ...\r\n '\\bf [SHIFT] + [R] \\rmreset movement points for all trials', ...\r\n '\\bf [L] \\rmload current row/trial', ...\r\n '\\bf [CTRL] + [L] \\rmload parameters and move vectors', ...\r\n '\\bf [SHIFT] + [L] \\rmload ROIs', ...\r\n '\\bf [CTRL] + [S] \\rmsave parameters and move vectors', ...\r\n '\\bf [SHIFT] + [S] \\rmsave ROIs', ...\r\n }';\r\n % display a message box\r\n h = msgbox( msgCellArray, 'Shortcut help for TrialView mode');\r\n \r\n % make sure the box is big enough\r\n boxPos = get(h, 'Position');\r\n set(h, 'Position', boxPos + [-200, -75, 400, 150]);\r\n % make font bigger\r\n hChild = get(h, 'Children');\r\n set(hChild(2), 'Units', 'Normalized', 'Position', [0, 0, 1, 1]);\r\n hText = get(hChild(2), 'Children');\r\n set(hText, 'FontSize', 12, 'Units', 'Normalized', 'Position', [0.01, 0.98, 0], ...\r\n 'FontName', 'Courier', 'VerticalAlignment', 'top', 'String', msgCellArray, ...\r\n 'Interpreter', 'tex');\r\n\r\n % left/right arrow keys => move by one frame back or forward\r\n case { 'leftarrow', 'rightarrow' };\r\n % adjust frame\r\n this.tv.iFrame = this.tv.iFrame + iff(ismember('shift', e.Modifier), 3, 1) ...\r\n * iff(strcmp(e.Key, 'leftarrow'), -1, 1);\r\n % keep frame between boundaries\r\n this.tv.iFrame = min(max(round(this.tv.iFrame), 1), this.tv.params.WFDataSize(3));\r\n % update GUI\r\n OCIA_trialview_changeFrame(this);\r\n\r\n % up/down arrow keys => move within the file selection list\r\n case { 'uparrow', 'downarrow' };\r\n if isfield(this.GUI.handles.tv, 'paramPanElems') ...\r\n && isfield(this.GUI.handles.tv.paramPanElems, 'fileList');\r\n % get selected element and size\r\n selElemIndex = get(this.GUI.handles.tv.paramPanElems.fileList, 'Value');\r\n nElems = numel(get(this.GUI.handles.tv.paramPanElems.fileList, 'String'));\r\n % adjust selection\r\n selElemIndex = selElemIndex + iff(strcmp(e.Key, 'uparrow'), -1, 1);\r\n % keep index between boundaries\r\n selElemIndex = min(max(selElemIndex, 1), nElems);\r\n % update GUI\r\n set(this.GUI.handles.tv.paramPanElems.fileList, 'Value', selElemIndex);\r\n % make sure parameters are updated\r\n TVUpdateParams(this);\r\n end;\r\n \r\n % add a movement point\r\n case 'space';\r\n OCIA_trialview_addMovePoint(this);\r\n \r\n % resets\r\n case 'r';\r\n % reset GUI\r\n if isempty(e.Modifier);\r\n OCIA_startFunction_trialView(this);\r\n \r\n % reset move points\r\n elseif ~isempty(e.Modifier) && all(strcmp(e.Modifier, 'control'));\r\n OCIA_trialview_resetMovePoints(this);\r\n \r\n % reset all move points\r\n elseif ~isempty(e.Modifier) && all(strcmp(e.Modifier, 'shift'));\r\n OCIA_trialview_resetMovePoints(this, 'all');\r\n \r\n end;\r\n \r\n % load\r\n case 'l';\r\n % load row\r\n if isempty(e.Modifier);\r\n OCIA_trialview_loadWideFieldData(this);\r\n \r\n % load params\r\n elseif ~isempty(e.Modifier) && all(strcmp(e.Modifier, 'control'));\r\n OCIA_trialview_loadParams(this);\r\n \r\n % load ROIs\r\n elseif ~isempty(e.Modifier) && all(strcmp(e.Modifier, 'shift'));\r\n OCIA_trialview_loadROIs(this);\r\n \r\n end;\r\n \r\n % save\r\n case 's';\r\n \r\n % save params\r\n if all(strcmp(e.Modifier, 'control'));\r\n OCIA_trialview_saveParams(this);\r\n \r\n % save ROIs\r\n elseif all(strcmp(e.Modifier, 'shift'));\r\n OCIA_trialview_saveROIs(this);\r\n \r\n end;\r\n\r\n end; % switch end\r\n end; % end of check for key presses not while inside a text uicontrol element\r\n \r\n %% --- #keyPressed : ROIDrawer\r\n case 'ROIDrawer';\r\n switch e.Key;\r\n \r\n % arrow keys\r\n case { 'uparrow', 'downarrow', 'leftarrow', 'rightarrow' };\r\n \r\n % move ROIs\r\n if ~ismember('control', e.Modifier) && ~ismember('shift', e.Modifier) ...\r\n && ~ismember('alt', e.Modifier);\r\n RDMoveROIs(this, strrep(e.Key, 'arrow', ''), this.rd.moveROIsStep);\r\n \r\n % rotate ROIs\r\n elseif ismember('control', e.Modifier) && strcmp(e.Key, 'leftarrow');\r\n RDRotateROIs(this, - this.rd.rotateROIsStep);\r\n \r\n % rotate ROIs\r\n elseif ismember('control', e.Modifier) && strcmp(e.Key, 'rightarrow');\r\n RDRotateROIs(this, this.rd.rotateROIsStep);\r\n \r\n % scale ROIs\r\n elseif ismember('shift', e.Modifier) && strcmp(e.Key, 'leftarrow');\r\n RDScaleROIs(this, this.rd.scaleROIsStep, 0);\r\n \r\n % scale ROIs\r\n elseif ismember('shift', e.Modifier) && strcmp(e.Key, 'rightarrow');\r\n RDScaleROIs(this, - this.rd.scaleROIsStep, 0);\r\n \r\n % scale ROIs\r\n elseif ismember('shift', e.Modifier) && strcmp(e.Key, 'uparrow');\r\n RDScaleROIs(this, 0, this.rd.scaleROIsStep);\r\n \r\n % scale ROIs\r\n elseif ismember('shift', e.Modifier) && strcmp(e.Key, 'downarrow');\r\n RDScaleROIs(this, 0, - this.rd.scaleROIsStep);\r\n \r\n % change ROI\r\n elseif ismember('alt', e.Modifier) && strcmp(e.Key, 'downarrow');\r\n currROI = get(this.GUI.handles.rd.selROIsList, 'Value');\r\n if isempty(currROI); currROI = 1; end;\r\n if currROI(1) < numel(get(this.GUI.handles.rd.selROIsList, 'String'));\r\n set(this.GUI.handles.rd.selROIsList, 'Value', currROI(1) + 1);\r\n end;\r\n RDSelROI(this);\r\n \r\n % change ROI \r\n elseif ismember('alt', e.Modifier) && strcmp(e.Key, 'uparrow');\r\n currROI = get(this.GUI.handles.rd.selROIsList, 'Value');\r\n if isempty(currROI);\r\n currROI = numel(get(this.GUI.handles.rd.selROIsList, 'String'));\r\n end;\r\n if currROI(1) > 1;\r\n set(this.GUI.handles.rd.selROIsList, 'Value', currROI(1) - 1);\r\n end;\r\n RDSelROI(this);\r\n end;\r\n \r\n % toggle zoom\r\n case 'z';\r\n RDActivateZoom(this, ~get(this.GUI.handles.rd.zTool, 'Value'));\r\n \r\n % new ROI\r\n case 'n';\r\n RDDrawNewROI(this, [], []);\r\n \r\n \r\n % compare ROISets\r\n case 'c';\r\n \r\n % invert target and reference\r\n if ismember('control', e.Modifier);\r\n selRef = get(this.GUI.handles.rd.refROISetASetter, 'Value');\r\n selTarg = get(this.GUI.handles.rd.refROISetBSetter, 'Value');\r\n set(this.GUI.handles.rd.refROISetASetter, 'Value', selTarg(1));\r\n set(this.GUI.handles.rd.refROISetBSetter, 'Value', selRef(1));\r\n RDCompareROIs(this, 'IDs');\r\n \r\n % ?\r\n elseif ismember('alt', e.Modifier);\r\n compareState = get(this.GUI.handles.rd.refROISet, 'Value');\r\n set(this.GUI.handles.rd.refROISet, 'Value', ~compareState);\r\n RDCompareROIs(this, 'IDs');\r\n \r\n % ?\r\n else\r\n RDCompareROIs(this, 'IDs');\r\n end;\r\n \r\n case 'l';\r\n % load ROIs\r\n if ismember('control', e.Modifier);\r\n RDSaveROIs(this);\r\n \r\n % select last ROIs\r\n else\r\n set(this.GUI.handles.rd.selROIsList, 'Value', numel(get(this.GUI.handles.rd.selROIsList, 'String')));\r\n RDSelROI(this);\r\n end;\r\n \r\n case 'r';\r\n % reload ROIs \r\n if ismember('shift', e.Modifier);\r\n \r\n spotIDs = get(this, 'all', 'spot');\r\n spotIDs(cellfun(@isempty, spotIDs)) = [];\r\n uniqueSpotIDs = unique([ '-'; spotIDs]);\r\n \r\n selectedSpotIDs = get(this, this.dw.selectedTableRows, 'spot');\r\n selectedSpotIDs(cellfun(@isempty, selectedSpotIDs)) = [];\r\n uniqueSelectedSpotIDs = unique(selectedSpotIDs);\r\n \r\n selRef = get(this.GUI.handles.rd.refROISetASetter, 'Value');\r\n selTarg = get(this.GUI.handles.rd.refROISetBSetter, 'Value');\r\n DWProcessWatchFolder(this);\r\n DWExtractNotebookInfo(this);\r\n pause(0.01);\r\n set(this.GUI.handles.dw.filt.spotID, 'String', uniqueSpotIDs, ...\r\n 'Value', find(strcmp(uniqueSelectedSpotIDs{1}, uniqueSpotIDs)));\r\n DWFilterSelectTable(this, 'new');\r\n pause(0.01);\r\n OCIA_dataWatcherProcess_drawROIs(this);\r\n set(this.GUI.handles.rd.tableList, 'Value', 1 : numel(this.rd.selectedTableRows));\r\n RDChangeRow(this, this.GUI.handles.rd.tableList);\r\n set(this.GUI.handles.rd.refROISetASetter, 'Value', selRef);\r\n set(this.GUI.handles.rd.refROISetBSetter, 'Value', selTarg);\r\n set(this.GUI.handles.rd.refROISet, 'Value', 1);\r\n RDCompareROIs(this);\r\n RDLoadROIs(this);\r\n \r\n % rename ROIs\r\n elseif ismember('control', e.Modifier);\r\n RDRenameROI(this);\r\n \r\n \r\n % rename ROIs box\r\n else\r\n set(this.GUI.handles.rd.ROIName, 'String', '');\r\n uicontrol(this.GUI.handles.rd.ROIName);\r\n end;\r\n \r\n case 'space';\r\n\r\n % delete selected ROIs\r\n case { 'd', 'delete' };\r\n RDDeleteROI(this);\r\n % toggle ROI display\r\n case 'i';\r\n RDShowHideROIs(this, 'IDs');\r\n \r\n % toggle ROI display\r\n case 'o';\r\n RDShowHideROIs(this, 'ROIs');\r\n \r\n case 's';\r\n % save ROIs\r\n if ismember('control', e.Modifier);\r\n RDSaveROIs(this);\r\n \r\n % select ROIs box\r\n else\r\n set(this.GUI.handles.rd.selROISetter, 'String', '');\r\n uicontrol(this.GUI.handles.rd.selROISetter);\r\n end;\r\n \r\n case 'a';\r\n % select all ROIs \r\n if ismember('control', e.Modifier);\r\n set(this.GUI.handles.rd.selROIsList, 'Value', ...\r\n 1 : numel(get(this.GUI.handles.rd.selROIsList, 'String')));\r\n RDSelROI(this);\r\n \r\n % image adjustement\r\n else\r\n set(this.GUI.handles.rd.imAdj, 'Value', ~get(this.GUI.handles.rd.imAdj, 'Value'));\r\n RDUpdateImage(this, this.GUI.handles.rd.imAdj);\r\n end;\r\n \r\n % pseudo flat field\r\n case 'p';\r\n set(this.GUI.handles.rd.pseudFF, 'Value', ~get(this.GUI.handles.rd.pseudFF, 'Value'));\r\n RDUpdateImage(this, this.GUI.handles.rd.pseudFF);\r\n \r\n \r\n otherwise;\r\n% showWarning(this, 'OCIA:keyPressed:UnknownKey', sprintf('Unknown key (%s) pressed.', e.Key));\r\n end;\r\n \r\n %% --- #keyPressed : Analyser\r\n case 'Analyser';\r\n switch e.Key;\r\n case {'leftarrow', 'rightarrow'};\r\n if ismember('control', e.Modifier);\r\n ANSelPlot(this, strrep(e.Key, 'arrow', ''));\r\n end;\r\n case {'uparrow', 'downarrow'};\r\n if ismember('control', e.Modifier);\r\n ANSelRuns(this, strrep(e.Key, 'arrow', ''));\r\n end;\r\n case 'z';\r\n if ismember('control', e.Modifier);\r\n ANActivateZoom(this, ~get(this.GUI.handles.an.zTool, 'Value'));\r\n end;\r\n case 'd';\r\n if ismember('control', e.Modifier);\r\n ANActivateDataCursor(this, ~get(this.GUI.handles.an.cTool, 'Value'));\r\n end;\r\n case 's';\r\n % save plot\r\n if ismember('control', e.Modifier);\r\n ANSavePlot(this, []);\r\n end;\r\n otherwise;\r\n% showWarning(this, 'OCIA:keyPressed:UnknownKey', sprintf('Unknown key (%s) pressed.', e.Key));\r\n end;\r\n \r\n %% --- #keyPressed : JointTracker\r\n case 'JointTracker';\r\n % get current object\r\n currObj = get(this.GUI.figH, 'CurrentObject');\r\n \r\n % check for key presses not while inside a text uicontrol element\r\n if ~isa(currObj, 'matlab.ui.control.UIControl') || ~ismember(get(currObj, 'Style'), { 'edit' });\r\n switch e.Key;\r\n\r\n % print help for shortcuts\r\n case 'h';\r\n msgCellArray = { ...\r\n 'This is the \\bfhelp\\rm for the \\bfshortcuts\\rm of the JointTracker mode of OCIA.', ...\r\n 'Following shortcuts can be used:', ...\r\n '\\bf [H] \\rmDisplay this help', ...\r\n '-------------------------------------------------------------------------------------------', ...\r\n '\\bf [A / D] \\rmPrevious / next frame', ...\r\n '\\bf [left / right arrows] \\rmPrevious / next frame', ...\r\n '\\bf [SHIFT] + [A / D] \\rmFirst / last frame', ...\r\n '\\bf [SHIFT] + [left / right arrows] \\rmFirst / last frame', ...\r\n '-------------------------------------------------------------------------------------------', ...\r\n '\\bf [C] \\rmChange the cursor display (dot <-> pointer)', ...\r\n '-------------------------------------------------------------------------------------------', ...\r\n '\\bf [W / S] \\rmChange joint type (manual <-> auto)', ...\r\n '\\bf [up / down arrow] \\rmChange joint type (manual <-> auto)', ...\r\n '-------------------------------------------------------------------------------------------', ...\r\n '\\bf [F] \\rmStart / stop auto-track', ...\r\n '\\bf [V] \\rmStart / stop manual-track', ...\r\n '\\bf [M] \\rmStart / stop manual-track', ...\r\n }';\r\n % display a message box\r\n h = msgbox(msgCellArray);\r\n \r\n % make sure the box is big enough\r\n boxPos = get(h, 'Position');\r\n set(h, 'Position', boxPos + [-200, -75, 400, 150]);\r\n % make font bigger\r\n hChild = get(h, 'Children');\r\n set(hChild(2), 'Units', 'Normalized', 'Position', [0, 0, 1, 1]);\r\n hText = get(hChild(2), 'Children');\r\n set(hText, 'FontSize', 12, 'Units', 'Normalized', 'Position', [0.01, 0.98, 0], ...\r\n 'FontName', 'Courier', 'VerticalAlignment', 'top', 'String', msgCellArray, ...\r\n 'Interpreter', 'tex');\r\n case 'c';\r\n JTSwapCursor(this);\r\n case { 'a', 'leftarrow' };\r\n if ismember('shift', e.Modifier);\r\n set(this.GUI.handles.jt.frameSetter, 'Value', 1);\r\n else\r\n set(this.GUI.handles.jt.frameSetter, 'Value', max(this.GUI.jt.iFrame - 1, 1));\r\n end;\r\n case { 'd', 'rightarrow' };\r\n if ismember('shift', e.Modifier);\r\n if get(this.GUI.handles.jt.autoTrack, 'Value');\r\n JTProcess(this, 'all');\r\n else\r\n set(this.GUI.handles.jt.frameSetter, 'Value', this.jt.nFrames);\r\n end;\r\n else\r\n set(this.GUI.handles.jt.frameSetter, 'Value', min(this.GUI.jt.iFrame + 1, this.jt.nFrames));\r\n end;\r\n \r\n case {'w', 's', 'uparrow', 'downarrow', };\r\n addValue = 1; if strcmp(e.Key, 's') || strcmp(e.Key, 'downarrow'); addValue = -1; end;\r\n newValue = min(max(this.GUI.jt.iJointType + addValue, 1), this.jt.nJointTypes);\r\n if newValue ~= get(this.GUI.handles.jt.jointTypeSelSetter, 'Value');\r\n set(this.GUI.handles.jt.jointTypeSelSetter, 'Value', newValue);\r\n JTChangeJointOrJointType(this, this.GUI.handles.jt.jointTypeSelSetter);\r\n end;\r\n case 'f';\r\n set(this.GUI.handles.jt.autoTrack, 'Value', ~get(this.GUI.handles.jt.autoTrack, 'Value'));\r\n JTProcess(this, 'autoTrackChanged');\r\n case {'m', 'v'};\r\n set(this.GUI.handles.jt.manuTrack, 'Value', ~get(this.GUI.handles.jt.manuTrack, 'Value'));\r\n JTManualTrackStart(this);\r\n case 'space';\r\n% set(this.GUI.handles.jt.viewOpts.preProc, 'Value', ...\r\n% ~get(this.GUI.handles.jt.viewOpts.preProc, 'Value'));\r\n% JTUpdateGUI(this, this.GUI.handles.jt.viewOpts.preProc);\r\n otherwise;\r\n% showWarning(this, 'OCIA:keyPressed:UnknownKey', sprintf('Unknown key (%s) pressed.', e.Key));\r\n end;\r\n end; % end of check for key presses not while inside a text uicontrol element\r\n \r\n %% --- #keyPressed : Discriminator\r\n case 'Discriminator';\r\n switch e.Key;\r\n \r\n % adjust response rate threshold\r\n case 'leftarrow';\r\n this.di.respRateThresh = max(min(this.di.respRateThresh - 0.5, 9.5), 1);\r\n showMessage(this, sprintf('Reponse threshold: %.1f.', this.di.respRateThresh), 'yellow');\r\n \r\n % adjust response rate threshold \r\n case 'rightarrow';\r\n this.di.respRateThresh = max(min(this.di.respRateThresh + 0.5, 9.5), 1);\r\n showMessage(this, sprintf('Reponse threshold: %.1f.', this.di.respRateThresh), 'yellow');\r\n \r\n % zoom level of activity\r\n case 'uparrow';\r\n this.GUI.di.zoomLevel = max(min(this.GUI.di.zoomLevel + this.GUI.di.zoomLevel * 0.1, 10), 1);\r\n showMessage(this, sprintf('Zoom level: %.1f.', this.GUI.di.zoomLevel), 'yellow');\r\n \r\n % zoom level of activity\r\n case 'downarrow';\r\n this.GUI.di.zoomLevel = max(min(this.GUI.di.zoomLevel - this.GUI.di.zoomLevel * 0.1, 10), 1);\r\n showMessage(this, sprintf('Zoom level: %.1f.', this.GUI.di.zoomLevel), 'yellow');\r\n \r\n % start/stop camera\r\n case 'c';\r\n DIStartStopCamera(this, 'toggle');\r\n showMessage(this, sprintf('Camera running: %s', get(this.GUI.di.camHandle, 'Running')), 'yellow');\r\n \r\n % start/stop activity\r\n case 'a';\r\n this.GUI.di.activityRunning = ~this.GUI.di.activityRunning;\r\n if this.GUI.di.activityRunning;\r\n this.GUI.di.actiMovieIndex = this.GUI.di.actiMovieIndex + 1;\r\n if this.GUI.di.actiMovieIndex > numel(this.GUI.di.actiMovies); this.GUI.di.actiMovieIndex = 1; end;\r\n end;\r\n showMessage(this, sprintf('Activity movie: %s', iff(this.GUI.di.activityRunning, 'on', 'off')), 'yellow');\r\n \r\n % lock mouse\r\n case 'l';\r\n this.di.lockMouse = ~this.di.lockMouse;\r\n showMessage(this, sprintf('Locking mouse: %s', iff(this.di.lockMouse, 'on', 'off')), 'yellow');\r\n \r\n % trial phases:\r\n % reset\r\n case '0';\r\n this.di.iTrial = 0;\r\n this.di.iStimMat = randi(10);\r\n this.di.targetStim = randi(2);\r\n showMessage(this, sprintf('Reset trials, iTrial: %d, iStimMat: %d, target stimulus: %d.', ...\r\n this.di.iTrial, this.di.iStimMat, this.di.targetStim), 'yellow');\r\n % new trial\r\n case '1';\r\n set(this.GUI.handles.di.messBox, 'String', 'Trial start ...', 'Background', 'yellow');\r\n set(this.GUI.handles.di.messBoxBack, 'Background', 'yellow');\r\n this.di.iTrial = this.di.iTrial + 1;\r\n showMessage(this, sprintf('Current trial: %d.', this.di.iTrial), 'yellow');\r\n % present stimulus\r\n case '2';\r\n set(this.GUI.handles.di.messBox, 'String', 'Stimulus ...', 'Background', 'yellow');\r\n set(this.GUI.handles.di.messBoxBack, 'Background', 'yellow');\r\n stimNum = this.di.stimMatrix(this.di.iTrial, this.di.iStimMat);\r\n isTarget = stimNum == this.di.targetStim;\r\n showMessage(this, sprintf('Stimulus index for trial %d: %d, target: %d.', this.di.iTrial, stimNum, isTarget), 'yellow');\r\n % get decision\r\n case '3';\r\n this.di.waitingForResp = true;\r\n this.di.waitingStartTime = nowUNIX;\r\n this.di.resp = false;\r\n set(this.GUI.handles.di.messBox, 'String', 'Decision ...', 'Background', 'yellow');\r\n set(this.GUI.handles.di.messBoxBack, 'Background', 'yellow');\r\n stimNum = this.di.stimMatrix(this.di.iTrial, this.di.iStimMat);\r\n isTarget = stimNum == this.di.targetStim;\r\n showMessage(this, sprintf('Trial %d: stimulus %d, target: %d - waiting for decision ...', this.di.iTrial, stimNum, isTarget), 'yellow');\r\n % reward\r\n case '4';\r\n this.di.waitingForResp = false;\r\n set(this.GUI.handles.di.messBox, 'String', 'Reward !', 'Background', 'green');\r\n set(this.GUI.handles.di.messBoxBack, 'Background', 'green');\r\n showMessage(this, 'Reward', 'yellow');\r\n % punishment\r\n case '5';\r\n this.di.waitingForResp = false;\r\n set(this.GUI.handles.di.messBox, 'String', 'Punishment !', 'Background', 'red');\r\n set(this.GUI.handles.di.messBoxBack, 'Background', 'red');\r\n showMessage(this, 'Punishment', 'yellow');\r\n \r\n end;\r\n end;\r\nend;\r\n\r\nend;\r\n\r\n%% -- #mouseDown\r\nfunction mouseDown(this, ~, ~)\r\n\r\n currentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};\r\n \r\n switch currentMode;\r\n \r\n case 'TrialView';\r\n \r\n % get selection type (mouse button)\r\n selType = get(this.GUI.figH, 'SelectionType');\r\n % get clicked object\r\n clickedObj = get(this.GUI.figH, 'CurrentObject');\r\n if isa(clickedObj, 'matlab.graphics.axis.Axes') || ...\r\n (~isa(get(clickedObj, 'Parent'), 'matlab.graphics.primitive.Group') ...\r\n && (isa(clickedObj, 'matlab.graphics.chart.primitive.Line') ...\r\n || isa(clickedObj, 'matlab.graphics.primitive.Patch') ...\r\n || isa(clickedObj, 'matlab.graphics.primitive.Text')));\r\n \r\n % left click\r\n if strcmp(selType, 'normal');\r\n this.GUI.tv.mouseDownOnAxe = true;\r\n end;\r\n \r\n end;\r\n \r\n case 'JointTracker';\r\n \r\n % make sure the click is within the axe image and not during a ROI drawing\r\n pos = get(this.GUI.handles.jt.axe, 'CurrentPoint');\r\n pos = pos(1, 1 : 2);\r\n XLim = get(this.GUI.handles.jt.axe, 'XLim');\r\n YLim = get(this.GUI.handles.jt.axe, 'YLim');\r\n if this.GUI.jt.selectingROI || any(pos < 0) || pos(1) > XLim(2) || pos(2) > YLim(2);\r\n return;\r\n end;\r\n \r\n if isempty(this.GUI.jt.placeJointIndex) && isempty(this.GUI.jt.moveJointIndex);\r\n selectionType = get(this.GUI.figH, 'SelectionType');\r\n JTJointClickStart(this, strcmp(selectionType, 'extend'));\r\n end;\r\n end;\r\n\r\nend;\r\n\r\n%% -- #mouseUp\r\nfunction mouseUp(this, h, e)\r\n\r\n currentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};\r\n \r\n switch currentMode;\r\n \r\n case 'TrialView';\r\n \r\n % get selection type (mouse button)\r\n selType = get(this.GUI.figH, 'SelectionType');\r\n % get clicked object\r\n clickedObj = get(this.GUI.figH, 'CurrentObject');\r\n if isa(clickedObj, 'matlab.graphics.axis.Axes') || ...\r\n (~isa(get(clickedObj, 'Parent'), 'matlab.graphics.primitive.Group') ...\r\n && (isa(clickedObj, 'matlab.graphics.chart.primitive.Line') ...\r\n || isa(clickedObj, 'matlab.graphics.primitive.Patch') ...\r\n || isa(clickedObj, 'matlab.graphics.primitive.Text')));\r\n \r\n % left click\r\n if strcmp(selType, 'normal');\r\n this.GUI.tv.mouseDownOnAxe = false;\r\n \r\n % right click\r\n elseif strcmp(selType, 'alt');\r\n OCIA_trialview_addMovePoint(this);\r\n\r\n end;\r\n \r\n elseif isa(clickedObj, 'matlab.graphics.primitive.Image') && clickedObj == this.GUI.handles.tv.wf.img ...\r\n && ~this.GUI.tv.mouseDownOnWFImg;\r\n OCIA_trialview_drawROI(this);\r\n \r\n elseif isa(clickedObj, 'matlab.graphics.primitive.Image') && clickedObj == this.GUI.handles.tv.behav.img ...\r\n && ~this.GUI.tv.mouseDownOnWFImg;\r\n OCIA_trialview_drawROI(this, this.GUI.handles.tv.behav.axe);\r\n \r\n end;\r\n \r\n case 'ROIDrawer';\r\n \r\n RDUpdateGUI(this, h, e);\r\n \r\n case 'Behavior';\r\n \r\n BEChangePiezoThresh(this, 'mouseAdjust', []);\r\n \r\n case 'JointTracker';\r\n \r\n % make sure the click is within the axe image and not during a ROI drawing\r\n pos = get(this.GUI.handles.jt.axe, 'CurrentPoint');\r\n pos = pos(1, 1 : 2);\r\n XLim = get(this.GUI.handles.jt.axe, 'XLim');\r\n YLim = get(this.GUI.handles.jt.axe, 'YLim');\r\n if this.GUI.jt.selectingROI || any(pos < 0) || pos(1) > XLim(2) || pos(2) > YLim(2);\r\n return;\r\n end;\r\n \r\n % process the click event\r\n JTImClick(this, h, e);\r\n \r\n % reset the joint tracking/moving settings\r\n this.GUI.jt.placeJointIndex = [];\r\n this.GUI.jt.moveJointIndex = [];\r\n this.GUI.jt.startFrame = [];\r\n this.GUI.jt.endFrame = [];\r\n this.GUI.jt.startTime = [];\r\n\r\n % remove manual tracking\r\n set(this.GUI.handles.jt.manuTrack, 'Value', 0);\r\n \r\n case 'Discriminator';\r\n \r\n this.di.nResps = this.di.nResps + 0.75;\r\n end;\r\n\r\nend;\r\n\r\n%% -- #mouseMoved\r\nfunction mouseMoved(this, ~, e)\r\n\r\n currentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};\r\n \r\n switch currentMode;\r\n \r\n case 'TrialView';\r\n \r\n if this.GUI.tv.mouseDownOnAxe;\r\n % get clicked object\r\n clickedObj = get(this.GUI.figH, 'CurrentObject');\r\n if isa(clickedObj, 'matlab.graphics.axis.Axes') || ...\r\n (~isa(get(clickedObj, 'Parent'), 'matlab.graphics.primitive.Group') ...\r\n && (isa(clickedObj, 'matlab.graphics.chart.primitive.Line') ...\r\n || isa(clickedObj, 'matlab.graphics.primitive.Patch') ...\r\n || isa(clickedObj, 'matlab.graphics.primitive.Text')));\r\n OCIA_trialview_changeFrame(this, clickedObj, e);\r\n end;\r\n end;\r\n \r\n case 'JointTracker';\r\n \r\n coords = get(this.GUI.handles.jt.axe, 'CurrentPoint');\r\n coords = round(coords(1, 1 : 2));\r\n if all(coords > 0) && coords(1) < size(this.GUI.jt.img, 2) && coords(2) < size(this.GUI.jt.img, 1);\r\n this.GUI.jt.mouseCoords = coords;\r\n % update the frame label\r\n currTimeTotSec = this.GUI.jt.iFrame / this.jt.frameRate;\r\n currTimeMin = floor(currTimeTotSec / 60);\r\n currTimeSec = floor(currTimeTotSec - currTimeMin * 60);\r\n currTimeMSec = floor((currTimeTotSec - currTimeMin * 60 - currTimeSec) * 1000);\r\n set(this.GUI.handles.jt.frameLabel, 'String', sprintf('F %03d\\nT %02d:%02d.%03d\\nM %04d %04d', ...\r\n this.GUI.jt.iFrame, currTimeMin, currTimeSec, currTimeMSec, coords));\r\n end;\r\n end;\r\n\r\nend;\r\n\r\n%% -- #windowResized\r\nfunction windowResized(this, ~, ~)\r\n \r\n % if no GUI, skip the resizing\r\n if ~isGUI(this); return; end;\r\n\r\n % store old position\r\n oldPos = this.GUI.pos; \r\n % update to new position\r\n this.GUI.pos = get(this.GUI.figH, 'Position'); \r\n % calculate ratios\r\n widthRatio = oldPos(3) / this.GUI.pos(3);\r\n% heightRatio = oldPos(4) / this.GUI.pos(4);\r\n \r\n % update the font size and the columns widths of the DataWatcher's table\r\n columnWidths = get(this.GUI.handles.dw.table, 'ColumnWidth');\r\n columnWidths = num2cell(cellfun(@(w)round(w / widthRatio), columnWidths));\r\n set(this.GUI.handles.dw.table, 'ColumnWidth', columnWidths, 'FontSize', max(min(this.GUI.pos(3) / 170, 22), 8));\r\n \r\nend;\r\n\r\n\r\n\r\n\r\n\r\nend % end methods\r\n\r\n\r\nend\r\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "RDSelROI.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/@OCIA/RDSelROI.m", "size": 3644, "source_encoding": "utf_8", "md5": "0361eb322847a59f38e2c2b6c30702ff", "text": "%% #OCIA:RD:RDSelROI\nfunction RDSelROI(this, varargin)\n\no('#RDSelROI()', 4, this.verb);\n\nh = []; % no handle by default\n% get the handle if there is any\nif nargin > 1; h = varargin{1}; end;\n\n% if change was requested by a number, overwrite the selection\nif ~isempty(h) && isnumeric(h) && ~ishandle(h);\n selROIs = h;\n% if change was requested by a string or cell-array of strings, overwrite the selection\nelseif ~isempty(h) && (ischar(h) || iscellstr(h));\n if ischar(h); h = { h }; end;\n if strcmp(get(this.GUI.figH, 'SelectionType'), 'extend');\n selROIs = [str2double(h), RDGetSelectedROIs(this, this.GUI.handles.rd.selROIsList)];\n else\n selROIs = str2double(h);\n end;\n selROIs(isnan(selROIs)) = [];\n% if a clearing of the selection was requested, empty selection \nelseif ~isempty(h) && h == this.GUI.handles.rd.selROISetterClear;\n selROIs = [];\n% if selection was requested by the edit field\nelseif ~isempty(h) && ((h == this.GUI.handles.rd.selROI) || (h == this.GUI.handles.rd.selROISetter));\n selROIs = RDGetSelectedROIs(this, h);\n% otherwise use selection with the list\nelse\n selROIs = RDGetSelectedROIs(this, this.GUI.handles.rd.selROIsList);\nend;\n\no('#RDSelROI(): h: %d, selectedROIs: %s .', h, num2str(selROIs), 3, this.verb);\n\n% update the color of the ROIs\nfor iROI = 1 : this.rd.nROIs;\n if ismember(iROI, selROIs);\n this.rd.ROIs{iROI, 1}.setColor('red');\n if ishandle(this.rd.ROIs{iROI, 5}) && strcmp(get(this.rd.ROIs{iROI, 1}, 'Visible'), 'off');\n set(this.rd.ROIs{iROI, 5}, 'Color', 'blue');\n end;\n else\n this.rd.ROIs{iROI, 1}.setColor('blue');\n if ishandle(this.rd.ROIs{iROI, 5}) && strcmp(get(this.rd.ROIs{iROI, 1}, 'Visible'), 'off');\n set(this.rd.ROIs{iROI, 5}, 'Color', 'red');\n end;\n end;\nend;\n\n% if no ROIs, no selection text\nif isempty(selROIs);\n selROIsText = '';\n% otherwise create the selection text\nelse\n % start with the first number\n selROIsText = sprintf('%s', this.rd.ROIs{selROIs(1), 2});\n inRange = false; % determines if we are currently in a range display (1 : ...)\n for iSel = 2 : numel(selROIs); % go through all numbers starting from the second\n \n % get the ROI numbers\n currROI = this.rd.ROIs{selROIs(iSel), 2};\n prevROI = this.rd.ROIs{selROIs(iSel - 1), 2};\n \n % if we are not in range and next number is just previous + 1, then start a range display\n if str2double(currROI) - 1 == str2double(prevROI) && ~inRange;\n selROIsText = sprintf('%s:', selROIsText);\n inRange = true;\n % if we are in range and next number is just previous + 1, do not display number and continue range\n elseif str2double(currROI) - 1 == str2double(prevROI) && inRange;\n % skip number\n % if next number is not just previous + 1, then eventually finish range display and display number\n else\n \t% if we were in range, finish range display of last number\n if inRange;\n selROIsText = sprintf('%s%s', selROIsText, prevROI);\n end\n % display next number\n selROIsText = sprintf('%s,%s', selROIsText, currROI);\n inRange = false;\n end;\n end;\n \n % if we are still in range display, it means last number could not be displayed, so display it\n if inRange;\n selROIsText = sprintf('%s%s', selROIsText, currROI);\n end;\n \n \nend;\n\n% re-update the selection\nset(this.GUI.handles.rd.selROISetter, 'String', strrep(selROIsText, '00', ''));\nset(this.GUI.handles.rd.selROIsList, 'Value', selROIs);\n\nend"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_genStimVect_fromAnalogInWideField.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromAnalogInWideField.m", "size": 15569, "source_encoding": "utf_8", "md5": "db650f76208ac994600bd0dc7f54800a", "text": "%% #OCIA:AN:OCIA_genStimVect_fromAnalogInWideField\nfunction [isValid, unvalidReason] = OCIA_genStimVect_fromAnalogInWideField(this, iDWRow, varargin)\n\n% get whether to do plots or not\nif nargin > 2; doPlotsTrig = varargin{1}; doPlotsMicr = varargin{1}; doPlotsSummary = varargin{1}; %#ok\nelseif nargin > 3; doPlotsTrig = varargin{1}; doPlotsMicr = varargin{2}; doPlotsSummary = 0; %#ok\nelse doPlotsTrig = 0; doPlotsMicr = 0; doPlotsSummary = 0; %#ok\nend;\n\nrowID = DWGetRowID(this, iDWRow); % get the row ID \nisValid = true; % by default, the row is valid\nunvalidReason = ''; % by default no reason\n\no('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);\n\n% get the behavior data for this row\nbehavData = getData(this, iDWRow, 'wfTrBehav', 'data');\n\n% if no behavior data is found, abort\nif isempty(behavData);\n isValid = false; % set the validity flag to false\n % store the reason why this row was not valid\n unvalidReason = sprintf('cannot find associated behavior data (behavior data unavailable in row %03d)', iDWRow);\n return; % abort processing of this row\nend;\n\niTrial = str2double(get(this, iDWRow, 'runNum')); % get the trial number\n% if no behavior row found using the behavior ID, abort\nif isempty(iTrial) || isnan(iTrial) || iTrial <= 0;\n isValid = false; % set the validity flag to false\n % store the reason why this row was not valid\n unvalidReason = sprintf('bad trial number (\"%s\" => %d\")', get(this, iDWRow, 'runNum'), iTrial);\n return; % abort processing of this row\nend;\n\n% fix missing fields\nif isfield(behavData, 'nTones');\n % if more than one element for nTones, there must be one element per trial\n if numel(behavData.nTones) > 1; nTones = behavData.nTones(iTrial);\n % otherwise there is only one constant number of tones\n else nTones = behavData.nTones;\n end;\n% if no field, assume there is only one tone\nelse nTones = 1;\nend;\n\n%% init the stim vector\nimgDim = str2dim(get(this, iDWRow, 'dim'));\n% compensate for the skipped frames\nif numel(imgDim) < 3; nFramesImg = 0;\nelse nFramesImg = imgDim(3);\nend;\n% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)\nstimVect = zeros(1, nFramesImg);\n% string storing the stimulus types for this row\nstimTypes = '';\n% cell-array storing the relevant time points for the imaging\nstimTimeFrames = {};\n% initialize variables\nimgFrameRate = 20;\n% calculate the number of bits to encode \nnMaxStimTimes = 10; nBitsToUseForStimTimes = ceil(log2(nMaxStimTimes));\n% assign bits to difference encodings\niBitTime = 1 : nBitsToUseForStimTimes; iBitCloud = iBitTime(end) + (1 : 2); iBitTarg = iBitCloud(end) + (1 : 2);\niBitResp = iBitTarg(end) + (1 : 2); iBitCorr = iBitResp(end) + (1 : 2);\n\n%% delay analysis (trig)\ntrigData = behavData.analogInData(strcmp(behavData.analogInNames, 'trig'), :); % extract the triger's trace\nnormThresh = 3 * std(trigData(1 : 100)); % take the first frames for normalization threshold\ntrigData(abs(trigData) < normThresh) = 0; % normalize to remove the noise of parts when there is no trigger\ntrigTop = find(trigData > 0); % find all the peaks\n\n% get the trigger delay\nanInSampRate = behavData.analogInSampRate;\ntrigInd = trigTop(1);\ntrigDelay = trigInd / anInSampRate;\n\n% store the extracted number: analog input sampling rate, trigger delay\nbehavData.behavSampRate = anInSampRate;\nbehavData.trigDelay = trigDelay;\n\n% if doPlotsTrig > 0; % if requested, plot a figure illustrating the extraction procedure\n% figure('Name', sprintf('%s_trig', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');\n% plot(trigData, 'k');\n% hold on;\n% scatter(trigTop(1), trigData(trigTop(1)), 200, 'b');\n% title(sprintf('trigDelay: %.3f', trigDelay));\n% end;\n\n%% sound start (stimulus time) analysis (micr)\n\n% get the number of samples\nnSamples = size(behavData.analogInData, 2);\n\n% extract the stimulus sound time and duration from the recorded sound\nmicr = linScale(abs(behavData.analogInData(strcmp(behavData.analogInNames, 'micr'), :)));\n% get a range for the begining of the signal\nbegRange = round(nSamples * 0.01 : nSamples * 0.1);\n% incrementally search for the right threshold\nnSoundsDiff = 1; soundYThresh = 0; soundThreshFactor = 5; soundThreshFactorStep = 5; nLoops = 0; %#ok\nwhile nSoundsDiff && soundThreshFactor < 55;\n % get a threshold for the sound onset\n soundThreshFactor = soundThreshFactor + soundThreshFactorStep;\n soundYThresh = soundThreshFactor * std(micr(begRange));\n % get the samples that exceeds the threshold, adding the first sample to catch the start of the first sound\n upSamples = [0 find(micr > soundYThresh)];\n % get the derivative of the upSamples, drops in the sample indexes indicate interruption of upSamples,\n % which means that there is a sound start\n upSamplesDiff = diff(upSamples);\n % use the ISI to find peaks. If no ISI, use 0.5 second\n ISI = 0.5;\n if isfield(behavData, 'ISI') && behavData.ISI > 0;\n ISI = behavData.ISI;\n end;\n % difference between detected upSample derivative's peaks must be at least half of the ISI\n minISI = ISI * 0.5 * anInSampRate;\n % get the index of the peaks where the derivative exceeds the ISI threshold and increment by one to get\n % the sound start index\n soundStartInds = upSamples(find(upSamplesDiff >= minISI) + 1);\n\n if ~isempty(soundStartInds);\n % calculate the sound start time\n soundStartTimes = soundStartInds / anInSampRate;\n else\n soundStartTimes = [];\n end;\n\n % check whether there is a big frame difference between the imaging and the behavior recording\n nSoundsDiff = abs(nTones - numel(soundStartTimes));\n nLoops = nLoops + 1;\n\nend;\n\n% if there is a mismatch in the number of sounds found and more sounds were found, show a warning\nif nSoundsDiff && ~isempty(soundStartTimes) && numel(soundStartTimes) >= nTones;\n showWarning(this, sprintf('OCIA:%s:MissingStim', mfilename()), ...\n sprintf(['Problem with number of stimuli found for %s (%d)! Number of stim detected in recorded ', ...\n 'data: %d, expected number of stim: %d. Taking only the first %d stim(s).'], rowID, iDWRow, ...\n numel(soundStartTimes), nTones, nTones));\n soundStartTimes = soundStartTimes(1 : nTones);\n doPlotsMicr = doPlotsMicr + 1; %#ok\n\n% if there is a mismatch in the number of sounds found and less sounds were found, show a warning\nelseif nSoundsDiff;\n showWarning(this, sprintf('OCIA:%s:MissingStim', mfilename()), ...\n sprintf(['Problem with number of stimuli found for %s (%d)! Number of stim detected in recorded ', ...\n 'data: %d, expected number of stim: %d.'], rowID, iDWRow, numel(soundStartTimes), nTones));\n doPlotsMicr = doPlotsMicr + 1; %#ok\nend;\n\n% get the stimulus time, including the imaging start delay\nsoundStartTimesImgReference = soundStartTimes - trigDelay;\nsoundStartIndexesImgReference = round(soundStartTimesImgReference * imgFrameRate); % get the stimulus index\n% remove stim start times that are too early\nif any(soundStartIndexesImgReference < 0);\n nRemStims = sum(soundStartIndexesImgReference < 0);\n soundStartIndexesImgReference(soundStartIndexesImgReference <= 0) = [];\n showWarning(this, sprintf('OCIA:%s:EarlyStim', mfilename()), ...\n sprintf('Removed %d early stimuli found for %s (%d)!', nRemStims, rowID, iDWRow));\nend;\n\n% store the starting time\nbehavData.soundStartTime = soundStartTimes;\n\n% encode the sound end stimulus\nsoundEndTimesImgReference = soundStartTimesImgReference + behavData.stimDur;\nsoundEndIndexesImgReference = round(soundEndTimesImgReference * imgFrameRate); % get the stimulus index\n\n\n% if doPlotsMicr > 0; % if requested, plot a figure illustrating the extraction procedure\n% figure('Name', sprintf('%s_micr', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');\n% rectangle('Position', [begRange(1) 0 begRange(end) - begRange(1) soundYThresh * 1.1], ...\n% 'FaceColor', [0.8 1 0.8], 'EdgeColor', [0.8 1 0.8]);\n% hold on;\n% plot(micr, 'k');\n% yLims = get(gca, 'YLim'); xLims = get(gca, 'XLim');\n% plot(upSamples(1 : end - 1) - 0.5, (upSamplesDiff / max(upSamplesDiff)) * max(micr) * 0.9, 'r');\n% plot(repmat(soundStartInds, 2, 1), repmat(yLims, numel(soundStartInds), 1)', 'r:');\n% plot(xLims, repmat(soundYThresh, 2, 1), 'g:');\n% title(sprintf('stimYThresh: %.5f, stimStartTimes: %s', soundYThresh, sprintf(' %.2fs', soundStartTimes)));\n% end;\n\n%% other stim times based one behavior recording\n% get the light time, including the imaging start delay\nif isfield(behavData, 'trialStartCue') && ~isnan(behavData.trialStartCue);\n trialStartCueImgReference = behavData.soundStartTime - trigDelay + (behavData.trialStartCue - behavData.soundTime);\n stimStartIndexesImgReference = round(trialStartCueImgReference * imgFrameRate); % get the stimulus index\n if stimStartIndexesImgReference <= nFramesImg;\n stimTimeFrames{end + 1} = stimStartIndexesImgReference;\n end;\nend;\n\n% add the sound stimulus frames\nstimTimeFrames{end + 1} = soundStartIndexesImgReference;\nstimTimeFrames{end + 1} = soundEndIndexesImgReference;\n\n% REMOVED BECAUSE NOT ACCURATE\n% get the response time, including the imaging start delay\n% if isfield(behavData, 'respTime') && ~isnan(behavData.respTime);\n% respTimeImgReference = behavData.soundStartTime - trigDelay + (behavData.respTime - behavData.soundTime);\n% stimStartIndexesImgReference = round(respTimeImgReference * imgFrameRate); % get the stimulus index\n% if stimStartIndexesImgReference <= nFramesImg;\n% stimTimeFrames{end + 1} = stimStartIndexesImgReference;\n% end;\n% end;\n\n% get the response window light cue time, including the imaging start delay\nif isfield(behavData, 'lightTime') && ~isnan(behavData.lightTime);\n lightCueTimeImgReference = behavData.soundStartTime - trigDelay + (behavData.lightTime - behavData.soundTime);\n stimStartIndexesImgReference = round(lightCueTimeImgReference * imgFrameRate); % get the stimulus index\n if stimStartIndexesImgReference <= nFramesImg;\n stimTimeFrames{end + 1} = stimStartIndexesImgReference;\n end;\nend;\n\n%% encode the stimuli\nif ~isempty(stimTimeFrames);\n \n % go through each stim time\n for iStimTime = 1 : numel(stimTimeFrames);\n\n % encode the stimulus time: get the bit code for each stimulus time\n bitCode = bitget(1, 1 : nBitsToUseForStimTimes);\n % encode the bitCode into the stimulus vector\n for iBitLoop = 1 : nBitsToUseForStimTimes;\n % annotate with the stimuli with the current bit iteratively\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitTime(iBitLoop), bitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'time');\n end;\n\n % annotate the stimulus time with the cloud type using the next bit\n soundType = double(behavData.stim == 1);\n soundTypeBitCode = bitget(1 + soundType, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitCloud(iBitLoop), soundTypeBitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'freq');\n end;\n % annotate the stimulus time with the target/non-target using the next bit\n isTarget = double(~isempty(behavData.target) && behavData.target == 1);\n isTargetBitCode = bitget(1 + isTarget, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitTarg(iBitLoop), isTargetBitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'targ');\n end;\n % annotate the stimulus time with the response / non response using the next bit\n isResp = double(~isempty(behavData.resp) && behavData.resp == 1);\n isRespBitCode = bitget(1 + isResp, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitResp(iBitLoop), isRespBitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'resp');\n end;\n % annotate the stimulus time with the correct / false using the next bit\n isCorrect = double(~xor(isTarget, isResp));\n isCorrectBitCode = bitget(1 + isCorrect, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitCorr(iBitLoop), isCorrectBitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'corr');\n end;\n % annotate the stimulus time with the auto / normal using the next bit\n isAuto = double(~isempty(behavData.autoReward) && behavData.autoReward == 1);\n isAutoBitCode = bitget(1 + isAuto, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitCorr(iBitLoop), isAutoBitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'auto');\n end;\n end;\n \n % clean up the stimTypes string\n stimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');\n\n % store the created stimulus vector and the different stimulus types encoding\n setData(this, iDWRow, 'stim', 'data', stimVect);\n setData(this, iDWRow, 'stim', 'loadStatus', 'full');\n setData(this, iDWRow, 'stim', 'stimTypes', stimTypes);\n \nend;\n\n% store back the data\nsetData(this, iDWRow, 'wfTrBehav', 'data', behavData);\n\n%% summary plot\nif doPlotsSummary > 0; % if requested, plot a figure illustrating the extraction procedure\n figure('Name', sprintf('%s_summary', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');\n hold on;\n yLims = [- 0.3, 1.2];\n % trigger\n plot((1 : numel(trigData)) / anInSampRate - trigDelay, linScale(trigData, [-1, 1]), 'k');\n plot(repmat(trigTop(1) / anInSampRate - trigDelay, 2, 1), yLims, 'k:');\n \n % microphone\n plot((1 : numel(micr)) / anInSampRate - trigDelay, micr, 'g');\n plot(repmat(soundStartTimesImgReference, 2, 1), yLims, 'g:');\n plot(repmat(soundEndTimesImgReference, 2, 1), yLims, 'g:');\n \n % piezo\n lickData = abs(behavData.analogInData(strcmp(behavData.analogInNames, 'piezo'), :)) * 15;\n plot((1 : numel(lickData)) / anInSampRate - trigDelay, lickData, 'r');\n plot([1, numel(lickData)] / anInSampRate - trigDelay, repmat(behavData.piezoThresh, 2, 1) * 15, 'r:');\n if ~exist('respTimeImgReference', 'var'); respTimeImgReference = NaN; end;\n plot(repmat(respTimeImgReference, 2, 1), yLims, 'r:');\n \n % light\n plot(repmat(trialStartCueImgReference, 2, 1), yLims, 'b:');\n if ~exist('lightCueTimeImgReference', 'var'); lightCueTimeImgReference = NaN; end;\n plot(repmat(lightCueTimeImgReference, 2, 1), yLims, 'b:');\n \n hold off;\n ylim(yLims);\n title( { sprintf('trigDelay: %.3f, trialStartCue: %.3f, soundStart: %.3f, soundEnd: %.3f', ...\n trigDelay, trialStartCueImgReference, soundStartTimesImgReference, soundEndTimesImgReference), ...\n sprintf('lightCue: %.3f, respTime: %.3f, respDelay: %.3f (actual: %.3f)', lightCueTimeImgReference, ...\n respTimeImgReference, behavData.respDelay, respTimeImgReference - lightCueTimeImgReference)});\nend;\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_genStimVect_fromBehavTextFile.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromBehavTextFile.m", "size": 5478, "source_encoding": "utf_8", "md5": "1379c5e1886d23dbf086cae8b1e60820", "text": "%% #OCIA:AN:OCIA_genStimVect_fromBehavTextFile\nfunction [isValid, unvalidReason] = OCIA_genStimVect_fromBehavTextFile(this, iDWRow, varargin)\n\n% get whether to do plots or not\nif nargin > 2; doDebugPlots = varargin{1}; \nelse doDebugPlots = 0;\nend;\n\nrowID = DWGetRowID(this, iDWRow); % get the row ID \nisValid = true; % by default, the row is valid\nunvalidReason = ''; % by default no reason\n\no('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);\n\n%% init the stim vector\n% get the number of skipped frames\nnSkippedFrames = this.an.skipFrame.nFramesBegin + this.an.skipFrame.nFramesEnd;\nimgDim = str2dim(get(this, iDWRow, 'dim'));\n% compensate for the skipped frames\nif numel(imgDim) < 3; nFramesImg = 0;\nelse nFramesImg = imgDim(3) - nSkippedFrames;\nend;\n% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)\nstimVect = zeros(1, nFramesImg);\n% string storing the stimulus types for this row\nstimTypes = '';\n% start bit encoding with bit 1\niBit = 1;\n\n% store temporarly this empty stimulus vector (in case things get stuck later on)\nsetData(this, iDWRow, 'stim', 'data', stimVect);\nsetData(this, iDWRow, 'stim', 'loadStatus', 'partial');\nsetData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));\n\n% if no imaging frames, abort\nif ~nFramesImg;\n isValid = false; % set the validity flag to false\n % store the reason why this row was not valid\n unvalidReason = sprintf('no imaging data for row %s %03d (frame number = 0)', rowID, iDWRow);\n return; % abort processing of this row\nend;\n\n% get the behavior for this row\nbehavData = getData(this, iDWRow, 'behavExtr', 'data');\n\n% get all possible textures and sort them\nrunTypes = get(this, 'all', 'runType');\nrunTypes(cellfun(@isempty, runTypes)) = [];\ntextureIDs = unique(runTypes);\ntextureRoughness = str2double(regexprep(textureIDs, '^P', ''));\n[~, sortIndex] = sort(textureRoughness);\ntextureIDs = textureIDs(sortIndex);\n\n% get frame rate\nframeRate = this.an.img.defaultFrameRate;\n\n% get the texture index\ntextureIndex = find(strcmp(textureIDs, regexprep(behavData.stimulus, 'Texture \\d ', '')));\n\n% get the decision\nif strcmp(behavData.decision , 'Go');\n decisionIndex = 1;\nelseif strcmp(behavData.decision, 'No Response');\n decisionIndex = 2;\nelseif strcmp(behavData.decision, 'Inappropriate Response');\n decisionIndex = 3;\nelseif strcmp(behavData.decision, 'No Go');\n decisionIndex = 4;\nend;\n\n% get texture's stimulus time and frame number\nstimStartTimeTexture = behavData.stimulus_time / 1000;\nstimStartFrameTexture = round(stimStartTimeTexture * frameRate);\n% adjust for skipped frames\nstimStartFrameTexture = stimStartFrameTexture - this.an.skipFrame.nFramesBegin;\n\n% get texture's stimulus time and frame number\nstimStartTimeLicking = behavData.reward_time / 1000;\nstimStartFrameLicking = round(stimStartTimeLicking * frameRate);\n% adjust for skipped frames\nstimStartFrameLicking = stimStartFrameLicking - this.an.skipFrame.nFramesBegin;\n\n% if no frame found, abort\nif isnan(stimStartFrameTexture);\n stimStartFrameTexture = [];\nend;\n% if no frame found, abort\nif isnan(stimStartFrameLicking);\n stimStartFrameLicking = [];\nend;\n\n% calculate the number of bits required for encoding 8 states (8 textures)\nnMaxStims = 8; nBitsToUse = ceil(log2(nMaxStims));\n% get the bit code for each stimulus number\nbitCode = zeros(nBitsToUse, 1);\nbitCode(:, 1) = bitget(textureIndex, 1 : nBitsToUse);\n% encode the bitCode into the stimulus vector\nfor iBitLoop = 1 : nBitsToUse;\n % annotate with the stimuli with the current bit iteratively\n stimVect(stimStartFrameTexture) = bitset(stimVect(stimStartFrameTexture), iBit, bitCode(iBitLoop, :));\n stimTypes = sprintf('%s,%s', stimTypes, 'text_textType');\n iBit = iBit + 1;\nend;\n% encode the bitCode into the stimulus vector\nfor iBitLoop = 1 : nBitsToUse;\n % annotate with the stimuli with the current bit iteratively\n stimVect(stimStartFrameLicking) = bitset(stimVect(stimStartFrameLicking), iBit, bitCode(iBitLoop, :));\n stimTypes = sprintf('%s,%s', stimTypes, 'lick_textType');\n iBit = iBit + 1;\nend;\n\n\n% calculate the number of bits required for encoding 8 states (8 outcomes)\nnMaxStims = 8; nBitsToUse = ceil(log2(nMaxStims));\n% get the bit code for each stimulus number\nbitCode = zeros(nBitsToUse, 1);\nbitCode(:, 1) = bitget(decisionIndex, 1 : nBitsToUse);\n% encode the bitCode into the stimulus vector\nfor iBitLoop = 1 : nBitsToUse;\n % annotate with the stimuli with the current bit iteratively\n stimVect(stimStartFrameTexture) = bitset(stimVect(stimStartFrameTexture), iBit, bitCode(iBitLoop, :));\n stimTypes = sprintf('%s,%s', stimTypes, 'text_decision');\n iBit = iBit + 1;\nend;\n% encode the bitCode into the stimulus vector\nfor iBitLoop = 1 : nBitsToUse;\n % annotate with the stimuli with the current bit iteratively\n stimVect(stimStartFrameLicking) = bitset(stimVect(stimStartFrameLicking), iBit, bitCode(iBitLoop, :));\n stimTypes = sprintf('%s,%s', stimTypes, 'lick_decision');\n iBit = iBit + 1;\nend;\n\n\n%% saving the stimulus vector\n% clean up the stimTypes string\nstimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');\n\n% store the created stimulus vector and the different stimulus types encoding\nsetData(this, iDWRow, 'stim', 'data', stimVect);\nsetData(this, iDWRow, 'stim', 'loadStatus', 'full');\nsetData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));\n\n\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_genStimVect_noStim.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_noStim.m", "size": 882, "source_encoding": "utf_8", "md5": "03e130ba77be5a2d529963b4cd2fe64c", "text": "%% #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn\nfunction [isValid, unvalidReason] = OCIA_genStimVect_noStim(this, iDWRow, varargin)\n\nisValid = true; % by default, the row is valid\nunvalidReason = ''; % by default no reason\n\n%% init the stim vector\n% get the number of skipped frames\nnSkippedFrames = this.an.skipFrame.nFramesBegin + this.an.skipFrame.nFramesEnd;\nimgDim = str2dim(get(this, iDWRow, 'dim'));\n% compensate for the skipped frames\nif numel(imgDim) < 3; nFramesImg = 0;\nelse nFramesImg = imgDim(3) - nSkippedFrames;\nend;\n% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)\nstimVect = zeros(1, nFramesImg);\n\n% store the extracted items: stimulus vector\nsetData(this, iDWRow, 'stim', 'data', stimVect);\nsetData(this, iDWRow, 'stim', 'loadStatus', 'full');\nsetData(this, iDWRow, 'stim', 'stimTypes', '');\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_genStimVect_fromInputArgument.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromInputArgument.m", "size": 2411, "source_encoding": "utf_8", "md5": "8cb502bb2a0dfe425818d1461d8d8ff5", "text": "%% #OCIA:AN:OCIA_genStimVect_fromInputArgument\nfunction [isValid, unvalidReason] = OCIA_genStimVect_fromInputArgument(this, iDWRow, stimVectCellArray, ...\n stimTypesCellArray, nMaxStimTypesCellArray)\n\nisValid = true; % by default, the row is valid\nunvalidReason = ''; % by default no reason\n\no('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);\n\n%% creating the stim vector\n% start bit encoding with bit 1\niBit = 0;\n\n% initiate final stim vector\nfinalStimVect = zeros(size(stimVectCellArray{1}));\nfinalStimTypes = '';\n\n% encode each stimulus type one after the other\nfor iStimVect = 1 : numel(stimVectCellArray);\n \n currStimVect = stimVectCellArray{iStimVect};\n stimIndices = find(currStimVect > 0);\n stimValues = currStimVect(stimIndices);\n \n % calculate the number of bits to encode \n nMaxStimTypes = nMaxStimTypesCellArray{iStimVect};\n nBitsToUseForStimTimes = max(ceil(log2(nMaxStimTypes)), 1);\n % assign bits to difference encodings\n iBitCurrStimVect = iBit + (1 : nBitsToUseForStimTimes);\n iBit = iBit + nBitsToUseForStimTimes;\n \n % encode the stimulus time: get the bit code for each stimulus time\n for iInd = 1 : numel(stimIndices);\n bitCode = bitget(stimValues(iInd), 1 : nBitsToUseForStimTimes);\n % encode the bitCode into the stimulus vector\n for iBitLoop = 1 : nBitsToUseForStimTimes;\n % annotate with the stimuli with the current bit iteratively\n finalStimVect(stimIndices(iInd)) = bitset(finalStimVect(stimIndices(iInd)), iBitCurrStimVect(iBitLoop), ...\n bitCode(iBitLoop));\n end;\n end;\n \n % encode the stimulus type\n for iBitLoop = 1 : nBitsToUseForStimTimes;\n finalStimTypes = sprintf('%s,%s', finalStimTypes, stimTypesCellArray{iStimVect});\n end;\n\n % store temporarly this empty stimulus vector (in case things get stuck later on)\n setData(this, iDWRow, 'stim', 'data', finalStimVect);\n setData(this, iDWRow, 'stim', 'loadStatus', 'partial');\n setData(this, iDWRow, 'stim', 'stimTypes', regexprep(finalStimTypes, '^,', ''));\n \nend;\n\n%% saving the stimulus vector \n% store the created stimulus vector and the different stimulus types encoding\nsetData(this, iDWRow, 'stim', 'data', finalStimVect);\nsetData(this, iDWRow, 'stim', 'loadStatus', 'full');\nsetData(this, iDWRow, 'stim', 'stimTypes', regexprep(finalStimTypes, '^,', ''));\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_genStimVect_fromMicrAnalogIn.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromMicrAnalogIn.m", "size": 25627, "source_encoding": "utf_8", "md5": "8fb42ab887a6a62a42ac00cb7eb1782b", "text": "%% #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn\nfunction [isValid, unvalidReason] = OCIA_genStimVect_fromMicrAnalogIn(this, iDWRow, varargin)\n\n% get whether to do plots or not\nif nargin > 2; doPlotsYscan = varargin{1}; doPlotsMicr = varargin{1};\nelseif nargin > 3; doPlotsYscan = varargin{1}; doPlotsMicr = varargin{2};\nelse doPlotsYscan = 0; doPlotsMicr = 0;\nend;\n\nrowID = DWGetRowID(this, iDWRow); % get the row ID \nisValid = true; % by default, the row is valid\nunvalidReason = ''; % by default no reason\n\no('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);\n\n% get the behavior data for this row\nbehavData = getData(this, iDWRow, 'behavExtr', 'data');\n\n% if no behavior data is found, abort\nif isempty(behavData);\n isValid = false; % set the validity flag to false\n % store the reason why this row was not valid\n unvalidReason = sprintf('cannot find associated behavior data (behavior data unavailable in row %03d)', iDWRow);\n return; % abort processing of this row\nend;\n\niTrial = str2double(get(this, iDWRow, 'runNum')); % get the trial number\n% if no behavior row found using the behavior ID, abort\nif isempty(iTrial) || isnan(iTrial) || iTrial <= 0;\n isValid = false; % set the validity flag to false\n % store the reason why this row was not valid\n unvalidReason = sprintf('bad trial number (\"%s\" => %d\")', get(this, iDWRow, 'runNum'), iTrial);\n return; % abort processing of this row\nend;\n\n% fix missing fields\nif isfield(behavData, 'nTones');\n % if more than one element for nTones, there must be one element per trial\n if numel(behavData.nTones) > 1; nTones = behavData.nTones(iTrial);\n % otherwise there is only one constant number of tones\n else nTones = behavData.nTones;\n end;\n% if no field, assume there is only one tone\nelse nTones = 1;\nend;\n\n%% init the stim vector\n% get the number of skipped frames\nnSkippedFrames = this.an.skipFrame.nFramesBegin + this.an.skipFrame.nFramesEnd;\nimgDim = str2dim(get(this, iDWRow, 'dim'));\n% compensate for the skipped frames\nif numel(imgDim) < 3; nFramesImg = 0;\nelse nFramesImg = imgDim(3) - nSkippedFrames;\nend;\n% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)\nstimVect = zeros(1, nFramesImg);\n% string storing the stimulus types for this row\nstimTypes = '';\n% initialize variables\nimgDelay = NaN;\ntrueFrameRate = NaN;\n% calculate the number of bits to encode \nnMaxStimTimes = 10; nBitsToUseForStimTimes = ceil(log2(nMaxStimTimes));\n% assign bits to difference encodings\niBitTime = 1 : nBitsToUseForStimTimes; iBitCloud = iBitTime(end) + (1 : 2); iBitTarg = iBitCloud(end) + (1 : 2);\niBitResp = iBitTarg(end) + (1 : 2); iBitCorr = iBitResp(end) + (1 : 2);\n% other random bit\niBit = 1;\n\n%% - #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn : delay and true frame rate analysis (yscan)\nif ismember('yscan', behavData.analogInNames);\n % extract the number of frames from the microscope's y scanner's position\n yscan = behavData.analogInData(strcmp(behavData.analogInNames, 'yscan'), :); % extract the y scanner's trace\n normThresh = 3 * std(yscan(1 : 1000)); % take the first 1000 frames for normalization threshold\n yscan(abs(yscan) < normThresh) = 0; % normalize to remove the noise of parts when scanner is not moving\n yscanTopPrctile = prctile(yscan, 80); % set a threshold at the 80th percentile\n yscanTop = find(yscan > yscanTopPrctile); % find all the peaks\n yscanTopDiff = diff(yscanTop); % get the differential of the peaks to find the real peak\n yscanTopDiffPeaks = [find(yscanTopDiff > 1) size(yscanTop, 2)]; % get the peaks\n nFramesBehav = size(yscanTopDiffPeaks, 2); % get the number of frames found using the recording of the y scanner\n\n % get the middle part of the frames (20%-80%) to exclude starting and ending artifacts\n middleFrames = round(nFramesBehav * 0.2) : round(nFramesBehav * 0.8);\n % calculate the true frame rate (based on the y position of the scanner)\n if isfield(behavData, 'analogInSampRate'); % if there is a field containing the analog input sampling rate\n anInSampRate = behavData.analogInSampRate;\n % calculate the true frame rate using the inter-peak interval\n trueFrameRate = anInSampRate / mean(diff(yscanTop(yscanTopDiffPeaks(middleFrames))));\n \n % no field containing the analog input rate, figure it out (backward compatibility)\n else\n % try to find the sampling rate from the two possible values\n unknownBehavRate = [3000 3333];\n % two possible frame rates\n trueFrameRateOptions = unknownBehavRate / mean(diff(yscanTop(yscanTopDiffPeaks(middleFrames))));\n % find the closest frame rate to the expected frame rate\n [~, closestBehavRateInd] = min(abs(trueFrameRateOptions - 77.67));\n % get analog input sampling rate and the true frame rate corresponding to this closest frame rate\n anInSampRate = unknownBehavRate(closestBehavRateInd);\n trueFrameRate = trueFrameRateOptions(closestBehavRateInd);\n % show a warning for this assumption\n showWarning(this, 'OCIA:OCIA_genStimVect_fromMicrAnalogIn:NoAnInSampRate', ...\n sprintf(['Missing analog in sample rate for %s (%d)! Assuming it was %d Hz (=> true frame rate: ', ...\n '%.2f Hz).'], rowID, iDWRow, anInSampRate, trueFrameRate));\n end;\n\n % get the imaging delay by substract the time of a single frame from the first y scanner peak\n frameLength = round(anInSampRate / trueFrameRate);\n firstFrameEndInd = yscanTop(yscanTopDiffPeaks(1));\n firstFrameStartInd = firstFrameEndInd - frameLength;\n imgDelay = firstFrameStartInd / anInSampRate;\n\n % store the extracted number: analog input sampling rate, imaging delay and true frame rate\n \n behavData.behavSampRate = anInSampRate;\n behavData.imgDelay = imgDelay;\n behavData.imgFrameRate = trueFrameRate;\n\n % check whether there is a big frame difference between the imaging and the behavior recording\n nFrameDiff = nFramesBehav - nFramesImg;\n % if there is some imaging data and difference is too big (more than 1 second), abort\n if nFramesImg && nFrameDiff > 1 * trueFrameRate;\n showWarning(this, 'OCIA:genStimVect:fromMicrAnalogIn:missingFrames', sprintf(['Missing frames in the ', ...\n 'imaging data: frames from behavior = %d, from imaging = %d (~= %.1f ms difference). Going on ...'], ...\n nFramesBehav, nFramesImg, 1000 * nFrameDiff / trueFrameRate));\n % change the display color\n frameDisplayColor = 'orange';\n \n elseif nFramesImg && nFrameDiff < 0;\n isValid = false; % set the validity flag to false\n % store the reason why this row was not valid\n unvalidReason = sprintf(['frame number mismatch (frames from behavior: %d, from imaging: %d ', ...\n '(~= %.1f ms difference).'], nFramesBehav, nFramesImg, 1000 * nFrameDiff / trueFrameRate); \n % change the display color\n frameDisplayColor = 'red';\n \n % no frame mismatch\n else \n % change the display color\n frameDisplayColor = 'green';\n end;\n \n % add the number of frames from the behavior in the comments\n comments = getR(this, iDWRow, 'comments');\n if iscell(comments); comments = comments{1}; end;\n % clean the HTML away\n comments = regexprep(comments, '^', ''); % remove HTML tag\n comments = regexprep(comments, ']+>', ''); % remove font tags\n comments = regexprep(comments, '', ''); % remove font tags\n % remove the previous frame number tag\n comments = regexprep(comments, '(, )?\\d+ frames \\(behav\\.\\)', '');\n % add the HTML for a colored frame number comment\n comments = sprintf('%s%s%d frames (behav.)', comments, ...\n iff(isempty(comments), '', ', '), frameDisplayColor, nFramesBehav);\n % put back the comments in the table and update the display\n set(this, iDWRow, 'comments', comments);\n DWUpdateColumnsDisplay(this, iDWRow, { 'comments' }, false);\n \n % if row is not valid, abort processing of this row\n if ~isValid; return; end;\n\n if doPlotsYscan > 0; % if requested, plot a figure illustrating the extraction procedure\n figure('Name', sprintf('%s_yscan', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');\n plot(yscan, 'k');\n title(sprintf('nFramesBehav: %d, nFramesImag: %d', nFramesBehav, nFramesImg));\n hold on;\n yLims = get(gca, 'YLim');\n plot(yscanTop, yscan(yscanTop), 'g');\n plot(yscanTop(1 : end - 1) + 0.5, yscanTopDiff / 100, 'r');\n plot(repmat(firstFrameStartInd, 2, 1), yLims, 'r:');\n scatter(yscanTop(yscanTopDiffPeaks), repmat(0.8, nFramesBehav, 1), 'b*');\n end;\n\nend; % end check yscan exists\n\n%% - #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn : sound start (stimulus time) analysis (micr)\nif ismember('micr', behavData.analogInNames);\n\n % get the number of samples\n nSamples = size(behavData.analogInData, 2);\n \n % extract the stimulus sound time and duration from the recorded sound\n micr = linScale(abs(behavData.analogInData(strcmp(behavData.analogInNames, 'micr'), :))); % extract the microphone's trace\n % get a range for the begining of the signal\n begRange = round(nSamples * 0.01 : nSamples * 0.1);\n % incrementally search for the right threshold\n nSoundsDiff = 1; soundYThresh = 0; soundThreshFactor = 5; soundThreshFactorStep = 5; nLoops = 0;\n while nSoundsDiff && soundThreshFactor < 55;\n % get a threshold for the sound onset\n soundThreshFactor = soundThreshFactor + soundThreshFactorStep;\n soundYThresh = soundThreshFactor * std(micr(begRange));\n % get the samples that exceeds the threshold, adding the first sample to catch the start of the first sound\n upSamples = [0 find(micr > soundYThresh)];\n % get the derivative of the upSamples, drops in the sample indexes indicate interruption of upSamples,\n % which means that there is a sound start\n upSamplesDiff = diff(upSamples);\n % use the ISI to find peaks. If no ISI, use 0.5 second\n ISI = 0.5;\n if isfield(behavData, 'ISI') && behavData.ISI > 0;\n ISI = behavData.ISI;\n end;\n % difference between detected upSample derivative's peaks must be at least half of the ISI\n minISI = ISI * 0.5 * anInSampRate;\n % get the index of the peaks where the derivative exceeds the ISI threshold and increment by one to get\n % the sound start index\n soundStartInds = upSamples(find(upSamplesDiff >= minISI) + 1);\n\n if ~isempty(soundStartInds);\n % calculate the sound start time\n soundStartTimes = soundStartInds / anInSampRate;\n else\n soundStartTimes = [];\n end;\n\n % check whether there is a big frame difference between the imaging and the behavior recording\n nSoundsDiff = abs(nTones - numel(soundStartTimes));\n nLoops = nLoops + 1;\n\n end;\n\n % if there is a mismatch in the number of sounds found and more sounds were found, show a warning\n if nSoundsDiff && ~isempty(soundStartTimes) && numel(soundStartTimes) >= nTones;\n showWarning(this, 'OCIA:OCIA_genStimVect_fromMicrAnalogIn:MissingStim', ...\n sprintf(['Problem with number of stimuli found for %s (%d)! Number of stim detected in recorded ', ...\n 'data: %d, expected number of stim: %d. Taking only the first %d stim(s).'], rowID, iDWRow, ...\n numel(soundStartTimes), nTones, nTones));\n soundStartTimes = soundStartTimes(1 : nTones);\n doPlotsMicr = doPlotsMicr + 1;\n \n % if there is a mismatch in the number of sounds found and less sounds were found, show a warning\n elseif nSoundsDiff;\n showWarning(this, 'OCIA:OCIA_genStimVect_fromMicrAnalogIn:MissingStim', ...\n sprintf(['Problem with number of stimuli found for %s (%d)! Number of stim detected in recorded ', ...\n 'data: %d, expected number of stim: %d.'], rowID, iDWRow, numel(soundStartTimes), nTones));\n doPlotsMicr = doPlotsMicr + 1;\n end;\n\n % if there is some imaging data and some sound start, create the simulus vector\n if nFramesImg && ~isempty(soundStartTimes);\n % get the stimulus time, including the imaging start delay\n soundStartTimesImgReference = soundStartTimes - imgDelay;\n stimStartIndexesImgReference = round(soundStartTimesImgReference * trueFrameRate); % get the stimulus index\n % remove stim start times that are too early\n if any(stimStartIndexesImgReference < 0);\n nRemStims = sum(stimStartIndexesImgReference < 0);\n stimStartIndexesImgReference(stimStartIndexesImgReference <= 0) = [];\n showWarning(this, 'OCIA:OCIA_genStimVect_fromMicrAnalogIn:EarlyStim', ...\n sprintf('Removed %d early stimuli found for %s (%d)!', nRemStims, rowID, iDWRow));\n end;\n \n %% annotate stimulus frames \n % if this is an cloud of tone discrimination task\n if strcmp(behavData.taskType, 'cotDiscr');\n \n % encode the sound start stimulus\n stimTimeFrames = { stimStartIndexesImgReference };\n \n % go through each stim time\n for iStimTime = 1 : numel(stimTimeFrames);\n \n % encode the stimulus time: get the bit code for each stimulus time\n bitCode = bitget(1, 1 : nBitsToUseForStimTimes);\n % encode the bitCode into the stimulus vector\n for iBitLoop = 1 : nBitsToUseForStimTimes;\n % annotate with the stimuli with the current bit iteratively\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitTime(iBitLoop), bitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'time');\n end;\n \n % annotate the stimulus time with the cloud type using the next bit\n soundType = double(behavData.stim == 1);\n soundTypeBitCode = bitget(1 + soundType, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitCloud(iBitLoop), soundTypeBitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'cloud');\n end;\n % annotate the stimulus time with the target/non-target using the next bit\n isTarget = double(~isempty(behavData.target) && behavData.target == 1);\n isTargetBitCode = bitget(1 + isTarget, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitTarg(iBitLoop), isTargetBitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'targ');\n end;\n % annotate the stimulus time with the response / non response using the next bit\n isResp = double(~isempty(behavData.resp) && behavData.resp == 1);\n isRespBitCode = bitget(1 + isResp, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitResp(iBitLoop), isRespBitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'resp');\n end;\n % annotate the stimulus time with the correct / false using the next bit\n isCorrect = double(~xor(isTarget, isResp));\n isCorrectBitCode = bitget(1 + isCorrect, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitCorr(iBitLoop), isCorrectBitCode(iBitLoop));\n stimTypes = sprintf('%s,%s', stimTypes, 'corr');\n end;\n end;\n\n % if this is an oddball experiment with the right number of sounds\n elseif strcmp(behavData.taskType, 'cotOdd') && isfield(behavData, 'oddPos') && numel(stimStartIndexesImgReference) >= behavData.oddPos;\n \n % annotate with 1 on the first bit to mark it as stimulus frame\n stimVect(stimStartIndexesImgReference) = bitset(stimVect(stimStartIndexesImgReference), iBit, 1);\n stimTypes = sprintf('%s,%s', stimTypes, 'stim');\n iBit = iBit + 1;\n \n % calculate the number of bits required for encoding 10 states (10 stimuli)\n nStims = numel(stimStartIndexesImgReference); nMaxStims = 10; nBitsToUse = ceil(log2(nMaxStims));\n % get the bit code for each stimulus number\n bitCode = zeros(nBitsToUse, nStims);\n for iStim = 1 : nStims;\n bitCode(:, iStim) = bitget(iStim, 1 : nBitsToUse);\n end;\n % encode the bitCode into the stimulus vector\n for iBitLoop = 1 : nBitsToUse;\n % annotate with the stimuli with the current bit iteratively\n stimVect(stimStartIndexesImgReference) = bitset(stimVect(stimStartIndexesImgReference), iBit, bitCode(iBitLoop, :));\n stimTypes = sprintf('%s,%s', stimTypes, 'stimNum');\n iBit = iBit + 1;\n end;\n \n % annotate with the sound type depending on the standard/odd using the next bit\n soundType = behavData.stim == 1;\n stimVect(stimStartIndexesImgReference) = bitset(stimVect(stimStartIndexesImgReference), iBit, soundType);\n stimVect(stimStartIndexesImgReference(behavData.oddPos)) = bitset(stimVect(stimStartIndexesImgReference(behavData.oddPos)), iBit, ~soundType);\n stimTypes = sprintf('%s,%s', stimTypes, 'soundType');\n iBit = iBit + 1;\n \n % calculate the number of bits required for encoding 3 states (first, pre-odd, odd)\n nStims = numel(stimStartIndexesImgReference); nMaxStims = 3; nBitsToUse = ceil(log2(nMaxStims));\n % get the bit code for each stimulus number\n bitCode = zeros(nBitsToUse, nStims);\n for iStim = 1 : nStims;\n % get the stimulus state to encode for this stimulus\n if iStim == 1; stimState = 1;\n elseif iStim == behavData.oddPos - 1; stimState = 2; \n elseif iStim == behavData.oddPos; stimState = 3;\n else stimState = 0;\n end;\n bitCode(:, iStim) = bitget(stimState, 1 : nBitsToUse);\n end;\n % encode the bitCode into the stimulus vector\n for iBitLoop = 1 : nBitsToUse;\n % annotate with the stimuli with the current bit iteratively\n stimVect(stimStartIndexesImgReference) = bitset(stimVect(stimStartIndexesImgReference), iBit, bitCode(iBitLoop, :));\n stimTypes = sprintf('%s,%s', stimTypes, 'oddball');\n iBit = iBit + 1;\n end;\n \n end;\n end;\n \n % clean up the stimTypes string\n stimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');\n\n % store the created stimulus vector and the different stimulus types encoding\n behavData.soundStartTime = soundStartTimes;\n setData(this, iDWRow, 'stim', 'data', stimVect);\n setData(this, iDWRow, 'stim', 'loadStatus', 'full');\n setData(this, iDWRow, 'stim', 'stimTypes', stimTypes);\n\n if doPlotsMicr > 0; % if requested, plot a figure illustrating the extraction procedure\n figure('Name', sprintf('%s_micr', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');\n rectangle('Position', [begRange(1) 0 begRange(end) - begRange(1) soundYThresh * 1.1], ...\n 'FaceColor', [0.8 1 0.8], 'EdgeColor', [0.8 1 0.8]);\n hold on;\n plot(micr, 'k');\n yLims = get(gca, 'YLim'); xLims = get(gca, 'XLim');\n plot(upSamples(1 : end - 1) - 0.5, (upSamplesDiff / max(upSamplesDiff)) * max(micr) * 0.9, 'r');\n plot(repmat(soundStartInds, 2, 1), repmat(yLims, numel(soundStartInds), 1)', 'r:');\n plot(xLims, repmat(soundYThresh, 2, 1), 'g:');\n title(sprintf('stimYThresh: %.5f, stimStartTimes: %s', soundYThresh, sprintf(' %.2fs', soundStartTimes)));\n end;\n\nend; % end check micr exists\n\n%% - #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn : light cue and response time\nif strcmp(behavData.taskType, 'cotDiscr') && ~isnan(imgDelay) && ~isnan(trueFrameRate);\n \n % encode the stimuli\n stimTimeFrames = { };\n \n % get the light time, including the imaging start delay\n if isfield(behavData, 'lightTime') && ~isnan(behavData.lightTime);\n lightTimeImgReference = behavData.soundStartTime - imgDelay + (behavData.lightTime - behavData.soundTime);\n stimStartIndexesImgReference = round(lightTimeImgReference * trueFrameRate); % get the stimulus index\n if stimStartIndexesImgReference <= nFramesImg;\n stimTimeFrames{end + 1} = stimStartIndexesImgReference;\n end;\n end;\n \n % get the response time, including the imaging start delay\n if isfield(behavData, 'respTime') && ~isnan(behavData.respTime);\n respTimeImgReference = behavData.soundStartTime - imgDelay + (behavData.respTime - behavData.soundTime);\n stimStartIndexesImgReference = round(respTimeImgReference * trueFrameRate); % get the stimulus index\n if stimStartIndexesImgReference <= nFramesImg;\n stimTimeFrames{end + 1} = stimStartIndexesImgReference;\n end;\n end;\n \n % get the light off time, including the imaging start delay\n if isfield(behavData, 'lightOffTime') && ~isnan(behavData.lightOffTime);\n lightOffTimeImgReference = behavData.soundStartTime - imgDelay + (behavData.lightOffTime - behavData.soundTime);\n stimStartIndexesImgReference = round(lightOffTimeImgReference * trueFrameRate); % get the stimulus index\n if stimStartIndexesImgReference <= nFramesImg;\n stimTimeFrames{end + 1} = stimStartIndexesImgReference;\n end;\n end;\n \n % go through each stim time\n for iStimTime = 1 : numel(stimTimeFrames);\n\n % encode the stimulus time: get the bit code for each stimulus time\n bitCode = bitget(1 + iStimTime, 1 : nBitsToUseForStimTimes);\n % encode the bitCode into the stimulus vector\n for iBitLoop = 1 : nBitsToUseForStimTimes;\n % annotate with the stimuli with the current bit iteratively\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), iBitTime(iBitLoop), ...\n bitCode(iBitLoop));\n end;\n\n % annotate the stimulus time with the cloud type using the next bit\n soundType = double(behavData.stim == 1);\n soundTypeBitCode = bitget(1 + soundType, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitCloud(iBitLoop), soundTypeBitCode(iBitLoop));\n end;\n % annotate the stimulus time with the target/non-target using the next bit\n isTarget = double(~isempty(behavData.target) && behavData.target == 1);\n isTargetBitCode = bitget(1 + isTarget, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitTarg(iBitLoop), isTargetBitCode(iBitLoop));\n end;\n % annotate the stimulus time with the response / non response using the next bit\n isResp = double(~isempty(behavData.resp) && behavData.resp == 1);\n isRespBitCode = bitget(1 + isResp, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitResp(iBitLoop), isRespBitCode(iBitLoop));\n end;\n % annotate the stimulus time with the correct / false using the next bit\n isCorrect = double(~xor(isTarget, isResp));\n isCorrectBitCode = bitget(1 + isCorrect, 1 : 2);\n for iBitLoop = 1 : 2;\n stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...\n iBitCorr(iBitLoop), isCorrectBitCode(iBitLoop));\n end;\n end;\n \n % if some stimulus was found\n if ~isempty(stimTypes);\n \n % clean up the stimTypes string\n stimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');\n\n % store the created stimulus vector and the different stimulus types encoding\n setData(this, iDWRow, 'stim', 'data', stimVect);\n setData(this, iDWRow, 'stim', 'loadStatus', 'full');\n setData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));\n \n end;\n \nend;\n\n% store back the data\nsetData(this, iDWRow, 'behavExtr', 'data', behavData);\n\n% % display message\n% showMessage(this, sprintf(['Extracting behavior data for %s (%d) done (frames behav: %d, ', ...\n% 'frames img: %d, nStims: %d, nLoops: %d, %3.1f sec).'], rowID, iDWRow, nFramesBehav, ...\n% nFramesImg, numel(stimStartTimes), nLoops, toc(behavExtrTic)));\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_genStimVect_fromWhisker.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromWhisker.m", "size": 4088, "source_encoding": "utf_8", "md5": "b073f00c4f340f8c1ab5674eb41e5d5d", "text": "%% #OCIA:AN:OCIA_genStimVect_fromWhisker\nfunction [isValid, unvalidReason] = OCIA_genStimVect_fromWhisker(this, iDWRow, varargin)\n\n% get whether to do plots or not\nif nargin > 2; doDebugPlots = varargin{1}; \nelse doDebugPlots = 0;\nend;\n\nrowID = DWGetRowID(this, iDWRow); % get the row ID \nisValid = true; % by default, the row is valid\nunvalidReason = ''; % by default no reason\n\no('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);\n\n%% init the stim vector\n% get the number of skipped frames\nnSkippedFrames = this.an.skipFrame.nFramesBegin + this.an.skipFrame.nFramesEnd;\nimgDim = str2dim(get(this, iDWRow, 'dim'));\n% compensate for the skipped frames\nif numel(imgDim) < 3; nFramesImg = 0;\nelse nFramesImg = imgDim(3) - nSkippedFrames;\nend;\n% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)\nstimVect = zeros(1, nFramesImg);\n% string storing the stimulus types for this row\nstimTypes = '';\n% start bit encoding with bit 1\niBit = 1;\n\n% store temporarly this empty stimulus vector (in case things get stuck later on)\nsetData(this, iDWRow, 'stim', 'data', stimVect);\nsetData(this, iDWRow, 'stim', 'loadStatus', 'partial');\nsetData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));\n\n% if no imaging frames, abort\nif ~nFramesImg;\n isValid = false; % set the validity flag to false\n % store the reason why this row was not valid\n unvalidReason = sprintf('no imaging data for row %s %03d (frame number = 0)', rowID, iDWRow);\n return; % abort processing of this row\nend;\n\n% get the (eventually down-sampled) whisker traces matrix for the requested rows\nwhiskTraces = OCIA_analysis_getRawWhiskTracesMatrix(this, iDWRow, true);\n\n% if no whisker data is found, abort\nif isempty(whiskTraces);\n isValid = false; % set the validity flag to false\n % store the reason why this row was not valid\n unvalidReason = sprintf('cannot find whisker data for row %s %03d', rowID, iDWRow);\n return; % abort processing of this row\nend;\n\n% normalize the traces by their mean\nwhiskTraces = whiskTraces - nanmean(whiskTraces);\n\n\n%% Whisker peak\nminPeakThresh = 10;\nminPeakDist = 5;\n[peakValues, stimPeakFrames] = findpeaks(whiskTraces, 'MinPeakHeight', minPeakThresh, 'MinPeakDistance', 15);\n\n% if there are some stimulus, fill the simulus vector\nif ~isempty(stimPeakFrames);\n \n % annotate the whisking peak with 1 on the current bit to mark it as stimulus frame\n stimVect(stimPeakFrames) = bitset(stimVect(stimPeakFrames), iBit, 1);\n stimTypes = sprintf('%s,%s', stimTypes, 'whiskPeak');\n iBit = iBit + 1;\n \n % if requested, plot a figure illustrating the extraction procedure\n if doDebugPlots > 0;\n figure('Name', sprintf('%s_whiskPeak', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');\n whiskHandle = plot(whiskTraces, 'k');\n hold('on');\n hScatt = scatter(stimPeakFrames, peakValues, 100, 'rs', 'fill');\n yLims = get(gca, 'YLim'); xLims = get(gca, 'XLim');\n minPeakHeightHandle = plot(xLims, repmat(minPeakThresh, 2, 1), 'g:');\n minPeakDistHandle = plot([stimPeakFrames; stimPeakFrames], repmat(yLims', 1, numel(stimPeakFrames)), 'b:');\n plot([stimPeakFrames + minPeakDist; stimPeakFrames + minPeakDist], repmat(yLims', 1, numel(stimPeakFrames)), 'b:');\n title(sprintf('minPeakThresh: %.1f, minPeakDist: %.1f', minPeakThresh, minPeakDist));\n legend([whiskHandle, hScatt(1), minPeakHeightHandle(1), minPeakDistHandle(1)], ...\n 'whisker angle', 'peaks', 'minimum peak height threshold', 'minimum inter-peak distance threshold');\n end;\n \nend;\n\n%% Other methods ...\n\n\n\n%% saving the stimulus vector\n% clean up the stimTypes string\nstimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');\n \n% store the created stimulus vector and the different stimulus types encoding\nsetData(this, iDWRow, 'stim', 'data', stimVect);\nsetData(this, iDWRow, 'stim', 'loadStatus', 'full');\nsetData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_startFunction_widefieldCreateAveragesForEachCondition.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/startFunctions/OCIA_startFunction_widefieldCreateAveragesForEachCondition.m", "size": 9795, "source_encoding": "utf_8", "md5": "eef9147a9768002dbc4259deb36d33ff", "text": "function OCIA_startFunction_widefieldCreateAveragesForEachCondition(this)\n% OCIA_startFunction_widefieldCreateAveragesForEachCondition - [no description]\n%\n% OCIA_startFunction_widefieldCreateAveragesForEachCondition(this)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n \n% iStartID = 37;\n iStartID = 41;\n iExcl = []; % iEndID = Inf;\n% iEndID = 40;\n iEndID = 43;\n iTrialStart = 1;\n iTrialEnd = Inf;\n fixedStartFrame = 60;\n\n % define trial types\n % { '4 kHz', '28 kHz', 'miss', 'FA', 'early', 'auto' } \n % { 'go', 'nogo', 'miss', 'FA', 'early', 'auto' }\n trialTypesRegexp = { 'hit', 'CR', 'quiet', 'moveDur', 'moveBef', ...\n 'hit_AND_moveDur', 'hit_AND_quiet', 'hit_AND_moveBef', 'hit_AND_[quiet|moveBef]', ...\n 'CR_AND_moveDur', 'CR_AND_quiet', 'CR_AND_moveBef', 'CR_AND_[quiet|moveBef]' };\n trialTypeSaveName = { 'hit', 'CR', 'strict_quiet', 'move', 'early_move', ...\n 'move_hit', 'strict_quiet_hit', 'early_move_hit', 'delay_quiet_hit', ...\n 'move_CR', 'strict_quiet_CR', 'early_move_CR', 'delay_quiet_CR' };\n\n %% get all widefield data\n OCIAChangeMode(this, 'DataWatcher');\n \n % get the DataWatcher's and the Analyser's GUI handles\n dwh = this.GUI.handles.dw;\n \n % set the watch types\n set(dwh.watchTypes.animal, 'Value', 1);\n set(dwh.watchTypes.day, 'Value', 1);\n set(dwh.watchTypes.wfLV, 'Value', 1);\n set(dwh.watchTypes.wfLVSess, 'Value', 1);\n set(dwh.watchTypes.wfLVMat, 'Value', 0);\n set(dwh.watchTypes.wfAn, 'Value', 0);\n set(dwh.watchTypes.behav, 'Value', 0);\n % set the filters\n set(dwh.filt.animalID, 'Value', 1, 'String', { '-' });\n set(dwh.filt.dayID, 'Value', 1, 'String', { '-' });\n set(dwh.filt.wfLVSessID, 'Value', 1, 'String', { '-' });\n set(dwh.filt.rowTypeID, 'Value', 1, 'String', { '-' });\n set(dwh.filt.dataLoadStatus, 'Value', 0, 'String', '');\n set(dwh.filt.rowNum, 'Value', 0, 'String', '');\n set(dwh.filt.runNum, 'Value', 0, 'String', '');\n set(dwh.filt.all, 'Value', 0, 'String', '');\n \n % update the table\n DWProcessWatchFolder(this);\n \n % set the watch types for processing\n set(dwh.watchTypes.wfLVMat, 'Value', 1);\n set(dwh.watchTypes.behav, 'Value', 1);\n \n % get triplets\n IDs = get(this, 'all', { 'animal', 'day', 'wfLVSess', 'runNum' }, DWFilterTable(this, 'rowType = WFLV session AND wfLVSess ~= \\d{6}'));\n \n %% go through each row\n for iID = max(iStartID, 1) : min(size(IDs, 1), iEndID);\n \n % do not process excluded IDs\n if ismember(iID, iExcl); continue; end;\n \n % get the IDs and set filters\n [animalID, dayID, sessID, sessNum] = IDs{iID, :};\n set(dwh.filt.animalID, 'Value', 2, 'String', { '-', animalID });\n set(dwh.filt.dayID, 'Value', 2, 'String', { '-', dayID });\n set(dwh.filt.wfLVSessID, 'Value', 2, 'String', { '-', sprintf('session%s_%s', sessNum, sessID) });\n \n % update the table\n DWProcessWatchFolder(this);\n \n % get trial rows\n [~, trialRowInds] = DWFilterTable(this, 'rowType = WF trial');\n if isempty(trialRowInds);\n showWarning(this, sprintf('OCIA:%s:NoTrialIndices', mfilename()), sprintf(...\n 'Problem with animal %s, day %s, session %s (%s): no trial index.\\n', ...\n animalID, dayID, sessID, sessNum));\n continue;\n end;\n avgStruct = struct();\n trialCountStruct = struct();\n DWLoadRow(this, trialRowInds(1), 'full');\n dims = str2dim(get(this, trialRowInds(1), 'dim'));\n \n % re-alignment to sound onset required\n pathToFirstTrial = get(this, trialRowInds(1), 'path');\n stimStartPath = regexprep(pathToFirstTrial, 'stim_trial1\\.mat', 'stimStartFrames.mat');\n % stimulus start defining file exists\n if exist(stimStartPath, 'file');\n stimStartFramesMat = load(stimStartPath);\n stimStartFrames = stimStartFramesMat.stimStartFrame;\n\n else\n stimStartFrames = [];\n showWarning(this, sprintf('OCIA:%s:NoStimStartFrames', mfilename()), sprintf(['Problem with animal %s, ', ...\n 'day %s, session %s (%s): cannot find stim start frames mat file at \"%s\". Skipping realigning.\\n'], ...\n animalID, dayID, sessID, sessNum, stimStartPath));\n end;\n \n % create average for each condition\n for iRow = max(iTrialStart, 1) : min(numel(trialRowInds), iTrialEnd);\n iDWRow = trialRowInds(iRow);\n \n % extract info and data for this row\n commentsForRow = get(this, iDWRow, 'comments');\n iTrial = str2double(get(this, iDWRow, 'runNum'));\n \n % check each trial type for a match\n for iTrialType = 1 : numel(trialTypeSaveName);\n trialTypeRegexp = trialTypesRegexp{iTrialType};\n trialType = trialTypeSaveName{iTrialType};\n % trial is a match for this type\n if ~isempty(regexp(commentsForRow, trialTypeRegexp, 'once'));\n % add to data structure\n [avgStruct, trialCountStruct] = addToDataStruct(this, iDWRow, animalID, dayID, sessID, sessNum, ...\n stimStartFrames, iTrial, fixedStartFrame, avgStruct, trialType, dims, trialCountStruct);\n end;\n \n % multiple trial types required\n if ~isempty(regexp(trialTypeRegexp, '_AND_', 'once'));\n multiTrialTypes = regexp(trialTypeRegexp, '_AND_', 'split');\n matchForEach = cellfun(@(triTy) ~isempty(regexp(commentsForRow, triTy, 'once')), multiTrialTypes);\n % all requirements of matching are met\n if all(matchForEach);\n % add to data structure\n [avgStruct, trialCountStruct] = addToDataStruct(this, iDWRow, animalID, dayID, sessID, ...\n sessNum, stimStartFrames, iTrial, fixedStartFrame, avgStruct, trialType, ...\n dims, trialCountStruct);\n \n end;\n end;\n \n end;\n \n % clean up by erasing data for this row\n DWFlushData(this, iDWRow, false, 'wfTrIm');\n end;\n \n % save the data for each condition\n for iTrialType = 1 : numel(trialTypeSaveName);\n trialType = trialTypeSaveName{iTrialType};\n % abort if no trials of this type\n if ~isfield(trialCountStruct, trialType) || trialCountStruct.(trialType) <= 0; continue; end;\n % divide by the number of trials\n N = trialCountStruct.(trialType);\n avgStruct.(trialType).aligned = avgStruct.(trialType).aligned ./ N;\n avgStruct.(trialType).unalign = avgStruct.(trialType).unalign ./ N;\n \n % save as \"tr_ave\" and \"N\" variable\n tr_ave = avgStruct.(trialType).unalign; %#ok\n trialPath = get(this, trialRowInds(1), 'path');\n save(regexprep(trialPath, 'stim_trial1', sprintf('cond_%s_average', trialType)), 'tr_ave', 'N');\n \n % save as \"tr_ave\" and \"N\" variable\n tr_ave = avgStruct.(trialType).aligned; %#ok\n trialPath = get(this, trialRowInds(1), 'path');\n save(regexprep(trialPath, 'stim_trial1', sprintf('cond_%s_average_aligned', trialType)), 'tr_ave', 'N');\n end;\n \n end;\n \nend\n\nfunction [avgStruct, trialCountStruct] = addToDataStruct(this, iDWRow, animalID, dayID, sessID, sessNum, ...\n stimStartFrames, iTrial, fixedStartFrame, avgStruct, trialType, dims, trialCountStruct)\n\n % make sur data is loaded\n DWLoadRow(this, iDWRow, 'full');\n dataForRow = getData(this, iDWRow, 'wfTrIm', 'data');\n imgDims = size(dataForRow);\n\n % re-alignment to sound onset required\n if ~isempty(stimStartFrames);\n % calculate frame shift\n stimStartFrameTrial = stimStartFrames(iTrial);\n nFramesDiff = fixedStartFrame - stimStartFrameTrial;\n if abs(nFramesDiff) > 10;\n showWarning(this, sprintf('OCIA:%s:AlignFrameRemoval', mfilename()), sprintf(['Problem with animal %s, ', ...\n 'day %s, session %s (%s): removing a lot of frames (%d) for realignment ...\\n'], ...\n animalID, dayID, sessID, sessNum, abs(nFramesDiff)));\n end;\n % not enough frame before sound\n dataForRowUnalign = dataForRow;\n if nFramesDiff > 0;\n dataForRow = cat(3, nan([imgDims(1:2), nFramesDiff]), dataForRow(:, :, 1 : (end - nFramesDiff)));\n % too many frames before sound\n elseif nFramesDiff < 0;\n dataForRow = cat(3, dataForRow(:, :, (abs(nFramesDiff) + 1) : end), nan([imgDims(1:2), abs(nFramesDiff)]));\n end;\n \n % otherwise use nans\n else\n dataForRowUnalign = nan(dims);\n\n end;\n\n % first trial of this type\n if ~isfield(avgStruct, trialType);\n avgStruct.(trialType).aligned = zeros(dims);\n avgStruct.(trialType).unalign = zeros(dims);\n trialCountStruct.(trialType) = 0;\n end;\n \n % add average values\n avgStruct.(trialType).aligned = avgStruct.(trialType).aligned + dataForRow;\n avgStruct.(trialType).unalign = avgStruct.(trialType).unalign + dataForRowUnalign;\n \n % add trial count\n trialCountStruct.(trialType) = trialCountStruct.(trialType) + 1;\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_analysis_wideField_drawCropRect.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_wideField_drawCropRect.m", "size": 820, "source_encoding": "utf_8", "md5": "f4f3787ccee041fd8eb5d85d86bace20", "text": "function OCIA_analysis_wideField_drawCropRect(this, ~, ~)\n% OCIA_analysis_wideField_drawCropRect - [no description]\n%\n% OCIA_analysis_wideField_drawCropRect(this)\n%\n% [No description]\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\n% remove previous rectangle\naxeChilds = get(this.GUI.handles.an.axe, 'Children');\ndelete(axeChilds(strcmp(get(axeChilds, 'Tag'), 'imrect')));\n\n% draw the ROI\nhROI = imrect(this.GUI.handles.an.axe);\nhROI.addNewPositionCallback(@(h)updateCropRect(this, h));\n\n% get position and store it\npos = roundn(hROI.getPosition(), 1);\nthis.an.wf.cropRect = pos;\n\n% update parameters\nANUpdatePlot(this, 'params');\n\n\nend\n\nfunction updateCropRect(this, newCropRect)\n this.an.wf.cropRect = roundn(newCropRect, 1);\n ANUpdatePlot(this, 'params');\nend\n \n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_analysis_getROIStat.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_getROIStat.m", "size": 1842, "source_encoding": "utf_8", "md5": "0108c7662da8e7c25a69f40e48834599", "text": "% get the grouping from the different variables\nfunction [ROIStat, description] = OCIA_analysis_getROIStat(ROIStatToCalc, respMethod, PSCaTracesStats, ...\n stimIDIndexes, stimIDs)\n \n% get the average responsiveness to all trials\nROIResps = reshape(nanmean(PSCaTracesStats.ROIRespTrial, 2), ...\n size(PSCaTracesStats.ROIRespTrial, 1), size(PSCaTracesStats.ROIRespTrial, 3));\n \n% select which ROI statistic to analyse\nswitch ROIStatToCalc;\n \n case 'responsiveness';\n ROIStat = ROIResps(stimIDIndexes, :)';\n % linearize the matrix\n ROIStat = ROIStat(:);\n\n description = sprintf('Responsiveness (%s %%DRR)', respMethod);\n \n case 'response time';\n \n ROIStat = PSCaTracesStats.ROIRespTime(stimIDIndexes, :)';\n % linearize the matrix\n ROIStat = ROIStat(:);\n description = 'Response time (sec)';\n \n case 'SI';\n \n % calculate SI\n ROIStat = (ROIResps(stimIDIndexes(2), :) - ROIResps(stimIDIndexes(1), :)) ...\n ./ (ROIResps(stimIDIndexes(1), :) + ROIResps(stimIDIndexes(2), :));\n description = sprintf('SI: %s (neg.) - %s (pos.)', stimIDs{stimIDIndexes});\n \n case 'd''';\n \n % calculate d''\n ROIStat = squeeze(...\n ( ...\n nanmean(PSCaTracesStats.ROIRespTrial(stimIDIndexes(2), :, :), 2) ...\n - nanmean(PSCaTracesStats.ROIRespTrial(stimIDIndexes(1), :, :), 2) ...\n ) ...\n ./ ...\n sqrt( ...\n 0.5 * nanstd(PSCaTracesStats.ROIRespTrial(stimIDIndexes(1), :, :), [], 2) .^ 2 ...\n + 0.5 * nanstd(PSCaTracesStats.ROIRespTrial(stimIDIndexes(2), :, :), [], 2) .^ 2) ...\n );\n description = sprintf('d'': %s (neg.) - %s (pos.)', stimIDs{stimIDIndexes});\n \nend;\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_analysis_getWhiskVectors.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_getWhiskVectors.m", "size": 1996, "source_encoding": "utf_8", "md5": "a3c25dc726e7ecc35017c2d86ec7ff70", "text": "%% #OCIA:AN:OCIA_analysis_caTraces_whiskvectors\nfunction [WAEnvs, WAAmp, WASetP, WAExpWhisk, WAFovWhisk] = OCIA_analysis_getWhiskVectors(this, ...\n rawWhiskTraces, whiskFrameRateCellArray)\n\nnRuns = numel(rawWhiskTraces);\n\n% define frequency bands\nExpwhisk_low_frequ = 7; % Hz frequ. band for exploratory whisking \nExpwhisk_up_frequ = 12; % Hz\nFovwhisk_low_frequ = 15; % Hz frequ. band for foveal whisking\nFovwhisk_up_frequ = 25; % Hz\nEnvWinSize = 0.3; % window size in seconds for envelope and sliding mean/amp calculation\n\n% loop through each run and calculate various whisking angle (WA) variables\nWAEnvs = cell(size(rawWhiskTraces)); % envelope (max - min)\nWAAmp = cell(size(rawWhiskTraces)); % amplitude (max)\nWASetP = cell(size(rawWhiskTraces)); % set point (mean angle)\nWAExpWhisk = cell(size(rawWhiskTraces)); % exploratory whisking\nWAFovWhisk = cell(size(rawWhiskTraces)); % foveal whisking\n\nparfor iRun = 1 : nRuns;\n \n whiskFrameRate = whiskFrameRateCellArray{iRun};\n \n % calculate the envelope\n whiskAngle = rawWhiskTraces{iRun};\n nWhiskFrames = size(whiskAngle, 2);\n winSize = round(EnvWinSize * whiskFrameRate);\n for iFrame = 1 : nWhiskFrames; \n r = iFrame - winSize : iFrame + winSize;\n r(r < 1 | r > nWhiskFrames) = [];\n WAEnvs{iRun}(iFrame) = max(whiskAngle(r)) - min(whiskAngle(r)); % Whisking envelope\n WAAmp{iRun}(iFrame) = max(whiskAngle(r)); % Whisking amplitude\n WASetP{iRun}(iFrame) = mean(whiskAngle(r)); % Whisker set point\n end;\n [~, bandpow1, bandpow2] = spectralDensityAnalysis(whiskAngle, 128, 127, 128, whiskFrameRate, ...\n Expwhisk_low_frequ, Expwhisk_up_frequ, Fovwhisk_low_frequ, Fovwhisk_up_frequ);\n \n % ...(whiskAngle, windowsiz, overlap, nfft, ...)\n WAExpWhisk{iRun} = bandpow1;\n WAFovWhisk{iRun} = bandpow2;\n \nend;\n\n\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_analysis_getGrouping.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_getGrouping.m", "size": 5378, "source_encoding": "utf_8", "md5": "71ab6791a9546bb97c7e85f287c452c3", "text": "% get the grouping from the different variables\nfunction [grouping, groupLabels] = OCIA_analysis_getGrouping(this, iDWRows, stimIDIndexes, selDispStimIDs, groupBy, ROINames, ROIPhases)\n\n% create the grouping variable\nswitch groupBy;\n case 'ROI';\n\n % remove the ROISet tag\n cleanROINames = regexprep(ROINames, 'RS\\d+_', '');\n uniqueCleanROINames = unique(cleanROINames, 'stable');\n % get the grouping from ROISet number\n grouping = cellfun(@(ROIName)find(strcmp(ROIName, uniqueCleanROINames)), cleanROINames);\n % expand the matrix for the stimulus types\n grouping = repmat(grouping, 1, numel(stimIDIndexes));\n % linearize the matrix\n grouping = grouping(:);\n % use the ROINames as group labels\n groupLabels = uniqueCleanROINames';\n\n case 'day';\n\n % use the \"ROIPhases\" cell-array if provided and no DataWatcher row indexes provided\n if exist('ROIPhases', 'var') && ~isempty(ROIPhases) && isempty(iDWRows);\n \n % remove the ROISet tag\n uniquePhases = unique(ROIPhases, 'stable');\n % get the grouping from ROI phase\n grouping = cellfun(@(ROIPhase)find(strcmp(ROIPhase, uniquePhases)), ROIPhases);\n % expand the matrix for the stimulus types\n grouping = repmat(grouping, 1, numel(stimIDIndexes));\n % linearize the matrix\n grouping = grouping(:);\n % use the ROINames as group labels\n groupLabels = uniquePhases;\n \n else\n \n % get the grouping from ROISet number\n grouping = cellfun(@(ROIName)str2double(regexprep(regexp(ROIName, 'RS\\d+_', 'match'), '[^\\d]', '')), ROINames);\n % get the days from the rows and from the ROISet IDs\n allDays = regexprep(unique(get(this, iDWRows, 'day')), '_', '');\n allROISetsDays = regexprep(unique(get(this, iDWRows, 'ROISet')), '_\\d+$', '');\n % re-map the grouping using the actual unique days\n for iROISetDay = 1 : numel(allROISetsDays);\n grouping(grouping == iROISetDay) = find(strcmp(allROISetsDays{iROISetDay}, allDays)); \n end;\n\n % expand the matrix for the stimulus types\n grouping = repmat(grouping, 1, numel(stimIDIndexes));\n % linearize the matrix\n grouping = grouping(:);\n\n % use different labels for the day groups\n% groupLabels = this.an.img.groupNames(unique(grouping));\n groupLabels = allROISetsDays(unique(grouping));\n \n end;\n\n case 'stimType';\n\n % split the stimulus IDs into stimulus ID and PSPerID\n splitStimIDs = cell(2, numel(selDispStimIDs));\n for iStimType = 1 : numel(selDispStimIDs);\n parts = regexp(selDispStimIDs{iStimType}, ' ', 'split');\n if numel(parts) > 2;\n partsString = regexprep(sprintf('%s-', parts{1 : end - 1}), '-$', '');\n parts = [partsString, parts(end)];\n end;\n splitStimIDs(:, iStimType) = parts;\n end;\n % extract the unique stimuli / PSPerID\n uniqueStims = unique(splitStimIDs(1, :), 'stable');\n \n % create a grouping for each stimulus type\n grouping = repmat((1 : numel(stimIDIndexes)), numel(ROINames), 1);\n % linearize the matrix\n grouping = grouping(:);\n \n % re-map the grouping indexes to make it only about the stimulus IDs and not the PSPerID\n for iStimType = 1 : numel(selDispStimIDs);\n grouping(grouping == iStimType) = find(strcmp(splitStimIDs(1, iStimType), uniqueStims));\n end;\n \n % use the stimulus IDs as group labels\n groupLabels = uniqueStims;\n\n case 'PSPer';\n\n % split the stimulus IDs into stimulus ID and PSPerID\n splitStimIDs = cell(2, numel(selDispStimIDs));\n for iStimType = 1 : numel(selDispStimIDs);\n parts = regexp(selDispStimIDs{iStimType}, ' ', 'split');\n if numel(parts) > 2;\n partsString = regexprep(sprintf('%s-', parts{1 : end - 1}), '-$', '');\n parts = [partsString, parts(end)];\n end;\n splitStimIDs(:, iStimType) = parts;\n end;\n % extract the unique stimuli / PSPerID\n uniquePSPer = unique(splitStimIDs(2, :), 'stable');\n \n % create a grouping for each stimulus type\n grouping = repmat((1 : numel(stimIDIndexes)), numel(ROINames), 1);\n % linearize the matrix\n grouping = grouping(:);\n \n % re-map the grouping indexes to make it only about the PSPerID and not the stimulus IDs\n for iStimType = 1 : numel(selDispStimIDs);\n grouping(grouping == iStimType) = find(strcmp(splitStimIDs(2, iStimType), uniquePSPer));\n end;\n \n % use the stimulus IDs as group labels\n groupLabels = uniquePSPer;\n\n case 'stimTypePSPer';\n\n % create a grouping for each stimulus type\n grouping = repmat((1 : numel(stimIDIndexes)), numel(ROINames), 1);\n % linearize the matrix\n grouping = grouping(:);\n % use the stimulus IDs as group labels\n groupLabels = selDispStimIDs';\n\n case 'none';\n\n % return empty vectors\n grouping = [];\n groupLabels = [];\n\nend;\n\nend\n"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_analysis_behav_getBehavVars.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_behav_getBehavVars.m", "size": 32382, "source_encoding": "utf_8", "md5": "7db800f203bd40f7c6c94b65743f703a", "text": "function [behavVars, rowIDs, colIDs] = OCIA_analysis_behav_getBehavVars(this, allBehavStructs, ...\n selectedLoadedBehavRows, includeEOTrials)\n% OCIA_analysis_behav_getBehavVars - [no description]\n%\n% [behavVars, rowIDs, colIDs] = OCIA_analysis_behav_getBehavVars(this, allBehavStructs, ...\n% selectedLoadedBehavRows, includeEOTrials)\n%\n% Extract the behavior variables from the input structures into a cell array.\n%\n% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)\n\n\n% count the number of strutures\nnBehavStructs = numel(allBehavStructs);\n\n% create a configuration cell-array for the different behavior variables with 3 + \"nBehavData\" + 2 columns:\n% { id, label, grouping options, plotting parameters, data for each structure, concatenated data (one value per trial), \n% concat. data without repetitions }\nbehavVars = { ...\n... id label grouping groupMethod plotParams (plot type, unit, color)\n 'behavInd', 'behav. file num.', { 'trial' }, '', { 'box', '', 'black' };\n 'date', 'date', { 'trial' }, '', { 'box' , '', 'black' };\n 'days', 'days', { 'trial' }, '', { 'box' , '', 'black' };\n 'time', 'time', { }, '', { 'scatter', 'hour', 'black' };\n 'session', 'session', { 'trial' }, '', { 'box' , '', 'black' };\n 'dateWithSession', 'date (with session)', { }, '', { 'scatter', '', 'black' };\n 'trialRange', 'used trial range', { }, '', { 'scatter', '', 'black' };\n 'nTrials', 'n. of trials', { 'run', 'session', 'date' }, 'sum', { 'scaline', 'trial', 'black' };\n 'resps', 'response', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', ' % ', 'black' };\n 'minRespTime', 'delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', [.8 .8 .2] };\n 'earliesAllowed', 'allowedEarlies', { 'run', 'session', 'date' }, 'mean', { 'scaline', ' % ', [.2 .8 .8] };\n% 'phase', 'training phase name', { 'trial' }, '', { 'box' , '', 'black' };\n% 'phaseGroup', 'training phase', { 'trial' }, '', { 'box' , '', 'black' };\n 'nogoPerc', 'NoGo percent', { 'run', 'session', 'date' }, 'mean', { 'scaline', ' % ', [.8 .2 .2] };\n 'animalID', 'animal ID', { 'trial' }, '', { 'box' , '', 'black' };\n 'stimMatrixRandomIndex', 'stim. matrix num.', { 'run' }, 'mean', { 'scatter', '', 'black' };\n 'respTypes', 'response type', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scatter', '', 'black' };\n 'respDelays', 'response delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', 'black' };\n% 'imagedTrials', 'imaged trials', { 'trial', }, 'sum', { 'box' , '', 'black' };\n 'startDelay', 'starting delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', 'black' };\n% 'spoutIn', 'spout delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', 'black' };\n 'lightCueOn', 'light delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', 'black' };\n 'nRewards', 'n. of rew. trials', { 'trial', 'run', 'session', 'date' }, 'sum', { 'scaline', 'trial', 'green' };\n% 'nRewardsEO', 'n. of EO rew. trials', { 'trial', 'run', 'session', 'date' }, 'sum', { 'scaline', 'trial', 'green' };\n% 'suppliedWater', 'supplied water', { 'session', 'date' }, 'max', { 'scaline', ' ml ', [0 0.5 1] };\n% 'rewardWater', 'reward water', { 'run', 'session', 'date' }, 'sum', { 'line' , ' ml ', 'cyan' };\n% 'water', 'total water', { 'run', 'session', 'date' }, 'sum', { 'line' , ' ml ', 'blue' };\n% 'weight', 'animal weight', { 'date' }, '', { 'scaline', ' g. ', 'black' };\n 'counts', 'performance counts', { }, '', { '' , '', '' };\n 'hitRate', 'hit rate', { 'trial', 'run', 'session', 'date' }, 'mean', { 'linesca', ' % ', 'green' };\n 'FARate', 'false alarm rate', { 'trial', 'run', 'session', 'date' }, 'mean', { 'linesca', ' % ', 'red' };\n 'earlies', 'earlies', { 'trial', 'run', 'session', 'date' }, 'mean', { 'linesca', ' % ', [0.2 0.5 1] };\n 'dprime', 'performance (d'')', { 'trial', 'run', 'session', 'date' }, 'max', { 'linesca', 'd'' ', 'blue' };\n};\nrowIDs = behavVars(:, 1); % extract the IDs\nbehavColIDs = regexp(regexprep(sprintf('%03d,', 1 : nBehavStructs), ',$', ''), ',', 'split');\ncolIDs = [{ 'id', 'label', 'grouping', 'groupMethod', 'plotParams' }, behavColIDs, { 'allDataRep', 'allData' }];\nnBehavVars = size(behavVars, 1); % count the number of variables (=> rows)\n% extend for each structure and for the concatenated data\nbehavVars(:, end + 1 : end + nBehavStructs + 2) = cell(nBehavVars, nBehavStructs + 2);\n\n% get the mice info file's content as a cell-array with one cell per line\nmiceInfoLines = readMiceInfoFile(this);\n\n% get all the starting time for each structure\nexpStartTimes = zeros(nBehavStructs, 1);\n% go through each behavior structure\nfor iBehav = 1 : nBehavStructs;\n % get the behavior data structure\n behavStruct = allBehavStructs{iBehav};\n % extract the experiment starting time as a \"datenum\"\n expStartTimes(iBehav) = unix2dn(behavStruct.expStartTime * 1000);\nend;\n\n% create the session indexes by clustering the times\nif nBehavStructs > 1;\n % get the date \"datenum\"\n expStartDates = datenum(datestr(expStartTimes, 'yyyy_mm_dd'), 'yyyy_mm_dd');\n % cluster the time (without the date)\n expStartTimesNoDate = expStartTimes - expStartDates;\n sessionIndexes = clusterdata(expStartTimesNoDate, 'maxclust', 2);\n\n % make sure the session labeled '1' is the one from the morning\n meanStartTimesForFirstSession = mean(expStartTimesNoDate(sessionIndexes == 1));\n meanStartTimesForSecondSession = mean(expStartTimesNoDate(sessionIndexes == 2));\n % if session 1 is later than session 2, swap them\n if meanStartTimesForFirstSession > meanStartTimesForSecondSession;\n sessionIndexes(sessionIndexes == 1) = 3;\n sessionIndexes(sessionIndexes == 2) = 1;\n sessionIndexes(sessionIndexes == 3) = 2;\n end;\nelse\n sessionIndexes = 1;\nend;\n\no('#%s(): gathering info about %d behavior files ...', mfilename(), nBehavStructs, 2, this.verb);\n\n \n% go through each behavior variable\nfor iVar = 1 : nBehavVars;\n \n % get the current behavior variable\n behavVarID = get(this, iVar, 'id', behavVars, colIDs);\n \n % go through each behavior structure\n for iBehav = 1 : nBehavStructs;\n \n % get the behavior index as string\n iBehavStr = sprintf('%03d', iBehav);\n % get the behavior data structure\n behavStruct = allBehavStructs{iBehav};\n % get the starting time for this structure\n expStartTime = expStartTimes(iBehav);\n % get the number of trials for this structure as the last valid trial having a trial ending time\n nTotTrials = find(~isnan(behavStruct.times.end) & ~isnan(behavStruct.resps), 1, 'last');\n % get early-on trials\n EOTrials = ~isnan(behavStruct.autoRewardGiven) & behavStruct.autoRewardGiven > 0 ...\n & strcmp(behavStruct.autoRewardModes, 'EarlyOn');\n nEOTrials = nansum(EOTrials);\n % remove early on auto-reward trials if required\n if ~includeEOTrials;\n nTotTrials = nTotTrials - nEOTrials;\n end;\n \n switch behavVarID;\n\n %% trialRange\n case 'trialRange';\n\n % by default, use all trials\n trialRange = 1 : nTotTrials;\n\n % if the phase was is not \"quite wakefulness\" (no reward and no go stimulation),\n % then try to remove the invalid trials\n if ~strcmp(behavStruct.phase, 'QW');\n \n % get the current day and session\n currDay = get(this, find(strcmp(rowIDs, 'date')), iBehavStr, behavVars, colIDs);\n currSession = get(this, find(strcmp(rowIDs, 'session')), iBehavStr, behavVars, colIDs);\n\n % if first structure, consider this as a first of session\n if iBehav == 1;\n isFirstStructFromSession = true; \n\n % otherwise check the previous structure's day and session\n else\n % get the day and session from the previous structure\n prevDay = get(this, find(strcmp(rowIDs, 'date')), sprintf('%03d', iBehav - 1), behavVars, colIDs);\n prevSession = get(this, find(strcmp(rowIDs, 'session')), sprintf('%03d', iBehav - 1), behavVars, colIDs);\n % this is the first file from session only if either the day or the session does not match\n isFirstStructFromSession = ~strcmp(prevDay, currDay) || prevSession ~= currSession; \n\n end;\n\n % if last structure, consider this as an end of session\n if iBehav == nBehavStructs;\n isLastStructFromSession = true;\n\n % otherwise check the previous structure's day and session\n else\n % get the day and session from the next structure\n nextDay = get(this, find(strcmp(rowIDs, 'date')), sprintf('%03d', iBehav + 1), behavVars, colIDs);\n nextSession = get(this, find(strcmp(rowIDs, 'session')), sprintf('%03d', iBehav + 1), behavVars, colIDs);\n % this is the first file from session only if either the day or the session does not match\n isLastStructFromSession = ~strcmp(nextDay, currDay) || nextSession ~= currSession;\n\n end; \n\n % if this is the first structure from a session, remove some trials at the begining\n if isFirstStructFromSession && ~isempty(this.an.be.nTrialsSkip);\n o('%s#: %s is first structure from session (%s, %d).', mfilename(), iBehavStr, currDay, ...\n currSession, 4, this.verb);\n trialRange(1 : min(this.an.be.nTrialsSkip(1), nTotTrials)) = []; \n end;\n\n % if this is the last structure from a session, remove some trials at the end \n if isLastStructFromSession && ~isempty(this.an.be.nTrialsSkip);\n o('%s#: %s is last structure from session (%s, %d).', mfilename(), iBehavStr, currDay, ...\n currSession, 4, this.verb);\n trialRange(max(end - this.an.be.nTrialsSkip(2) + 1, 1) : end) = [];\n\n end;\n\n % if this is the last structure from a session, remove some trials at the end \n if isLastStructFromSession && ~isempty(this.an.be.nMinRespTrialSkip); \n % get the response types\n respTypes = behavStruct.respTypes(trialRange);\n % get the parameters for the ending non-responsive ratio mesure\n minNResps = this.an.be.nMinRespTrialSkip(1);\n nLastTrial = this.an.be.nMinRespTrialSkip(2);\n % if there are enough trials to calculate the non-responsive trials\n if numel(respTypes) > nLastTrial;\n % counter for the number of trials removed\n nTrialsRemoved = 0;\n % get the last trials\n lastRespTypes = respTypes(end - nLastTrial + 1 : end);\n % get how many response there was in these last trials\n nResps = sum(lastRespTypes == 1 | lastRespTypes == 3);\n % as long as the number of responsive trials is not enough and there are enough trials\n % to calculate the number of responses\n while nResps < minNResps && numel(respTypes) > nLastTrial;\n % remove the last trial\n respTypes(end) = [];\n % update the counter\n nTrialsRemoved = nTrialsRemoved + 1;\n % get the \"new\" last trials\n lastRespTypes = respTypes(end - nLastTrial + 1 : end);\n % get the \"new\" number of response(s) in the last trials\n nResps = sum(lastRespTypes == 1 | lastRespTypes == 3);\n end;\n % exclude the last trials\n trialRange(end - nTrialsRemoved + 1 : end) = [];\n end;\n end;\n end; % end of QW phase check\n\n % if Early-on trials should not be included\n if ~includeEOTrials;\n % remove early on trials\n EOTrialIndices = find(EOTrials);\n trialRange(ismember(trialRange, EOTrialIndices)) = [];\n \n end;\n \n % store the trial range\n data = trialRange; \n\n %% nTrials\n case 'nTrials';\n\n % update the actual number of trials\n trialRange = get(this, find(strcmp(rowIDs, 'trialRange')), iBehavStr, behavVars, colIDs);\n\n % store the number of trials\n data = zeros(1, nTotTrials);\n data(trialRange) = 1;\n\n %% resps, phase, respDelays, respTypes, animalID, stimMatrixRandomIndex\n case { 'resps', 'phase', 'respDelays', 'respTypes', 'animalID', 'stimMatrixRandomIndex' };\n % if the behavior variable is stored in the structure's root, extract it from there\n if isfield(behavStruct, behavVarID);\n data = behavStruct.(behavVarID);\n else\n data = NaN;\n end; \n\n %% lightCueOn, spoutIn, startDelay\n case { 'lightCueOn', 'spoutIn', 'startDelay' };\n % if the behavior variable is stored in the structure's root, extract it from there\n if isfield(behavStruct, 'times') && isfield(behavStruct.times, behavVarID);\n data = behavStruct.times.(behavVarID);\n % unless this variable is the starting delay, subtract the starting delay to have a time in\n % seconds from the trial start\n if ~strcmp(behavVarID, 'startDelay') && isfield(behavStruct.times, 'startDelay');\n data = data - behavStruct.times.startDelay;\n end;\n else\n data = NaN;\n end; \n \n %% phaseGroup\n case 'phaseGroup';\n phase = get(this, find(strcmp(rowIDs, 'phase')), iBehavStr, behavVars, colIDs);\n if regexp(phase, '^Q', 'once');\n data = 'baseline';\n elseif regexp(phase, '^[ABL]', 'once');\n data = 'shaping';\n elseif regexp(phase, '^[CDE][A-Z]\\d', 'once');\n data = 'discrimination';\n else\n data = '[unknown]';\n end\n \n %% nogoPerc\n case 'nogoPerc';\n data = 100 * nanmean(~ismember(behavStruct.stims, behavStruct.config.tone.goStim));\n \n %% behavInd\n case 'behavInd';\n % store the behavior index\n data = iBehav;\n\n %% date\n case 'date';\n % store the date as string\n data = datestr(expStartTime, 'mm_dd');\n\n %% days\n case 'days';\n % store the days as string of number of days since experiment start\n firstDateVec = datevec(get(this, find(strcmp(rowIDs, 'date')), '001', behavVars, colIDs), 'mm_dd');\n expStartVec = datevec(datestr(expStartTime, 'yyyy_mm_dd'), 'yyyy_mm_dd');\n data = sprintf('%02d', 1 + etime(expStartVec, firstDateVec) / 3600 / 24);\n \n %% dateWithSession\n case 'dateWithSession';\n % get the session\n session = get(this, find(strcmp(rowIDs, 'session')), iBehavStr, behavVars, colIDs);\n % store the date as string\n data = [datestr(expStartTime, 'mm_dd'), ' ', iff(session == 1, 'am', 'pm')];\n\n %% time\n case 'time';\n % get the starting hour and minute\n startHour = str2double(datestr(expStartTime, 'HH'));\n startMinute = str2double(datestr(expStartTime, 'MM'));\n % store the time as a decimal hour\n data = startHour + startMinute / 60;\n\n %% session\n case 'session';\n % use the clustered sessions\n data = sessionIndexes(iBehav);\n\n %% imagedTrials\n case 'imagedTrials';\n % get the behavior ID of this structure\n behavRowID = get(this, iBehav, 'behav', selectedLoadedBehavRows);\n % check whether there is ANY imaging row\n imagingRows = DWFilterTable(this, 'rowType = Imaging data');\n % some imaging rows are present\n if ~isempty(imagingRows);\n % try to find imaging rows that have the same behavior ID\n imagingRows = DWFilterTable(this, sprintf('behav = %s AND rowType = Imaging data', behavRowID));\n % get the trial number of these imaging rows\n imagedTrialNumbers = str2double(get(this, 'all', 'runNum', imagingRows));\n % find and store which trials of the behavior structure have been imaged\n data = double(arrayfun(@(i)ismember(i, imagedTrialNumbers), 1 : nTotTrials));\n % get the spot number as index for the data\n if ~isempty(imagingRows);\n data(data > 0) = str2double(regexprep(get(this, 'all', 'spot', imagingRows), 'spot', ''));\n end;\n \n % no imaging rows, try to find it by day\n else\n % get the date\n dateForRowNoYear = get(this, find(strcmp(rowIDs, 'date')), iBehavStr, behavVars, colIDs);\n dateForRow = [datestr(expStartTime, 'yyyy'), '_', dateForRowNoYear];\n % find if there are any spot folders for this day\n dateSpotPath = sprintf('%smou_bl_%s/%s/spot*', this.path.localData, behavStruct.animalID, dateForRow);\n spotFolders = dir(dateSpotPath);\n if ~isempty(spotFolders);\n data = ones(nTotTrials, 1);\n else\n data = zeros(nTotTrials, 1);\n end;\n \n end;\n \n %% nRewards\n case 'nRewards';\n % store the rewarded trials\n data = double(~isnan(behavStruct.times.end) & ~isnan(behavStruct.resps) & behavStruct.respTypes == 1);\n\n %% nRewardsEO\n case 'nRewardsEO';\n % store the EO rewarded trials\n if includeEOTrials;\n data = double(~isnan(behavStruct.times.end) & ~isnan(behavStruct.resps) & behavStruct.respTypes == 1);\n data(~EOTrials) = 0;\n else\n data = [];\n end;\n\n %% suppliedWater\n case 'suppliedWater';\n % if some info was found\n if ~isempty(miceInfoLines);\n % get the current structure's date in the format of the mice info file, with an \"am/pm\" label \n % depending on the session\n dateToSearch = ['-' datestr(expStartTime, 'yymmdd') iff(session == 1, 'am', 'pm')];\n % get the lines that have these date\n lineIndexes = find(cellfun(@(cont)~isempty(regexp(cont, dateToSearch, 'once')), miceInfoLines));\n % if no line found, assume no water was supplied\n if isempty(lineIndexes);\n suppliedWater = 0;\n % if a line was found, get the amount of supplied water\n else\n % get the animal index of this structure\n animalIndex = str2double(behavStruct.animalID(end - 1 : end));\n % get the line after the date line\n suppliedWaterCellIndex = lineIndexes(animalIndex) + 1;\n % extract the amount of supplied water\n suppliedWater = str2double(regexp(miceInfoLines{suppliedWaterCellIndex}, '(\\d\\.\\d+)', 'match'));\n end;\n % store the supplied water\n data = suppliedWater;\n % no info, no data\n else\n suppliedWater = 0;\n data = NaN;\n end;\n \n %% rewardWater\n case 'rewardWater';\n % get the list of rewarded trials as a logical array of length \"nTrials\"\n isReward = ~isnan(behavStruct.times.end) & ~isnan(behavStruct.resps) & behavStruct.respTypes == 1;\n % get the amount of water received on trial using the opening-time <=> water amount conversion ( multiply by 3 ):\n % 0.02s opening = 0.006ul water, 0.03s opening = 0.009 ul water\n waterReward = isReward * behavStruct.params.rewDur * 0.3;\n % store the rewarded water\n data = waterReward;\n\n %% water\n case 'water';\n % store the total water as the sum of the reward water and the supplied water\n data = waterReward + suppliedWater / numel(waterReward);\n\n %% weight\n case 'weight';\n % if some info was found\n if ~isempty(miceInfoLines);\n % get the current structure's date in the format of the mice info file\n dateToSearch = [datestr(expStartTime, 'yymmdd'), '\\s+'];\n % get the lines that have these date\n lineIndexes = find(cellfun(@(cont)~isempty(regexp(cont, dateToSearch, 'once')), miceInfoLines));\n % if no line found, use NaN as weight\n if isempty(lineIndexes);\n data = NaN;\n % if a line was found, get the weight from it\n else\n % get the line of the weights (if several lines, take the last one)\n weightsLine = miceInfoLines{lineIndexes(end)};\n % try to extract the weight numbers\n weightHits = str2double(regexprep(regexp(weightsLine, '\\s\\d{2}\\s?', 'match'), '\\s', ''));\n % if no extraction possible, use NaN as weight\n if isempty(weightHits);\n data = NaN;\n % if a match was found, get the weight\n else\n % get the animal index of this structure\n animalIndex = str2double(behavStruct.animalID(end));\n % take the weight of that animal\n data = weightHits(animalIndex);\n end;\n end;\n % no info, no data\n else\n data = NaN;\n end;\n\n %% counts\n case 'counts';\n % analyse the response types\n data = analyseBehavPerf(behavStruct.respTypes, [], [], 0);\n\n %% hitRate\n case 'hitRate';\n % get the analysis of the response types\n counts = get(this, find(strcmp(rowIDs, 'counts')), iBehavStr, behavVars, colIDs);\n % store the percent of go trials on target trial\n data = counts.TGOP;\n\n %% FARate\n case 'FARate';\n % get the analysis of the response types\n counts = get(this, find(strcmp(rowIDs, 'counts')), iBehavStr, behavVars, colIDs);\n % store the percent of go trials on non-target trial\n data = counts.NTGOP;\n\n %% dprime\n case 'dprime';\n % get the analysis of the response types\n counts = get(this, find(strcmp(rowIDs, 'counts')), iBehavStr, behavVars, colIDs);\n % store the dprime value for this structure\n data = counts.DPRIME;\n\n %% earlies\n case 'earlies';\n % get the analysis of the response types\n counts = get(this, find(strcmp(rowIDs, 'counts')), iBehavStr, behavVars, colIDs);\n % store the dprime value for this structure\n data = counts.INVALIDP;\n\n %% minRespTime\n case 'minRespTime';\n data = behavStruct.times.respMin - behavStruct.times.startDelay;\n \n %% earliesAllowed\n case 'earliesAllowed';\n if isfield(behavStruct.config.training, 'allowEarlyLicks');\n data = behavStruct.config.training.allowEarlyLicks * 100;\n else\n data = NaN;\n end;\n\n %% OTHERWISE\n % if variable is not found, skip and show warning\n otherwise\n data = [];\n showWarning(this, 'OCIA:OCIA_analysis_behav_dprime:UnknownBehavVar', ...\n sprintf('Unknown behavior variable: \"%s\". Skipping it.', behavVarID));\n\n end; % end of behavior variable ID switch\n \n % if data has nTrials values, apply the trial range filtering\n if isnumeric(data) && numel(data) > 1 && ~strcmp(behavVarID, 'trialRange');\n trialRange = get(this, find(strcmp(rowIDs, 'trialRange')), iBehavStr, behavVars, colIDs);\n try\n data = data(trialRange);\n catch\n o('stop', 0, 0);\n end;\n end; \n \n % actually store the behavior variable\n behavVars = set(this, iVar, iBehavStr, data, behavVars, colIDs); \n \n end; % end of behavior structures loop\nend; % end of behavior variable loop\n\n%% create the concatenated data for all structures\n% create a concatenated data where each variable has a value for each trial\n% go through each behavior structure\nfor iBehav = 1 : nBehavStructs;\n \n % get the behavior index as string\n iBehavStr = sprintf('%03d', iBehav);\n % get the number of trials\n nTrials = sum(get(this, find(strcmp(rowIDs, 'nTrials')), iBehavStr, behavVars, colIDs));\n \n % go through each behavior variable\n for iVar = 1 : nBehavVars;\n \n % get the data for this structure and this variable\n data = get(this, iVar, iBehavStr, behavVars, colIDs);\n % get all the data for this variable with one value per trial\n allDataRep = get(this, iVar, 'allDataRep', behavVars, colIDs);\n % get all the data for this variable without repetition\n allData = get(this, iVar, 'allData', behavVars, colIDs);\n \n % if data is a string, concatenate with a cell array of \"nTrials\" times the string\n if ischar(data);\n allDataRep = [ allDataRep repmat( { data }, 1, nTrials) ]; %#ok\n allData = [ allData { data } ]; %#ok\n \n % if data is a numeric of length 1, concatenate with a replicaton of \"nTrials\" times the data\n elseif isnumeric(data) && numel(data) == 1;\n allDataRep = [ allDataRep repmat( data, 1, nTrials) ]; %#ok\n allData = [ allData data ]; %#ok\n \n % if data is a numeric of length \"nTrials\", concatenate the data itself\n elseif isnumeric(data) && size(data, 1) == nTrials;\n allDataRep = [ allDataRep data' ]; %#ok\n allData = [ allData data' ]; %#ok\n \n % if data is a numeric of length \"nTrials\", concatenate the data itself\n elseif isnumeric(data) && size(data,2) == nTrials;\n allDataRep = [ allDataRep data ]; %#ok\n allData = [ allData data ]; %#ok\n \n % otherwise show a warning and use NaNs\n else\n allDataRep = [ allDataRep nan(1, nTrials) ]; %#ok\n allData = [ allData NaN ]; %#ok\n % if data is not empty, show a warning\n if ~isempty(data) && ~isstruct(data);\n showWarning(this, 'OCIA:OCIA_analysis_behav_getBehavVars:BadSizeBehavVar', ...\n sprintf('Behavior variable \"%s\" has a bad size in structure %02d: %d x %d (nTrials = %02d). Using NaNs.', ...\n behavVars{iVar, 1}, iBehav, size(data), nTrials));\n end;\n \n end;\n \n % store back the concatenated data\n % get all the data for this variable with one value per trial\n behavVars = set(this, iVar, 'allDataRep', { allDataRep }, behavVars, colIDs);\n % get all the data for this variable without repetition\n behavVars = set(this, iVar, 'allData', { allData }, behavVars, colIDs);\n\n end; % end of behavior variable loop\nend; % end of behavior structures loop\n\nend\n\nfunction miceInfoLines = readMiceInfoFile(this)\n% extract the lines from the mice info file\n\n% open file\nmiceInfoFilePath = [this.path.localData this.an.be.miceInfoFilePath];\nfID = fopen(miceInfoFilePath);\n\nif fID == -1;\n miceInfoLines = []; % return nothing\n showWarning(this, 'OCIA:OCIA_analysis_behav_dprime:CannotReadMiceInfoLine', ...\n sprintf('Could not read the \"MiceInfo\" file at \"%s\". Skipping it.', miceInfoFilePath));\n return;\nend;\n\n% allocate a cell array for the lines\nmiceInfoLines = cell(1000, 1);\n\n% read all lines\ni = 1;\nmiceInfoLines{i} = fgetl(fID); i = i + 1;\nwhile ischar(miceInfoLines{i - 1});\n miceInfoLines{i} = fgetl(fID); i = i + 1;\nend;\n\n% close the file\nfclose(fID);\n\n% remove empty or numeric lines\nmiceInfoLines(cellfun(@isempty, miceInfoLines)) = [];\nmiceInfoLines(cellfun(@isnumeric, miceInfoLines)) = [];\n\n\nend"} +{"plateform": "github", "repo_name": "HelmchenLabSoftware/OCIA-master", "name": "OCIA_parseNotebookFile_H45Balazs.m", "ext": ".m", "path": "OCIA-master/caImgAnalysis/OCIA/custom/parseNotebook/OCIA_parseNotebookFile_H45Balazs.m", "size": 9607, "source_encoding": "utf_8", "md5": "0c5a917a0ff89436458c3f52e1cb6233", "text": "function notebookInfo = OCIA_parseNotebookFile_H45Balazs(notebookFilePath)\n\n% written by B. Laurenczy - 2013/10/15\n\n%% init variables\nnotebookInfo = cell(1, 14);\n% notebookInfo = cell(1, 10);\niRow = 1;\nskipLineRead = false;\n% regular expression patterns\n% mouseIDPattern = '^mou_[db]l_\\d{6}_\\d{2}$';\nmouseIDPattern = '^\\w+$';\nheaderPattern = '^(?sp\\d{2})(?[^_ ]+)?_?(?\\d+)?(?[\\w \\/-,\\.]+)?$';\ndateTimePattern = '^(?\\d{4}_\\d{2}_\\d{2})__(?