plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
BrainardLab/TeachingCode-master
GLW_Gabor.m
.m
TeachingCode-master/GLWindowExamples/GLW_Gabor.m
4,810
utf_8
1d932035a25694b0cc0366af7fae8500
function GLW_Gabor % GLW_Gabor Demonstrates how to show a gabor patch in GLWindow. % % Syntax: % GLW_Gabor % % Description: % The function createGabor at the end does the work of % creating the gabor patch. % % Also demonstrated is how to use the PTB calibration routines % to gamma correct the gabor. % % Press - 'd' to dump image of window into a file % - 'q' to quit % 12/5/12 dhb Wrote it from code lying around, in part due to Adam Gifford. try % Choose the last attached screen as our target screen, and figure out its % screen dimensions in pixels. Using these to open the GLWindow keeps % the aspect ratio of stuff correct. d = mglDescribeDisplays; screenDims = d(end).screenSizePixel; % Open the window. win = GLWindow('SceneDimensions', screenDims,'windowId',length(d)); win.open; % Load a calibration file for gamma correction. Put % your calibration file here. calFile = 'PTB3TestCal'; S = WlsToS((380:4:780)'); load T_xyz1931 T_xyz = SplineCmf(S_xyz1931,683*T_xyz1931,S); igertCalSV = LoadCalFile(calFile); igertCalSV = SetGammaMethod(igertCalSV,0); igertCalSV = SetSensorColorSpace(igertCalSV,T_xyz,S); % Draw a neutral background at roughly half the % dispaly maximum luminance. bgrgb = [0.5 0.5 0.5]'; bgRGB1 = PrimaryToSettings(igertCalSV,bgrgb); win.BackgroundColor = bgRGB1'; win.draw; % Add central fixation cross, just for fun win.addLine([-20 0], [20 0], 3, [1 1 1],'Name','fixHorz'); win.addLine([0 20], [0 -20], 3, [1 1 1],'Name', 'fixVert'); % Create two gabor patches with specified parameters pixelSize = 400; contrast1 = 0.75; contrast2 = 0.25; sf1 = 6; sf2 = 3; sigma1 = 0.1; sigma2 = 0.2; theta1 = 0; theta2 = 75; phase1 = 90; phase2 = 0; xdist = 400; ydist = 0; gabor1rgb = createGabor(pixelSize,contrast1,sf1,theta1,phase1,sigma1); gabor2rgb = createGabor(pixelSize,contrast2,sf2,theta2,phase2,sigma2); % Gamma correct [calForm1 c1 r1] = ImageToCalFormat(gabor1rgb); [calForm2 c2 r2] = ImageToCalFormat(gabor2rgb); [RGB1] = PrimaryToSettings(igertCalSV,calForm1); [RGB2] = PrimaryToSettings(igertCalSV,calForm2); gabor1RGB = CalFormatToImage(RGB1,c1,r1); gabor2RGB = CalFormatToImage(RGB2,c2,r2); % Add to display and draw. One is on left and the other on the right. win.addImage([-xdist ydist], [pixelSize pixelSize], gabor1RGB, 'Name','leftGabor'); win.addImage([xdist ydist], [pixelSize pixelSize], gabor2RGB, 'Name','rightGabor'); win.enableObject('leftGabor'); win.enableObject('rightGabor'); win.draw; % Wait for a key to quit ListenChar(2); FlushEvents; while true win.draw; key = GetChar; switch key % Quit case 'q' break; case 'd' win.dumpSceneToTiff('GLGabors.tif'); otherwise break; end end % Clean up and exit win.close; ListenChar(0); % Error handler catch e ListenChar(0); if ~isempty(win) win.close; end rethrow(e); end function theGabor = createGabor(meshSize,contrast,sf,theta,phase,sigma) % % Input % meshSize: size of meshgrid (and ultimately size of image). % Must be an even integer % contrast: contrast on a 0-1 scale % sf: spatial frequency in cycles/image % cycles/pixel = sf/meshSize % theta: gabor orientation in degrees, clockwise relative to positive x axis. % theta = 0 means horizontal grating % phase: gabor phase in degrees. % phase = 0 means sin phase at center, 90 means cosine phase at center % sigma: standard deviation of the gaussian filter expressed as fraction of image % % Output % theGabor: the gabor patch as rgb primary (not gamma corrected) image % Create a mesh on which to compute the gabor if rem(meshSize,2) ~= 0 error('meshSize must be an even integer'); end res = [meshSize meshSize]; xCenter=res(1)/2; yCenter=res(2)/2; [gab_x gab_y] = meshgrid(0:(res(1)-1), 0:(res(2)-1)); % Compute the oriented sinusoidal grating a=cos(deg2rad(theta)); b=sin(deg2rad(theta)); sinWave=sin((2*pi/meshSize)*sf*(b*(gab_x - xCenter) - a*(gab_y - yCenter)) + deg2rad(phase)); % Compute the Gaussian window x_factor=-1*(gab_x-xCenter).^2; y_factor=-1*(gab_y-yCenter).^2; varScale=2*(sigma*meshSize)^2; gaussianWindow = exp(x_factor/varScale+y_factor/varScale); % Compute gabor. Numbers here run from -1 to 1. theGabor=gaussianWindow.*sinWave; % Convert to contrast theGabor = (0.5+0.5*contrast*theGabor); % Convert single plane to rgb theGabor = repmat(theGabor,[1 1 3]);
github
BrainardLab/TeachingCode-master
GLW_Mouse.m
.m
TeachingCode-master/GLWindowExamples/GLW_Mouse.m
5,836
utf_8
fa2bd80d702af2e7d6a36896e5e0834e
function GLW_Mouse(fullScreen) % GLW_Mouse Shows how to capture/set the mouse with GLWindow. % % Syntax: % GLW_Mouse % GLW_Mouse(false) % % Description: % Demonstrates how to capture mouse position and button clicks and how to % set the mouse position while using GLWindow. Mouse functionality is % provided by the MGL libraries. At the beginning of the program the mouse % is forced to the middle of the display. Clicking the mouse prints out the % RGB value of the pixel that was clicked if using the system mouse cursor. % % If the rendered cursor is enabled, detection of the pixel values isn't % possible without doing some geometry calculations or reading non RGB pixel % data, which this example doesn't get into. % % Bring the cursor back into the Matlab command window and hit 'q' to % quit. % % Input: % fullScreen (logical) - Toggles fullscreen mode on/off. Defaults to true. % This global lets us access some low level OpenGL values. global GL; if nargin == 0 fullScreen = true; end % Dimensions of our GLWindow scene. screenDimsCm = [48 30]; % If we want to display the cursor as a dot instead of the system cursor, % enable this flag. The consequence of not using the system cursor and instead % using a rendered cursor is that it's harder to get the underlying RGB values % and we don't do that here. useSystemCursor = true; % Create the GLWindow object. win = GLWindow('FullScreen', logical(fullScreen), 'SceneDimensions', screenDimsCm, ... 'HideCursor', ~useSystemCursor); try % Add a blue oval. win.addOval([0 0], [5 5], [0 0 1], 'Name', 'square'); if ~useSystemCursor % Add a small oval to represent our mouse position. Add this last % to your GLWindow so that it is always on top of your other % objects. win.addOval([0 0], [0.25 0.25], [1 0 0], 'Name', 'mouse'); end % Open up the display. win.open; % Store the pixel dimensions of the display. We'll use this later to % convert pixel values into SceneDimensions values. screenDimsPx = win.DisplayInfo(win.WindowID).screenSizePixel; % Enable keyboard capture. ListenChar(2); FlushEvents; % Flag to keep track of mouse button state. alreadyPressed = false; % Force the mouse to the center of the screen. The mouse coordinate % system is in pixels, with lower left as 0,0 and increasing to the % right and upwards. This coordinate system differs from that used to % draw objects, which we agree is irritating. fprintf('- Moving mouse to center of the display.\n'); mglSetMousePosition(screenDimsPx(1)/2, screenDimsPx(2)/2, win.WindowID); % Loop continuously until 'q' is pressed. keepLooping = true; while keepLooping if CharAvail switch GetChar case 'q' keepLooping = false; end else % Get the current mouse state. The mouse state has 3 fields: % buttons, x, y. x and y will give you the horizontal and % vertical pixel position of the mouse relative to the % specified screen where (0,0) is the bottom left corner of the % display. The GLWindow object contains a property 'WindowID' % that gives us the target screen for mglGetMouse. mouseInfo = mglGetMouse(win.WindowID); % Look to see if the user is pressing a button. We keep track % of button state so that we don't register the same button % press multiple times. if mouseInfo.buttons > 0 && ~alreadyPressed if useSystemCursor % Print out the RGB value of the pixel the mouse was on. % To do this we make a low level OpenGL call to read pixels % straight from the framebuffer. This call also returns % the alpha (transparency) value as the 4th value in the % return vector. if (mouseInfo.x > 0 & mouseInfo.y > 0) glReadBuffer(GL.FRONT); pxRGBA = squeeze(glReadPixels(mouseInfo.x, mouseInfo.y, 1, 1, GL.RGB, GL.UNSIGNED_BYTE)) / 255; fprintf('- Pixel at position %0.1f, %0.1f in RGB: [%g, %g, %g]\n', mouseInfo.x, mouseInfo.y ,pxRGBA(1), pxRGBA(2), pxRGBA(3)); glReadBuffer(GL.BACK); end else fprintf('- Mouse clicked at pixel (%d, %d)\n', mouseInfo.x, mouseInfo.y); end % Toggle that the button is being pressed. alreadyPressed = true; elseif mouseInfo.buttons == 0 % If the button isn't currently being pressed we can turn % off the alreadyPressed flag. alreadyPressed = false; end if ~useSystemCursor % Move our circle to the position of the mouse so it looks like % we're moving around a cursor. We first need to put the % mouse pixel coordinates into the same units as % SceneDimensions in our GLWindow object. There's a short % function at the bottom of this file that does this. mousePos = px2cm([mouseInfo.x mouseInfo.y], screenDimsPx, screenDimsCm); win.setObjectProperty('mouse', 'Center', mousePos); end % Render the scene. win.draw; end end % Clean up. ListenChar(0); win.close; catch e ListenChar(0); win.close; rethrow(e); end function cmCoords = px2cm(pxCoords, screenDimsPx, screenDimsCm) % px2cm - Converts a position in pixels to centimeters. % % Syntax: % cmCoords = px2cm(pxCoords, screenDimsPx, screenDimsCm) % % Input: % pxCoords (Mx2) - Pixel coordinates. % screenDimsPx (1x2) - Screen dimensions in pixels. % screenDimsCm (1x2) - Screen dimensions in centimeters. % % Output: % cmCoords (Mx2) - Coordinates in centimeters. if nargin ~= 3 error('Usage: EyeTracker.px2cm(pxCoords, screenDimsPx, screenDimsCm)'); end cmCoords = zeros(size(pxCoords)); cmCoords(:,1) = pxCoords(:,1) * screenDimsCm(1) / screenDimsPx(1) - screenDimsCm(1)/2; cmCoords(:,2) = -screenDimsCm(2)/2 + pxCoords(:,2) * screenDimsCm(2) / screenDimsPx(2);
github
BrainardLab/TeachingCode-master
GLW_Text.m
.m
TeachingCode-master/GLWindowExamples/GLW_Text.m
3,299
utf_8
2c62be36a85ef53bcb2a78bba3193d3d
function GLW_Text(fullScreen) % GLW_Text Demonstrates how to show text with GLWindow % % Syntax: % GLW_Text % GLW_Text(fullScreen) % % Description: % Opens a window and shows the string 'red' on the screen. % % Press - 'r' to change the word % - 'c' to change the color of the text % - 'e' to enable the text (i.e. display it) % - 'd' to disable the text (i.e. hide it) % - 'q' to quit % % Input: % fullScreen (logical) - If true, the last screen attached to the computer % will be opened in fullscreen mode. If false, a regular window is opened % on the main screen. Defaults to true. error(nargchk(0, 1, nargin)); if ~exist('fullScreen', 'var') fullScreen = true; end % We can set the coordinate range of our OpenGL window. sceneDimensions = [50 30]; % Background color (RGB) of the window. bgRGB = [0 0 0]; % Create the GLWindow object. win = GLWindow('FullScreen', fullScreen, ... 'SceneDimensions', sceneDimensions, ... 'BackgroundColor', bgRGB); try % Add some text. At minimum, we have to pass the text to display to % 'addText', but there are other parameters we can set including its % location, color, and font size. txtString = 'red'; enableState = true; win.addText(txtString, ... % Text to display 'Center', [0 0], ... % Where to center the text. (x,y) 'FontSize', 100, ... % Font size 'Color', [1 0 0], ... % RGB color 'Name', 'myText'); % Identifier for the object. % Open the window. win.open; % Initialize our keyboard capture. ListenChar(2); FlushEvents; while true % Draw the scene. win.draw; % Wait for a keypress. switch GetChar % Quit case 'q' break; % Randomly change the text. case 'r' switch ceil(rand*6) case 1 txtString = 'red'; case 2 txtString = 'green'; case 3 txtString = 'blue'; case 4 txtString = 'yellow'; case 5 txtString = 'brown'; case 6 txtString = 'pink'; end % This will replace whatever text was shown before. win.setText('myText', txtString); % Change color case 'c' % For technical reasons, you can't change the color % of a text object directly. But, you can 're-add' % it with the same name and it will replace the % previous version. This this code acts to change % the color of the currently displayed string. win.addText(txtString, ... % Text to display 'Center', [0 0], ... % Where to center the text. (x,y) 'FontSize', 100, ... % Font size 'Color', rand(1,3), ... % RGB color 'Enabled',enableState, ... % Preseve enable/disable 'Name', 'myText'); % Identifier for the object. % Enable case 'e' enableState = true; win.enableObject('myText'); case 'd' enableState = false; win.disableObject('myText'); end end cleanup(win); catch e cleanup(win); rethrow(e); end function cleanup(win) if ~isempty(win) win.close; end ListenChar(0);
github
BrainardLab/TeachingCode-master
GetTheResponse.m
.m
TeachingCode-master/GLWindowExamples/GLW_PhaseDistort/GetTheResponse.m
3,680
utf_8
6a5242c995de8001a5ccd02583cac7e8
function [answerIsCorrect, quitExp] = GetTheResponse(win, imageSize, whichSide, leftImagePosition, rightImagePosition) % [answerInCorrect, quitExp] = GetTheResponse(win, imageSize, whichSide, leftImagePosition, rightImagePosition) % % This function positions the mouse on the center of the screen and waits % for the user to click on one or the two images that are displayed on the % experimental window. % % If the user clicks on the correct/wrong image (specified by parameter % whichSide), the returned parameter 'answerIsCorrect' is set to true/false. % % If the user clicks outside of either image, we remain in the loop until % the mouse click occurs within one of the two image areas. % % If the user enter a 'q' key, the loop is terminated and the returned % parameter 'quitExp' is set to true. % % % 12/10/12 npc Wrote it. % % move cursor to center of screen screenSizeInPixels = win.DisplayInfo(win.WindowID).screenSizePixel; mouseHomeX = screenSizeInPixels(1)/2; mouseHomeY = screenSizeInPixels(2)/2; mglSetMousePosition(mouseHomeX, mouseHomeY,win.WindowID); % compute bounding rects for left and right image rect0 = SetRect(0,0, imageSize, imageSize); leftImageRect = CenterRectOnPointd(rect0, leftImagePosition(1) + mouseHomeX, ... leftImagePosition(2) + mouseHomeY); rightImageRect = CenterRectOnPointd(rect0, rightImagePosition(1) + mouseHomeX, ... rightImagePosition(2) + mouseHomeY); quitExp = false; keepLooping = true; answerIsCorrect = false; while (keepLooping) if CharAvail % Get the key theKey = GetChar; if (theKey == 'q') keepLooping = false; quitExp = true; end else % Get the mouse state mouseInfo = mglGetMouse(win.WindowID); % Check to see if a mouse button was pressed if (mouseInfo.buttons > 0) [keepLooping, answerIsCorrect] = ... CheckWhichImageWasSelected(mouseInfo.x, mouseInfo.y, leftImageRect, rightImageRect, whichSide); end end end % while keepLooping if (~quitExp) GiveFeedback(answerIsCorrect); end end function [keepLooping, answerIsCorrect] = CheckWhichImageWasSelected(mouseX, mouseY, leftImageRect, rightImageRect, whichSide) % [keepLooping, answerIsCorrect] = CheckWhichImageWasSelected(win, mouseX, mouseY, leftImageRect, rightImageRect, whichSide) % % Determine if the mouse click occurred within the left or the right image % and determine whether the anser is correct or wrong. If the mouse click was % outside of both image areas, remain in the polling loop. % % 12/10/12 npc Wrote it. % answerIsCorrect = false; % If the user did not click on the left or the right image, remain in the polling loop if ((~IsInRect(mouseX, mouseY, leftImageRect))&&(~IsInRect(mouseX, mouseY, rightImageRect))) keepLooping = true; return; end % Ok, we have a hit. Exit mouse/keyboard polling loop keepLooping = false; % Determine if the mouse click was on the correct image if (IsInRect(mouseX, mouseY, leftImageRect)) % mouse click on LEFT image if (whichSide == 0) answerIsCorrect = true; end elseif (IsInRect(mouseX, mouseY, rightImageRect)) % mouse click on RIGHT image if (whichSide == 1) answerIsCorrect = true; end end end
github
BrainardLab/TeachingCode-master
LoadImagesAndComputeTheirSpectra.m
.m
TeachingCode-master/GLWindowExamples/GLW_PhaseDistort/LoadImagesAndComputeTheirSpectra.m
3,523
utf_8
c04e731ea8750c9a0e2e9608650c1853
function [image1Struct, image2Struct, imageSize] = LoadImagesAndComputeTheirSpectra(imageResizingFactor) % [image1struct, image2struct, imageSize] = LoadImagesAndComputeTheirSpectra(imageResizingFactor) % % Load images, resize them according to parameter imageResizingFactor % (via bicubic interpolation) and perform Fourier analysis on them. % Convention assumes that images are in MAT files with image name % equal to file name. Images are also assumed scaled in range 0-255. % % The returned image structs contain the following fields: % - Name : a string with the name of the image % - ImageMatrix : the image data, i.e, a [rows x cols] matrix % - Amplitude : the amplitude spectrum of the image, i.e., a [rows x cols] matrix % - Phase : the phase spectrum of the image, i.e., a [rows x cols] matrix % - RGBdata : the RGB version of the image data, i.e, a [rows x cols x 3] matrix % % 12/10/12 npc Wrote it. % image1Struct = loadAndAnalyze('reagan128', imageResizingFactor); image2Struct = loadAndAnalyze('einstein128', imageResizingFactor); if (isempty(image1Struct) || isempty(image2Struct)) imageSize = 0; else [imageSize,~] = size(image1Struct.ImageMatrix); end end function imageStruct = loadAndAnalyze(imageName, imageResizingFactor) % Load image, interpolate and compute its amplitude/phase spectra % if (exist(sprintf('%s.mat', imageName)) == 2) % load mat file with image load(imageName, '-mat'); eval(['imageMatrix = ' imageName ';']); % interpolate imageMatrix by imageResizingFactor if (imageResizingFactor > 1) imageMatrix = intepolateImage(imageMatrix, imageResizingFactor); end % flip image upside-down and normalize it imageMatrix = flipud(imageMatrix) / 255; % compute spectral analysis imageFT = fft2(imageMatrix); % generate imageStruct imageStruct = struct; imageStruct.Name = imageName; imageStruct.ImageMatrix = imageMatrix; imageStruct.Amplitude = abs(imageFT); imageStruct.Phase = angle(imageFT); imageStruct.RGBdata = repmat(imageStruct.ImageMatrix, [1 1 3]); else % file does not exist. Print message fprintf('Did not find image %s', sprintf('%s.mat', imageName)); imageStruct = []; end end function newImage = intepolateImage(image, factor) % Intepolate image by the given factor % % make sure newImageSize is an even number newImageSize = ceil(size(image,1) * factor); if (mod(newImageSize,2) == 1) newImageSize = newImageSize-1; end % compute original and interpolated indices x = [1:size(image,1)]; xi = 1+[0:newImageSize-1]/newImageSize*size(image,1); [X,Y] = meshgrid(x,x); [XI,YI] = meshgrid(xi,xi); % do the interpolation newImage = interp2(X,Y, image, XI, YI, 'cubic*'); % take care of any nan values newImage(isnan(newImage)) = 0; % enable this flag to generate a figure showing the original and intepolated images displayIntepolatedPhotos = false; if (displayIntepolatedPhotos) figure(2); clf; subplot(1,2,1); imagesc(image); axis square set(gca, 'CLim', [0 255]); subplot(1,2,2); imagesc(newImage); axis square set(gca, 'CLim', [0 255]); colormap(gray); end end
github
BrainardLab/TeachingCode-master
PhaseDistortDemoGUI.m
.m
TeachingCode-master/GLWindowExamples/GLW_PhaseDistort/PhaseDistortDemoGUI.m
5,375
utf_8
e5f168581d0225e06a5760f0e0990ec2
function varargout = PhaseDistortDemoGUI(varargin) % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @PhaseDistortDemoGUI_OpeningFcn, ... 'gui_OutputFcn', @PhaseDistortDemoGUI_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT end % --- Executes just before PhaseDistortDemoGUI is made visible. function PhaseDistortDemoGUI_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to PhaseDistortDemoGUI (see VARARGIN) % Choose default command line output for PhaseDistortDemoGUI handles.output = hObject; experimentParams = struct; experimentParams.generatePhaseFieldFromPinkNoise = false; experimentParams.useSoftCircularAperture = false; experimentParams.imageResizingFactor = 1.5; experimentParams.questTrials = 60; handles.experimentParams = experimentParams; set(handles.WindowImagesCheckbox, 'Value', handles.experimentParams.useSoftCircularAperture); if (experimentParams.generatePhaseFieldFromPinkNoise) set(handles.Noise1fMethodButton, 'Value', 1); set(handles.DavidMethodButton, 'Value', 0); else set(handles.Noise1fMethodButton, 'Value', 0); set(handles.DavidMethodButton, 'Value', 1); end set(handles.ResizingFactor, 'String', sprintf('%2.2f', handles.experimentParams.imageResizingFactor)); set(handles.QuestTrials, 'String', sprintf('%2.0f', handles.experimentParams.questTrials)); % Update handles structure guidata(hObject, handles); % UIWAIT makes PhaseDistortDemoGUI wait for user response (see UIRESUME) % uiwait(handles.figure1); end % --- Outputs from this function are returned to the command line. function varargout = PhaseDistortDemoGUI_OutputFcn(hObject, eventdata, handles) varargout{1} = handles.output; end % --- Executes on button press in StartExperiment. function StartExperiment_Callback(hObject, eventdata, handles) handles.experimentParams.imageResizingFactor = str2double(get(handles.ResizingFactor, 'String')); handles.experimentParams.questTrials = str2double(get(handles.QuestTrials, 'String')); handles.experimentParams.useSoftCircularAperture = get(handles.WindowImagesCheckbox, 'Value'); handles.experimentParams PhaseDistortDemo(handles.experimentParams.generatePhaseFieldFromPinkNoise, ... handles.experimentParams.useSoftCircularAperture, ... handles.experimentParams.imageResizingFactor, ... handles.experimentParams.questTrials, ... handles.ResultsAxes); end function WindowImagesCheckbox_Callback(hObject, eventdata, handles) handles.experimentParams.useSoftCircularAperture = get(hObject,'Value'); end function ResizingFactor_Callback(hObject, eventdata, handles) handles.experimentParams.imageResizingFactor = str2double(get(hObject,'String')); end function QuestTrials_Callback(hObject, eventdata, handles) handles.experimentParams.questTrials = str2double(get(hObject,'String')); end function ResizingFactor_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end function edit2_Callback(hObject, eventdata, handles) end function edit2_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end function RandomPhaseGenerationSelector_SelectionChangeFcn(hObject, eventdata, handles) switch get(eventdata.NewValue,'Tag') % Get Tag of selected object. case 'DavidMethodButton' handles.experimentParams.generatePhaseFieldFromPinkNoise = false; case 'Noise1fMethodButton' handles.experimentParams.generatePhaseFieldFromPinkNoise = true; otherwise % Code for when there is no match. end end function figure1_CreateFcn(hObject, eventdata, handles) end function QuestTrials_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end function edit4_Callback(hObject, eventdata, handles) end function edit4_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end end
github
BrainardLab/TeachingCode-master
backpropTutorial.m
.m
TeachingCode-master/MatlabTutorials/backpropTutorial.m
5,769
utf_8
6899dc4f89555b0feb61209b349d76d9
function backpropTutorial % backpropTutorial.m % % Illustrate backprop, by trying to use it to fit a function with a two % layer network. The initial idea was to set this up to reproduce some % of the fits shown in Figure 4.12 of Bishop, using the backpropagation % algorithm described later in the chapter. % % The line example works perfectly. For the parabola, dualramp, and step % functions, the network does approximately the right thing, but the quality of fit % is markedly worse than shown in Figure 4.12. The sinusoid is not fit % at all well. % % The example in Bishop uses a different algorithm to set the weights, and % this may be the problem. Or we may still have a bug in the backprop % implementation here. % % For some of the test functions, the training can get stuck in a local % minima. Whether it does this or not is pretty sensitive to the initial % weights, learning rate, etc. For the most part, the current parameters % seem to work pretty well for the functions being fit (except for the % sine). % % 8/27/08 dhb Wrote it. % 8/27/08 dhb and others Squashed several bugs during reading group meeting. % 8/27/08 dhb Store previous weights from output layer for hidder layer update. % dhb Get tanh derivative correct. % dhb Variable learning rate. % dhb More functions to try to fit. %% Clear and close clear; close all; %% Define network dimension and initialize weights. The number of weights % includes the additive term. nInputUnits = 2; nHiddenUnits = 5; inputWeights = rand(nHiddenUnits-1,nInputUnits); outputWeights = rand(1,nHiddenUnits); %% Define function to try to fit. Change the string % to one of the options in the case statement to try % different functions. inputFunction = 'dualramp'; nTrainingPoints = 1000; x = 2*rand(nInputUnits-1,nTrainingPoints)-1; switch(inputFunction) case 'parabola' t = x.^2; case 'line' t = x; case 'step' t = sign(x); case 'dualramp' t = abs(x); case 'sine' t = sin(2*pi*x); end %% Plot of target function funPlot = figure; clf; hold on set(gca,'FontName','Helvetica','FontSize',14); plot(x,t,'ro','MarkerSize',2,'MarkerFaceColor','r'); %% Add plot of the initial network response y0 = ComputeNetwork(x,inputWeights,outputWeights); plot(x,y0,'go','MarkerSize',2,'MarkerFaceColor','g'); drawnow; %% Set up learning and error tracking parameters n0 = 0.2; decayExponent = 0.01; errIndex = 1; err(errIndex) = sum((t-y0).^2); errPlot = figure; clf; set(gca,'FontName','Helvetica','FontSize',14); plotEvery = 100; %% Train the network, using the backprop algorithm nTrainingIterations = 5000; for i = 1:nTrainingIterations % Print and plot of incremental error if (rem(i,100) == 0) yNow = ComputeNetwork(x,inputWeights,outputWeights); errIndex = errIndex+1; err(errIndex) = sum((t-yNow).^2); figure(errPlot); hold on plot(plotEvery*((1:errIndex)-1),err(1:errIndex),'k'); end % Choose a training value from training set randomObservationIndices = randperm(nTrainingPoints); randomObservationIndex = randomObservationIndices(1); xTrain = x(:,randomObservationIndex); xTrainOnes = [ones(1,size(xTrain,2)) ; xTrain]; tTrain = t(randomObservationIndex); % Compute network values for this training exemplar [yCurrent,yCurrentLinear,hiddenCurrent,hiddenCurrentLinear] = ComputeNetwork(xTrain,inputWeights,outputWeights); % Update learning rate n = n0/(i^decayExponent); % Update output weights deltaOut = (yCurrent-tTrain); outputWeights0 = outputWeights; for j = 1:nHiddenUnits outputWeights(1,j) = outputWeights(1,j) - n*deltaOut*hiddenCurrent(j); end % Backprop to input weights for j = 2:nHiddenUnits deltaHidden = nonlinderiv(hiddenCurrentLinear(j-1))*deltaOut*outputWeights0(1,j); for k = 1:nInputUnits inputWeights(j-1,k) = inputWeights(j-1,k) - n*deltaHidden*xTrainOnes(k); end end end % Labels for error plot figure(errPlot); xlabel('Iteration','FontName','Helvetica','FontSize',18); ylabel('Summed Squared Error','FontName','Helvetica','FontSize',18); %% Add plot final network response, in black figure(funPlot); y = ComputeNetwork(x,inputWeights,outputWeights); plot(x,y,'ko','MarkerSize',2,'MarkerFaceColor','k'); xlim([-1 1.5]); xlabel('X','FontName','Helvetica','FontSize',18); ylabel('Y','FontName','Helvetica','FontSize',18); legend('target','initial','final'); %% Done end %% Forward network computation. Linear output layer and non-linearity on % output of hidden units. function [response,responseLinear,hiddenResponse,hiddenResponseLinear] = ComputeNetwork(x,inputWeights,outputWeights) % Compute response of hidden units x = [ones(1,size(x,2)) ; x]; hiddenResponseLinear = inputWeights*x; hiddenResponse = nonlin(hiddenResponseLinear); % Compute output response hiddenResponse = [ones(1,size(hiddenResponse,2)) ; hiddenResponse]; responseLinear = outputWeights*hiddenResponse; response = responseLinear; end %% Nonlinear function. Can change this and the corresponding derivative % function if you want to use another non-linearity (e.g. logistic). function y = nonlin(x) y = tanh(x); end %% Nonlinear function derivative. function y = nonlinderiv(x) y = tanhderiv(x); end %% Derivative of hyperbolic tangent. function y = tanhderiv(x) y = 1-tanh(x).^2; end % Logistic function function y = logit(x) y = 1./(1+exp(-x)); end % Logistic derivative function y = logitderiv(x) y = logit(x).*(1-logit(x)); end
github
BrainardLab/TeachingCode-master
crossvalTutorial.m
.m
TeachingCode-master/MatlabTutorials/crossvalTutorial.m
2,991
utf_8
3fcbfceda64bb678c4eb5f1e92ce3200
function crossvalTutorial % crossvalTutorial % % Quick little tutorial to show how to cross-validate some data. % % 12/16/16 dhb, ar Wrote the skeleton. %% Clear clear; close all; %% Parameters nIndependentValues = 10; nReplications = 100; noiseSd = 10; nFolds = 8; c1 = 5; c2 = -3; %% Let's generate a dataset of random numbers that are described by a quadratic xVals = repmat(linspace(0,10,nIndependentValues),nReplications,1); yObserved = zeros(size(xVals)); for jj = 1:nReplications xMatTemp = [xVals(jj,:) ; xVals(jj,:).^ 2]; yTemp = [c1 c2]*xMatTemp; yObserved(jj,:) = yTemp + normrnd(0,noiseSd,1,size(yObserved,2)); end %% Plot the simulated data figure; clf; hold on for jj = 1:size(yObserved,2) plot(xVals(jj,:),yObserved(jj,:),'ro','MarkerSize',8,'MarkerFaceColor','r'); end %% Do a cross-validated fit, using the crossval function % % We'll do both linear and quadratic fits % % Linear linearCrossValErr = crossval(@linearFit,xVals,yObserved,'KFold',nFolds); meanLinearCrossValErr = mean(linearCrossValErr); % Quadratic quadraticCrossValErr = crossval(@quadraticFit,xVals,yObserved,'KFold',nFolds); meanQuadraticCrossValErr = mean(quadraticCrossValErr); % Report who won if (quadraticCrossValErr < linearCrossValErr) fprintf('Crossval method: Correctly identified that it was quadratic\n'); else fprintf('Crossval method: Incorrectly think it is linear\n'); end %% Now we'll do the same thing using the cvpartition class. % % This is a bit less slick for this simple example, but much % more flexible when the fit functions need to be more complicated. c = cvpartition(nReplications,'Kfold',nFolds); for kk = 1:nFolds % Get indices for kkth fold trainingIndex = c.training(kk); testIndex = c.test(kk); check = trainingIndex + testIndex; if (any(check ~= 1)) error('We do not understand cvparitiion''s kFold indexing scheme'); end % Get linear and quadratic error for this fold linearCrossValErr(kk) = linearFit(xVals(trainingIndex,:),yObserved(trainingIndex,:),xVals(testIndex,:),yObserved(testIndex,:)); quadraticCrossValErr(kk) = quadraticFit(xVals(trainingIndex,:),yObserved(trainingIndex,:),xVals(testIndex,:),yObserved(testIndex,:)); end % Get mean error for two types of it meanQuadraticCrossValErr = mean(quadraticCrossValErr); meanLinearCrossValErr = mean(linearCrossValErr); % Report who won if (quadraticCrossValErr < linearCrossValErr) fprintf('CVParitition method: Correctly identified that it was quadratic\n'); else fprintf('CVParitition method: Incorrectly think it is linear\n'); end end function testVal = linearFit(xTrain,yTrain,xTest,yTest) c = xTrain(:)\yTrain(:); yPred = xTest(:)*c; yDiff = yPred(:)-yTest(:); testVal = sum(yDiff.^2); end function testVal = quadraticFit(xTrain,yTrain,xTest,yTest) c = [xTrain(:) xTrain(:).^2]\yTrain(:); yPred = [xTest(:) xTest(:).^2]*c; yDiff = yPred(:)-yTest(:); testVal = sum(yDiff.^2); end
github
BrainardLab/TeachingCode-master
fourierFitTutorial.m
.m
TeachingCode-master/MatlabTutorials/fourierFitTutorial.m
6,908
utf_8
a67ecd1ea0d9e92848a1435151551bbe
function fourierFitTutorial % fourierFitTutorial % % Demonstrate how to fit fourier functions to data, using optimization % toolbox. Both unconstrained and constrained. Shows fmincon in action. % % 4/21/09 dhb Started on it. % 7/15/09 dhb Check optim version and handle inconsistences in options. %% Clear clear; close all; %% Generate a test data set with three elements in the data set. Make shape similar but not identical. noisesd = 0.2; fitorder = 2; testHues = 1:40; xset{1} = (testHues-1)/length(testHues+1); xset{2} = xset{1}; xset{3} = xset{1}; coeffstrue{1} = [2 1 1 0.4 0.25 0.1 0.2]; yset{1} = ComputeFourierModel(coeffstrue{1},xset{1}) + normrnd(0,noisesd,size(xset{1})); coeffstrue{2} = [1 0.3 1.2 0.5 0.25 -0.1 0.0]; yset{2} = ComputeFourierModel(coeffstrue{2},xset{2}) + normrnd(0,noisesd,size(xset{1})); coeffstrue{3} = [1.5 0.5 0.9 0.3 0.35 0 0.2]; yset{3} = ComputeFourierModel(coeffstrue{3},xset{3}) + normrnd(0,noisesd,size(xset{1})); %% Fit the dataset, unconstrained [coeffsunset,ypredunset,errorunset] = FitUnconstrainedModel(xset,yset,fitorder); %% Fit the dataset, constrained [coeffsconset,ypredconset,errorconset] = FitConstrainedModel(xset,yset,fitorder); %% Report what happened figure; clf; subplot(3,1,1); hold on plot(xset{1},yset{1},'ro','MarkerFaceColor','r','MarkerSize',6); plot(xset{1},ypredunset{1},'r'); plot(xset{1},ypredconset{1},'b'); ylim([0 5]); subplot(3,1,2); hold on plot(xset{2},yset{2},'ro','MarkerFaceColor','r','MarkerSize',6); plot(xset{2},ypredunset{2},'r'); plot(xset{2},ypredconset{2},'b'); ylim([0 5]); subplot(3,1,3); hold on plot(xset{3},yset{3},'ro','MarkerFaceColor','r','MarkerSize',6); plot(xset{3},ypredunset{3},'r'); plot(xset{3},ypredconset{3},'b'); ylim([0 5]); end function [coeffsset,ypredset,errorset] = FitUnconstrainedModel(xset,yset,order) % [coeffset,ypred] = FitUnconstrainedModel(x,y,order) % % Fit the fourier model of given order separately to each data set in the % passed cell arrays xset and yset. Return cell arrays giving fit coefficients, % predictions, and errors. % % 4/21/09 dhb Wrote it. % Optimization options options = optimset('fmincon'); if (verLessThan('optim','4.1')) options = optimset(options,'Diagnostics','off','Display','off','LargeScale','off'); else options = optimset(options,'Diagnostics','off','Display','off','LargeScale','off','Algorithm','active-set'); end % Define length of coefficients from order coeffs00 = zeros(1,3+2*(order-1)); % Do each set separately nSets = length(xset); for i = 1:nSets x = xset{i}; y = yset{i}; % Initialize guess and set bounds, based loosely on data. coeffs0 = coeffs00; coeffs0(1) = mean(y); coeffs0(2) = mean(y); lb = [min(y) -10*max(abs(y))*ones(1,length(coeffs0(2:end)))]; ub = [max(y) 10*max(abs(y))*ones(1,length(coeffs0(2:end)))]; % Do the fit. coeffsset{i} = fmincon(@FitUnconstrainedFun,coeffs0,[],[],[],[],... lb,ub,[],options,x,y); % Get final prediction and error for return ypredset{i} = ComputeFourierModel(coeffsset{i},x); errorset{i} = EvaluateModelFit(y,ypredset{i}); end end function f = FitUnconstrainedFun(coeffs,x,y) % f = FitUnconstrainedFun(coeffs,x,y) % % Error function for unconstrained model fit. % % 4/21/09 dhb Wrote it. ypred = ComputeFourierModel(coeffs,x); f = EvaluateModelFit(y,ypred); end function [coeffsset,ypredset,errorset] = FitConstrainedModel(xset,yset,order,guesscoeffs) % [coeffset,ypred] = FitConstrainedModel(x,y,order,guesscoeffs) % % Fit the fourier model of given order separately to each data set in the % passed cell arrays xset and yset. Return cell arrays giving fit coefficients, % predictions, and errors. The fit is constrained so that each element of the % dataset has the same modulation shape, but the modulation mean and depth can % vary. % % 4/21/09 dhb Wrote it. % Optimization options options = optimset('fmincon'); if (verLessThan('optim','4.1')) options = optimset(options,'Diagnostics','off','Display','off','LargeScale','off'); else options = optimset(options,'Diagnostics','off','Display','off','LargeScale','off','Algorithm','active-set'); end % Grab number of sets nSets = length(xset); % Initialize guess and set bounds, based loosely on data. concoeffs0 = [zeros(1,2*nSets) zeros(1,1+2*(order-1))]; miny = Inf; maxy = -Inf; index = 1; for i = 1:nSets concoeffs0(2*(i-1)+1) = mean(yset{i}); concoeffs0(2*(i-1)+2) = mean(yset{i}); index = index+2; if (min(yset{i}) < miny) miny = min(yset{i}); end if (max(yset{i}) > maxy) maxy = max(yset{i}); end end lb = [-10*max(abs([miny maxy]))*ones(1,length(concoeffs0))]; ub = [10*max(abs([miny maxy]))*ones(1,length(concoeffs0))]; for i = 1:nSets lb(2*(i-1)+1) = miny; ub(2*(i-1)+1) = maxy; end % Do the numerical fit concoeffs = fmincon(@FitConstrainedFun,concoeffs0,[],[],[],[],... lb,ub,[],options,xset,yset); % Get final prediction and error for return coeffsset = UnpackConCoeffs(concoeffs,nSets); for i = 1:nSets ypredset{i} = ComputeFourierModel(coeffsset{i},xset{i}); errorset{i} = EvaluateModelFit(yset{i},ypredset{i}); end end function f = FitConstrainedFun(concoeffs,xset,yset) % f = FitUnconstrainedFun(coeffs,xset,yset) % % Error function for constrained model fit. % % 4/21/09 dhb Wrote it. % Unpack constrained coefficients nSets = length(xset); coeffsset = UnpackConCoeffs(concoeffs,nSets); % Get error for each set and sum f = 0; for i = 1:nSets ypred = ComputeFourierModel(coeffsset{i},xset{i}); f = f + EvaluateModelFit(yset{i},ypred); end end function coeffsset = UnpackConCoeffs(concoeffs,nSets) % coeffsset = UnpackConCoeffs(concoeffs,nSets) % % Unpack array of constrained coefficients into cell array % in form to evaluate each component separately. % % 4/21/09 dhb Wrote it. index = 1; for i = 1:nSets coeffsset{i}(1) = concoeffs(index); index = index+1; coeffsset{i}(2) = concoeffs(index); index = index+1; end for i = 1:nSets coeffsset{i}(3:3+length(concoeffs(index:end))-1) = concoeffs(index:end); end end function ypred = ComputeFourierModel(coeffs,x) % ypred = ComputeFourierModel(coeffs,x) % % ypred = coeffs(1) + coeffs(2)*(sin(2*pi*x) + coeffs(3)*cos(2*pi*x) + coeffs(4)*sin(2*pi*2*x) + coeffs(5)*cos(2*pi*2*x) + ... % % The order of the equation is determined from the length of coeffs. % The input x is assumed to be in the range [0-1]. % % 4/21/09 dhb Wrote it. % Modulation a = coeffs(1); b = coeffs(2); modulation = sin(2*pi*x) + coeffs(3)*cos(2*pi*x); for i = 1:length(coeffs(4:end))/2 modulation = modulation + coeffs(2*(i-1)+4)*sin(2*pi*(i+1)*x) + coeffs(2*(i-1)+5)*cos(2*pi*(i+1)*x); end ypred = a + b*modulation; end function f = EvaluateModelFit(y,ypred) % f = EvaluateModelFit(y,ypred) % % 4/21/09 dhb Wrote it. resid = y-ypred; f = sqrt(sum(resid.^2)/length(resid)); end
github
BrainardLab/TeachingCode-master
crossContextMLDScalingTutorial.m
.m
TeachingCode-master/MatlabTutorials/crossContextMLDScalingTutorial.m
5,968
utf_8
6678160b25bded3b8fd03551f9351930
function CrossContextMLDSScalingTutorial % CrossContextMLDSScalingTutorial % % Suppose we have cross-context data of the form, see stimulus % X, seen in context 1, and choose which of two alternatives, Y1 and Y2, % seen in context 2, that is most like X. % % We want to take a bunch of data of this form, where Y1 and Y2 vary % trial-to-trial, and find the value of Y that is the best match to X. % % We assume that the Y's live in an N dimensional perceptual space. % This seems like an MDS setup, with triad data. As discussed % in Maloney and Yang (2003), triads are a special case of % the MLDS stimuli, with one stimulus repeated twice. % % The other difference here is the change of context, but I don't think % that is fundamental. % % If we're willing to take the scales as one-dimensional and assume that % the scale in one context maps into the other in some parametric % way, we could find the parametric transformation. % % This code simulates out the basic MLDS analysis for a case like the above, % to make sure nothing goes too wonky. % % NOTE: We how have a toolbox, BrainardLabToolbox/MLDSColorSelection, that % implements much of what is here. This should be modified to call through % that, and the two should cross-reference each other. % % 1/10/12 dhb Wrote it. %% Clear and close clear; close all; %% Parameters sigma = 0.10; nY = 10; nSimulatePerPair = 100; %% Generate a list of X and Y stimuli x = 0.55; yOfX = MapXToY(x); linY = logspace(log10(0.5),log10(0.6),nY); y = MapXToY(linY); %% Simulate out probabilities for pairwise trials thePairs = nchoosek(1:nY,2); nPairs = size(thePairs,1); theSimResponse1 = zeros(nPairs,1); theTheoryResponse1 = zeros(nPairs,1); for i = 1:nPairs n1 = 0; for j = 1:nSimulatePerPair if (SimulateResponse1(x,y(thePairs(i,1)),y(thePairs(i,2)),sigma,@MapXToY)) n1 = n1 + 1; end end theSimResponse1(i) = n1; theTheoryProb1(i) = ComputeProb1(x,y(thePairs(i,1)),y(thePairs(i,2)),sigma,@MapXToY); end theSimProb1 = theSimResponse1/nSimulatePerPair; %% Make sure that simulated data matches the theoretical model. Nothing % else is going to work if this isn't done correctly figure; clf; hold on plot(theTheoryProb1,theSimProb1,'ro','MarkerSize',4,'MarkerFaceColor','r'); xlabel('Theory'); ylabel('Simulation'); axis('square'); axis([0 1 0 1]); plot([0 1],[0 1],'k'); %% Find the maximum likelihood solution for x and the y's. We % fix the origin at y(1) and the scale via sigma, which are thus % assumed known. % Compute log likelihood of actual simulated data as a baseline logLikelyTrue = ComputeLogLikelihood(thePairs,theSimResponse1,nSimulatePerPair,MapXToY(x),y,sigma); % Search to find the best solution options = optimset('fmincon'); options = optimset(options,'Diagnostics','off','Display','iter','LargeScale','off','Algorithm','active-set'); y1 = y(1); x0 = [x linY(2:end)]; vlb = -10*max(x0)*ones(size(x0)); vub = 10*max(x0)*ones(size(x0)); fitX = fmincon(@(x)FitContextFCScalingFun(x,y1,thePairs,theSimResponse1,nSimulatePerPair,sigma),x0,[],[],[],[],vlb,vub,[],options); xFit = fitX(1); yFit = [y1 fitX(2:end)]; logLikelyFit = ComputeLogLikelihood(thePairs,theSimResponse1,nSimulatePerPair,xFit,yFit,sigma); fprintf('Log likelihood true: %g, fit: %g\n',logLikelyTrue,logLikelyFit); %% Plot the recovered configuration figure; clf; hold on plot(y,yFit,'ro','MarkerSize',4,'MarkerFaceColor','r'); plot(MapXToY(x),xFit,'bo','MarkerSize',4,'MarkerFaceColor','b'); xlabel('Simulated'); ylabel('Fit'); axis('square'); minVal = min([y yFit]); maxVal = max([y yFit]); axis([minVal maxVal minVal maxVal]); plot([minVal maxVal],[minVal maxVal],'k'); end %% f = FitContextFCScalingFun(x,y1,thePairs,theResponse1,nTrials,sigma) % % Error function for the numerical search. function f = FitContextFCScalingFun(x,y1,thePairs,theResponse1,nTrials,sigma) if (any(isnan(x))) error('Entry of x is Nan'); end xFit = x(1); yFit = [y1 x(2:end)]; logLikely = ComputeLogLikelihood(thePairs,theResponse1,nTrials,xFit,yFit,sigma); f = -logLikely; end %% logLikely = ComputeLogLikelihood(thePairs,theResponse1,nTrials,xFit,yFit,sigma) % % Compute likelihood of data for any configuration function logLikely = ComputeLogLikelihood(thePairs,theResponse1,nTrials,xFit,yFit,sigma) nPairs = size(thePairs,1); logLikely = 0; for i = 1:nPairs theTheoryProb1 = ComputeProb1(xFit,yFit(thePairs(i,1)),yFit(thePairs(i,2)),sigma,@IdentityMap); if (isnan(theTheoryProb1)) error('Returned probability is NaN'); end if (isinf(theTheoryProb1)) error('Returend probability is Inf'); end logLikely = logLikely + theResponse1(i)*log10(theTheoryProb1) + (nTrials-theResponse1(i))*log10(1-theTheoryProb1); end if (isnan(logLikely)) error('Returned likelihood is NaN'); end end %% p1 = ComputeProb1(x,y1,y2,sigma,mapFunction) % % Compute probability of responding 1 given target and pair. % The passed mapFunction simulates the effect of context change % between x domain and y domain function p1 = ComputeProb1(x,y1,y2,sigma,mapFunction) yOfX = mapFunction(x); diff1 = y1-yOfX; diff2 = y2-yOfX; diffDiff = abs(diff1)-abs(diff2); p1 = normcdf(-diffDiff,0,sigma); if (p1 == 0) p1 = 0.0001; elseif (p1 == 1) p1 = 0.9999; end end %% response1 = SimulateResponse1(x,y1,y2,sigma,mapFunction) % % Simulate a trial given target and pair. % The passed mapFunction simulates the effect of context change % between x domain and y domain function response1 = SimulateResponse1(x,y1,y2,sigma,mapFunction) yOfX = mapFunction(x); diff1 = y1-yOfX; diff2 = y2-yOfX; if (abs(diff1)-abs(diff2) + normrnd(0,sigma) <= 0) response1 = 1; else response1 = 0; end end %% yOfX = MapXToY(x) % % Example map function function yOfX = MapXToY(x) yOfX = x.^0.8 - 0.1; end %% yOfX = IdentityMap(x) % % Identity map function. When simulating fit % we use this. function yOfX = IdentityMap(x) yOfX = x; end
github
BrainardLab/TeachingCode-master
glmTutorial.m
.m
TeachingCode-master/MatlabTutorials/glmTutorial.m
4,724
utf_8
e130c3872af22a7d5482aa8d8594dce6
function glmTutorial % % Demonstrate how to use Matlab's Statistics Toolbox glm routines % to fit data. % % This is right basic idea, but needs a little fixing up still. % % Need to: % a) Add better comments. % b) Show how to wrap a parameter search around the parameters of % the linking function. % c) Worry about the regime where the linking function is such that % the glm routines return NaN because of ill-conditioning. % % 9/21/13 dhb Wrote it. %% Clear clear; close all; %% Parameters. % % We construct a linear function of some % random numbers, bTrue gives the weights. bTrue = [2 3 5]'; xDim = length(bTrue); nObservations = 100; noiseSd = 0.01; %% Link function and its parameters. % % We assume that the observed data are a Naka-Rushton function % of the linear values. The way the glm stuff works, % this means that the linking function is the inverse of the % Naka-Rushton function. global linkParams linkParams.type = 'AffinePower'; switch (linkParams.type) case 'InverseNakaRushton' linkParams.params(1) = 10; linkParams.params(2) = 3; linkParams.params(3) = 2; linkS.Link = @ForwardLink; linkS.Derivative = @DerivativeLink; linkS.Inverse = @InverseLink; case 'AffinePower' linkParams.params(1) = 1; linkParams.params(2) = 0.5; linkS.Link = @ForwardLink; linkS.Derivative = @DerivativeLink; linkS.Inverse = @InverseLink; case 'Power' linkParams.params(1) = 2; linkS.Link = @ForwardLink; linkS.Derivative = @DerivativeLink; linkS.Inverse = @InverseLink; otherwise error('Unknown link function type'); end %% X variables X = rand(nObservations,xDim); %% Linear y is a linear function of X yLinear = X*bTrue; yNonLinear = InverseLink(yLinear); yObserved = yNonLinear + noiseSd*randn(size(yNonLinear)); %% Figure [~,index] = sort(yLinear); theFig = figure; clf; hold on plot(yLinear(index),yObserved(index),'ro','MarkerSize',8,'MarkerFaceColor','r'); plot(yLinear(index),yNonLinear(index),'r'); %% GLM fit warnState = warning('off','stats:glmfit:IterationLimit'); GLM = GeneralizedLinearModel.fit(X,yObserved,'Distribution','normal','Link',linkS,'Intercept',false); warning(warnState); bFit = GLM.Coefficients.Estimate yLinearPred = X*bFit; yNonLinearPred = InverseLink(yLinearPred); figure(theFig); plot(yLinear(index),yNonLinearPred(index),'b'); xlabel('True linear value'); ylabel('Obs/Predicted nonlinear value'); %% This is just a check that the PTB NakaRushton function properly % inverts itself. switch (linkParams.type) case 'NakaRushton' linearInvertCheck = ForwardLink(yNonLinearPred); if (any(abs(yLinearPred-linearInvertCheck) > 1e-7)) error('Naka-Rushton inversion error'); end % A little more testing figure; clf; derivCheck = DerivativeLink(yNonLinearPred); subplot(2,1,1); hold on plot(yNonLinearPred(index),linearInvertCheck(index),'r'); subplot(2,1,2); hold on plot(yNonLinearPred(index),derivCheck(index),'r'); end end function out = ForwardLink(in) global linkParams switch (linkParams.type) case 'InverseNakaRushton' in(in < 0) = 0; in(in > linkParams.params(1)) = linkParams.params(1); out = InvertNakaRushton(linkParams.params,in); case 'AffinePower' in(in < 0) = 0; out = linkParams.params(1) + in.^linkParams.params(2); case 'Power' in(in < 0) = 0; out = in.^linkParams.params(1); otherwise error('Unknown link function type'); end end function out = DerivativeLink(in) global linkParams switch (linkParams.type) case 'InverseNakaRushton' in(in < 0) = 0; in(in > linkParams.params(1)) = linkParams.params(1); out = DerivativeInvertNakaRushton(linkParams.params,in); case 'AffinePower' in(in < 0) = 0; out = linkParams.params(2)*in.^(linkParams.params(2)-1); case 'Power' in(in < 0) = 0; out = linkParams.params(2)*in.^(linkParams.params(2)-1); otherwise error('Unknown link function type'); end end function out = InverseLink(in) global linkParams switch (linkParams.type) case 'InverseNakaRushton' % Force input into required range in(in < 0) = 0; out = ComputeNakaRushton(linkParams.params,in); case 'AffinePower' in(in < 0) = 0; tmp = in - linkParams.params(1); tmp(tmp < 0) = 0; out = tmp.^(1/linkParams.params(2)); case 'Power' in(in < 0) = 0; out = in.^(1/linkParams.params(2)); otherwise error('Unknown link function type'); end end
github
BrainardLab/TeachingCode-master
TestPredictNRAffineMatchesAnaIndividual.m
.m
TeachingCode-master/MatlabTutorials/lightessModelsTutorial/TestPredictNRAffineMatchesAnaIndividual.m
29,899
utf_8
d4db10f878711848957271786b92778a
function TestPredictNRAffineMatches % TestPredictNRAffineMatches % % Work out what the little model does for various choices of input % % 12/4/10 dhb Wrote it. % 4/20/11 dhb Lot's of little changes. Switch polarity of data plots %% Clear clear; close all; % Define relevant directories. currentDir = pwd; dataDir = '/Users/Shared/Matlab/Experiments/HDRExperiments/HDRAna'; whichDataSet = 3; %% Choose model parameters and generate predictions, plot. % Let's one explore what the model can do. %DO_PRELIM_STUFF = 0; % if (DO_PRELIM_STUFF) % yRef = logspace(-2,4); % % %% Set up parameters % params0.rmaxRef = 1.0; % params0.gainRef = 10e-4; % params0.offsetRef = 0; % params0.expRef = 2.5; % params0.rmax = 1.01; % params0.gain = 0.5*10e-4; % params0.offset = 1; % params0.exp = 1; % % %% Plot effect of mucking with exponent % figure; clf; hold on % exponents = [1.5 2 2.5]; % for i = 1:length(exponents) % params0.exp = exponents(i); % yMatch{i} = PredictNRAffineMatches(yRef,params0); % % % Plot % plot(log10(yMatch{i}),log10(yRef),'k','LineWidth',3); % xlim([-3 5]); ylim([-3 5]); % xlabel('Log10 Target Lum'); % ylabel('Log10 Standard Lum/Refl'); % end % end paletteGlossy = [-2.0458e+00 -1.8447e+00 -1.6840e+00 -1.4881e+00 -1.3251e+00 -1.1838e+00 -1.0424e+00 -9.2046e-01 -8.1417e-01 -7.1175e-01 ... -6.2160e-01 -5.3180e-01 -4.5087e-01 -3.7192e-01 -2.9654e-01 -2.2746e-01 -1.6488e-01 -1.0768e-01 -4.3064e-02]; paletteMatte = [ NaN NaN NaN -1.4660 -1.3279 -1.1379 -1.0155 -0.8726 -0.7791 -0.6807 -0.6038 ... -0.5046 -0.4332 -0.3622 -0.3050 -0.2280 -0.1671 -0.0941 -0.0472]; paletteGlossyTruncated = [NaN NaN NaN paletteGlossy(:,4:end)]; %% Fit some matching data SARAH_TEST_DATA = 0; if (SARAH_TEST_DATA) else switch whichDataSet case 1 conditionList = {'FullGlossyfull','FullGlossytruncated', 'FullMattetruncated', 'WhiteGlossyfull','WhiteGlossytruncated', 'WhiteMattetruncated'}; subjectList = {'bam', 'cly', 'flv', 'lta' ,'ncd', 'rpd', 'stg', 'tfm'}; keepSomeData = [ [ -1.3802 -1.2294 -0.9707 -0.7100 -0.3612 0.0249 0.3078 0.5715 0.7699 0.9778 1.0846 1.3089 1.4555 1.5644 1.7196 1.9207 2.0673 2.2239 2.3914]; [ NaN NaN NaN -0.9522 -0.6050 -0.2339 0.1047 0.4402 0.6977 0.8384 1.0023 1.2422 1.4114 1.5759 1.7508 1.9397 2.0528 2.2656 2.4112]; [ NaN NaN NaN -1.0312 -0.7059 -0.2358 0.1020 0.4629 0.6309 0.8030 1.0495 1.1958 1.3473 1.5350 1.6646 1.8909 2.0447 2.2378 2.3792]; [ NaN -0.0746 0.0318 0.2519 0.6330 0.9303 1.1223 1.3450 1.5182 1.7405 1.8143 2.0090 1.9072 2.2261 NaN 2.4317 NaN NaN NaN]; [ NaN NaN NaN -0.0043 0.4266 0.6850 0.9769 1.2355 1.4810 1.6573 1.7507 1.9130 2.0836 2.1939 NaN 2.4042 NaN NaN NaN]; [ NaN NaN NaN 0.0356 0.3936 0.7326 0.9986 1.2143 1.4117 1.5808 1.7714 1.9066 2.0828 2.1358 2.3293 2.3833 NaN NaN NaN];]; case 2 conditionList = {'FullGlossyfull2','FullMattetruncated2', 'Full30Glossyfull2', 'Full30Mattetruncated2', 'White30Glossyfull','White30Mattetruncated', 'Gray30Glossyfull', 'Gray30Mattetruncated'}; subjectList = {'bam', 'cly', 'ncd', 'stg', 'tfm'}; keepSomeData = [ [ -1.0849 -0.9622 -0.8648 -0.6281 -0.3869 -0.1036 0.2128 0.4567 0.7647 0.9488 1.1614 ... 1.3723 1.5101 1.6622 1.7990 1.9214 2.0359 2.2311 2.3199]; [ NaN NaN NaN -0.8392 -0.5873 -0.1825 0.1171 0.4655 0.7031 0.9464 1.1034 ... 1.3530 1.4774 1.6270 1.8231 1.9047 2.1262 2.2451 2.2713] [ NaN NaN NaN NaN NaN 1.2849 1.2088 1.2595 1.3693 1.4580 1.5826 ... 1.7126 1.8139 1.9713 2.1010 2.1720 2.3164 2.4515 2.5170]; [ NaN NaN NaN NaN NaN NaN 1.1963 1.2787 1.3236 1.4529 1.5473 ... 1.6579 1.8419 1.8985 2.0625 2.1901 2.3280 2.4015 2.5215]; [ NaN NaN NaN NaN NaN 1.2475 1.2973 1.3907 1.6027 1.7238 1.8637... 1.9849 2.0992 2.2393 2.3454 2.4286 2.5200 2.5425 2.6196]; [NaN NaN NaN NaN NaN 1.2689 1.2883 1.4364 1.5560 1.7329 1.8336... 1.9731 2.1075 2.2431 2.3248 2.4025 2.5065 2.5691 2.6030]; [ NaN NaN NaN -0.0572 -0.0016 0.0921 0.2724 0.4301 0.5819 0.7071 0.7965 ... 0.9089 1.0300 1.0749 1.1734 1.2381 1.2656 NaN NaN]; [NaN NaN NaN NaN -0.0920 0.0354 0.2398 0.4029 0.5708 0.6956 0.7910... 0.9222 1.0426 1.0873 1.1855 1.2379 NaN NaN NaN]; ] case 3 subjectList={'ajh', 'arp', 'kjn', 'orp' ,'rvn'}; conditionList = {'FullGlossyfull3', 'FullGlossyfull4','Full30Glossyfull3','Full30Glossyfull4'... , 'Full1000Glossyfull3', 'FullGray30Glossyfull', 'FullGray1000Glossyfull', ... 'FullMeanPlusGlossyfull', 'Full30MeanPlusGlossyfull', 'FullGray30MeanPlusGlossyfull', 'FullMeanPlusGlossyfull2', 'FullMeanMinusGlossyfull2'}; keepSomeData = [[-1.2469 -1.0194 -0.6968 -0.3888 -0.1960 0.1387 0.3627 0.6095 0.8034 0.8159 ... 0.9833 1.1952 1.3942 1.5388 1.5710 1.7905 2.0848 2.0719 2.3168]; % full3 [ -1.4012 -0.9285 -0.7862 -0.4952 -0.2476 0.0172 0.2259 0.4565 0.5586 0.7049 ... 0.8431 1.0677 1.1933 1.3972 1.6246 1.7266 1.8868 2.1460 2.2618]; % full4 [NaN NaN NaN NaN 1.1345 1.1445 1.2867 1.3138 1.3704 1.5017 ... 1.5732 1.6708 1.7791 1.8904 1.9778 2.0832 2.2022 2.3184 2.4071]; % full30 3 [NaN NaN NaN NaN NaN NaN 1.1932 1.2166 1.2841 1.4061 ... 1.4842 1.6065 1.6801 1.8158 1.9317 2.0486 2.1714 2.2893 2.4259]; % full30 4 [ -0.3140 -0.2027 -0.0686 0.0819 0.2873 0.4310 0.5986 0.7905 0.8960 1.0847 ... 1.2355 1.3290 1.4651 1.6356 1.7116 1.8833 1.9983 2.1780 2.3949]; % full 1000 [ NaN NaN NaN NaN 0.4098 0.4786 0.6039 0.7330 0.8416 0.8923 ... 0.9797 1.1226 1.1993 1.3123 1.4279 1.5174 1.6544 1.6851 NaN]; % full Gray30 [ -1.0961 -0.8952 -0.7221 -0.4952 -0.3652 -0.1803 -0.0603 0.0522 0.3139 0.3222 ... 0.4816 0.6810 0.8161 0.9925 1.1563 1.3792 1.5010 1.6713 1.7328]; % full gray 1000; [-1.2028 -0.9204 -0.6084 -0.2414 -0.0021 0.0723 0.2916 0.5297 0.6825 0.8876 ... 0.9969 1.2277 1.2544 1.4292 1.6247 1.8370 2.0001 2.1447 2.2880]; % full mean plus; [NaN NaN NaN NaN NaN NaN 1.1726 1.2939 1.3940 1.5356 ... 1.5940 1.7435 1.8141 1.9606 2.0642 2.1749 2.3042 2.3794 2.4674]; % full30 mean plus; [NaN NaN NaN NaN 0.4270 0.4158 0.5322 0.6765 0.7749 0.8527 ... 0.9992 1.1176 1.2819 1.3642 1.4917 1.6065 1.6876 NaN NaN]; % fullgray30 [-7.5486e-01 -6.3016e-01 -3.7002e-01 -7.5043e-02 2.5521e-01 4.1869e-01 6.5650e-01 8.2140e-01 9.3936e-01 ... 1.1518e+00 1.3266e+00 1.3894e+00 1.4861e+00 1.7282e+00 1.8061e+00 1.9940e+00 2.1053e+00 2.2826e+00 2.3641e+00]; % fullmeanplus2 [-8.8795e-01 -7.5641e-01 -5.6947e-01 -4.3999e-01 -2.9319e-01 -1.1604e-01 5.8502e-02 2.5986e-01 3.7464e-01 ... 5.2778e-01 6.5286e-01 8.2851e-01 9.8959e-01 1.1379e+00 1.4417e+00 1.6340e+00 1.7811e+00 2.0558e+00 2.1961e+00]; % fullmeanminus ]; end for i = 1:length(conditionList) for j=1:length(subjectList) luminanceMatchesPerChip{i,j} = load(fullfile(dataDir,'data',conditionList{i},subjectList{j},[conditionList{i} '-' subjectList{j} '-TestAverages.txt'])); luminanceMatchesPerChip{i,j} = luminanceMatchesPerChip{i,j}(:, 2:end); % averageLumMatchesPerSubject{j}(:,i) = nanmean(luminanceMatchesPerChip{i,j},2); averageLumMatchesPerSubject{i}(:,j) = nanmean(luminanceMatchesPerChip{i,j},2); end end averageLumMatchesPerSubjectAll{i} = averageLumMatchesPerSubject{i}; %% See how many matches per subject are made. % If less than 3 subjects assigned anything to this chip, drop them. for g = 1: length(averageLumMatchesPerSubject) nSubjectMatches{g} = sum(isnan(averageLumMatchesPerSubject{g}),2); end for g = 1: length(nSubjectMatches) for r = 1:length(nSubjectMatches{g}) if (nSubjectMatches{g}(r) > 2) averageLumMatchesPerSubject{g}(r,:) = nan(1, size(averageLumMatchesPerSubject{g},2)); end end end cd(currentDir); xDataLim = [-2 3]; yDataLim = [-3 0]; fid = fopen(['ANA_TEST_DATA/ParamDump_All' num2str(whichDataSet) '_ALL.txt'],'w'); figPrefix = 'ANA_TEST_DATA/'; RESPONSE_REMAP = 0; end % Optional search to find reference parameters that put the responses rougly equally spaced on the y-axis. This isn't theoretically critical, but % seems as good an idea as any. FITREF = 0; if (FITREF) if (verLessThan('optim','4.1')) error('Your version of the optimization toolbox is too old. Update it.'); end options = optimset('fmincon'); options = optimset(options,'Diagnostics','off','Display','iter','LargeScale','off','Algorithm','active-set'); options = optimset(options,'MaxFunEvals',1200); targetRespRef = linspace(critValue,1-critValue,length(someDataRef)); conTolRef = (targetRespRef(2)-targetRespRef(1)); x0 = ParamsToListRef(params0); vlb = [x0(1)/100 x0(2) -100*mean(someDataRef) 1]; vub = [x0(1)*100 x0(2) 100*mean(someDataRef) 4]; x1 = fmincon(@InlineMinFunctionRef,x0,[],[],[],[],vlb,vub,@InlineConFunctionRef,options); params0 = ListToParamsRef(x1,params0); end %% Now do the fitting wrt to the reference paramters % rangeFig = figure; dataFig = figure; %position = get(gcf,'Position'); %position(3) = 1000; position(4) = 400; %set(gcf,'Position',position); allData = cell(1,length(conditionList)); for i = 1:length(conditionList) temptemp = []; for j = 1:length(subjectList) temptemp = [temptemp; [averageLumMatchesPerSubject{i}(:,j)']]; end %allDataMean(i,:) = nanmean(temptemp, 1); acrossSubjectLumAverages{i} = NaN(size(paletteGlossy',1),1); for g = 1:size(paletteGlossy',1) okindex = ~isnan(averageLumMatchesPerSubject{i}(g,:)'); tt=mean(averageLumMatchesPerSubject{i}(g,okindex))'; acrossSubjectLumAverages{i}(g,1)=tt; end temptemp = [temptemp; acrossSubjectLumAverages{i}(:)'] ; allData{i} = temptemp; clear temptemp end %% for debugging purposes. for i = 1:length(conditionList) check = keepSomeData(i,:) - acrossSubjectLumAverages{i}(:)'; end %% for i = 1: length(conditionList) figure(dataFig); clf; someData = allData{i}; for whichData = 1:(size(someData,1)) switch(conditionList{i}) case {'FullGlossyfull','WhiteGlossyfull', 'FullGlossyfull2','Full30Glossyfull2', 'White30Glossyfull','Gray30Glossyfull',... 'FullGlossyfull3', 'Full30Glossyfull3', 'Full1000Glossyfull3', 'FullGray30Glossyfull'... 'FullGlossyfull4', 'Full30Glossyfull4', 'FullGray1000Glossyfull', 'FullGray30MeanPlusGlossyfull'... 'FullMeanPlusGlossyfull', 'Full30MeanPlusGlossyfull', 'FullMeanPlusGlossyfull2', 'FullMeanMinusGlossyfull2'} someDataRef = 10.^[paletteGlossy(1,:)]; case {'FullGlossytruncated','WhiteGlossytruncated'} someDataRef = 10.^paletteMatte(1,:); case {'FullMattetruncated','WhiteMattetruncated', 'FullMattetruncated2','Full30Mattetruncated2','White30Mattetruncated','Gray30Mattetruncated'} someDataRef = 10.^paletteMatte(1,:); end %% Initialize parameters. Set reference rmax to 1 and exponent to 2. Find % gain and offset that map the luminances across the central % portion % of the response range. useDataRef = someDataRef; clear params0 params0.rmaxRef = 1.0; params0.expRef = 3; critValue = 0.01; minResp = InvertNakaRushton([params0.rmaxRef 1 params0.expRef],critValue); maxResp = InvertNakaRushton([params0.rmaxRef 1 params0.expRef],1-critValue); minRef = min(someDataRef); maxRef = max(someDataRef); params0.gainRef = (maxResp-minResp)/(maxRef-minRef); params0.offsetRef = minRef-minResp/params0.gainRef; paramsRefNoFit = params0; lumVals = logspace(log10(someDataRef(1)),log10(someDataRef(end)),1000); lumVals = logspace(-3,0,1000); ySub = params0.gainRef*(lumVals-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRefForRemap = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); respRefRemapped = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefForRemap)/params0.gainRef+params0.offsetRef); %remapFig = figure; clf; hold on %plot(respRefForRemap,respRefRemapped,'r','LineWidth',2); %xlim([0 1]); %ylim(yDataLim); %xlabel('Visual Response'); %ylabel('Predicted Reflectance Match'); % cd(figPrefix); % % % if SARAH_TEST_DATA; % % else % savefig(['ResponseRemapping' num2str(whichDataSet) '.pdf'],remapFig,'pdf'); % save(['ResponseRemappingData' num2str(whichDataSet)],'respRefForRemap','respRefRemapped'); % % end % cd .. % someDataMatch = 10.^[someData(whichData,:)]; okIndex = find(~isnan(someDataMatch)); useDataMatch = someDataMatch(okIndex); useDataRef = someDataRef(okIndex); if whichDataSet == 1 subplot(3,3,whichData,'FontSize', 4); hold on else subplot(3,2,whichData,'FontSize', 4); hold on end plot(log10(useDataMatch),log10(useDataRef),'bo','MarkerFaceColor','b','MarkerSize',4); xlabel('Log10 Target Lum', 'FontSize',6); ylabel('Log10 Standard Lum/Refl', 'FontSize',6); setAverage = size(someData,1); if whichData == setAverage title(['Average' conditionList{i}], 'FontSize',6); else title([subjectList{whichData} ' ' conditionList{i}], 'FontSize',6); end % Parameter search options if (verLessThan('optim','4.1')) error('Your version of the optimization toolbox is too old. Update it.'); end options = optimset('fmincon'); options = optimset(options,'Diagnostics','off','Display','off','LargeScale','off','Algorithm','active-set'); % Initialize match parameters in same way endPointWeight = 0; params0.rmax = params0.rmaxRef; params0.exp = params0.expRef; params0.gain = params0.gainRef; params0.offset = params0.offsetRef; someDataPred0 = PredictNRAffineMatches(someDataRef,params0); %plot(log10(someDataRef),log10(someDataPred0),'y','LineWidth',1); %params0 if whichData == setAverage fprintf(fid,['Dataset ' conditionList{i} ' Average ' '\n']); else fprintf(fid,['Dataset ' conditionList{i} ' ' subjectList{whichData} '\n']); end fprintf(fid,'\tReference params: gain = %0.2g, offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',params0.gainRef,params0.offsetRef,params0.rmaxRef,params0.expRef); % Fit, first just gain x0 = ParamsToList(params0); vlb = [x0(1) x0(2)/100 x0(3:end)]; vub = [x0(1) x0(2)*100 x0(3:end)]; x1 = fmincon(@InlineMinFunction,x0,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x1,params0); someDataPred1 = PredictNRAffineMatches(someDataRef,params0); %plot(log10(someDataPred1),log10(someDataRef),'b','LineWidth',1); %params0 g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tGain only model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); % Fit, gain and offset vlb = [x1(1) x1(2)/100 x1(3) -100*abs(x1(4)) x1(5)]; vub = [x1(1) x1(2)*100 x1(3) 100*abs(x1(4)) x1(5)]; x2 = fmincon(@InlineMinFunction,x1,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x2,params0); someDataPred2 = PredictNRAffineMatches(someDataRef,params0); g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tGain/Offset model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); paramsGainOffset = params0; %params0 % Exp FITEXP = 1; if (FITEXP) vlb = [x2(1) x2(2)/100 x2(3) -100*abs(x2(4)) 0.5]; vub = [x2(1) x2(2)*100 x2(3) 100*abs(x2(4)) 4]; endPointWeight = 10; x3 = fmincon(@InlineMinFunction,x2,[],[],[],[],vlb,vub,[],options); endPointWeight = 0; x3 = fmincon(@InlineMinFunction,x3,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x3,params0); someDataPred3 = PredictNRAffineMatches(someDataRef,params0); else x3 = x2; someDataPred3 = PredictNRAffineMatches(someDataRef,params0); end fprintf(fid,'\tGain/Offset/Exp model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); % Let rMax vary too. This doesn't add much if exponent varies.. Tp the fits, so I % uncluttered plots by removing. Have not looked at whether varying % rMax can be substituted for varying the exponent. FITMAX = 0; if (FITMAX) vlb = [x3(1) x3(2)/100 0.5 -100*abs(x3(4)) x3(5)]; vub = [x3(1) x3(2)*100 2 100*abs(x3(4)) x3(5)]; x = fmincon(@InlineMinFunction,x3,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x,params0); someDataPred = PredictNRAffineMatches(someDataRef,params0); plot(log10(someDataPred3),log10(someDataRef),'k','LineWidth',1.5); %params0 else x = x3; someDataPred = PredictNRAffineMatches(someDataRef,params0); end % Dump of interesting parameters g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tPredicted (actual) black point %0.2g (%0.2g); white point %0.2g (%0.2g)\n',someDataPred(1),someDataMatch(1),someDataPred(end),someDataMatch(end)); fprintf(fid,'\tOne-in predicted black point %0.2g (%0.2g); white point %0.2g (%0.2g)\n',someDataPred(2),someDataMatch(2),someDataPred(end-1),someDataMatch(end-1)); % Plot stuff of interest plot(log10(someDataPred),log10(someDataRef),'r','LineWidth',2); plot(log10(someDataPred2),log10(someDataRef),'g','LineWidth',1); xlim(xDataLim); ylim(yDataLim); % Add plot of response functions for ref and match % Subtract the old offset, and truncate below 0 to zero. % We allow an optional remapping of the response back to the % luminance/reflectance space of the reference matches. This % mapping is static across contexts. This turns out not to % terribly interesting. lumVals = logspace(-2,3,1000); ySub = params0.gainRef*(lumVals-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRefSmooth = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); if (RESPONSE_REMAP) respRefSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefSmooth)/params0.gainRef+params0.offsetRef); end ySub = params0.gainRef*(someDataRef-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); if (RESPONSE_REMAP) respRef = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRef)/params0.gainRef+params0.offsetRef); end ySub = params0.gain*(lumVals-params0.offset); ySub(ySub <= 0) = 0+eps; respMatchSmooth = ComputeNakaRushton([params0.rmax 1 params0.exp],ySub); if (RESPONSE_REMAP) respMatchSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respMatchSmooth)/params0.gainRef+params0.offsetRef); end ySub = params0.gain*(someDataMatch-params0.offset); ySub(ySub <= 0) = 0+eps; respMatch = ComputeNakaRushton([params0.rmax 1 params0.exp],ySub); if (RESPONSE_REMAP) respMatch = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respMatch)/params0.gainRef+params0.offsetRef); end ySub = paramsGainOffset.gain*(lumVals-paramsGainOffset.offset); ySub(ySub <= 0) = 0+eps; respGainOffsetSmooth = ComputeNakaRushton([paramsGainOffset.rmax 1 paramsGainOffset.exp],ySub); if (RESPONSE_REMAP) respGainOffsetSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respGainOffsetSmooth)/params0.gainRef+params0.offsetRef); end ySub = paramsRefNoFit.gainRef*(lumVals-paramsRefNoFit.offsetRef); ySub(ySub <= 0) = 0+eps; respRefNoFitSmooth = ComputeNakaRushton([paramsRefNoFit.rmaxRef 1 paramsRefNoFit.expRef],ySub); % if (RESPONSE_REMAP) % respRefNoFitSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefNoFitSmooth)/params0.gainRef+params0.offsetRef); % end % % % subplot(1,2,2); hold on % % plot(log10(someDataRef),respRef,'ko','MarkerFaceColor','k','MarkerSize',6); % % plot(log10(lumVals),respRefSmooth,'k:','LineWidth',2); % % %plot(log10(lumVals),respRefNoFitSmooth,'b','LineWidth',1); % % % % plot(log10(someDataMatch),respMatch,'bo','MarkerFaceColor','b','MarkerSize',8); % % plot(log10(lumVals),respMatchSmooth,'r','LineWidth',2); % % plot(log10(lumVals),respGainOffsetSmooth,'g','LineWidth',1); % % % xlim(xDataLim); % if (RESPONSE_REMAP) % ylim(yDataLim); % ylabel('Remapped Response'); % else % ylim([0 1.2]); % ylabel('Response'); % end % xlabel('Log10 luminance'); % % % Save figure cd(figPrefix); savefig(['TestFit_' num2str(whichDataSet) ' ' conditionList{i} 'ALL.pdf'],dataFig,'pdf'); cd('..'); fprintf(fid,'\n'); % %% Fill output summary structure % if (SARAH_TEST_DATA) % % else % summaryStructs(whichData).whitePoint = someDataPred(end); % summaryStructs(whichData).blackPoint = someDataPred(1); % summaryStructs(whichData).range = someDataPred(end) - someDataPred(1); % summaryStructs(whichData).exp = params0.exp; % predictExpFromWB(whichData,1) = summaryStructs(whichData).whitePoint; % predictExpFromWB(whichData,2) = log10(summaryStructs(whichData).range); % expVals(whichData,1) = summaryStructs(whichData).exp; % %% Range versus exp figure % figure(rangeFig) % subplot(1,2,1); hold on % plot(summaryStructs(whichData).range,summaryStructs(whichData).exp,'ro','MarkerFaceColor','r','MarkerSize',8); % xlabel('Range'); ylabel('Exponent'); % xlim([0 300]); ylim([0 4]); % subplot(1,2,2); hold on % plot(summaryStructs(whichData).whitePoint,summaryStructs(whichData).exp,'ro','MarkerFaceColor','r','MarkerSize',8); % xlabel('White Point'); ylabel('Exponent'); % xlim([0 300]); ylim([0 4]); % end end end fclose(fid); %% Try to predict exponents % expRegCoefs = predictExpFromWB\expVals; % predictedExpVals = predictExpFromWB*expRegCoefs; % expPredFig = figure; clf; hold on % plot(expVals,predictedExpVals,'ro','MarkerSize',8,'MarkerFaceColor','r'); % plot([0 4],[0 4],'k'); % xlim([0 4]); ylim([0 4]); % xlabel('Exponent'); ylabel('Predicted Exponent'); % axis('square'); %% Write out summary structs % cd(figPrefix); % if (SARAH_TEST_DATA) % % else % WriteStructsToText(['SummaryDataAll', num2str(whichDataSet), '.txt'],summaryStructs); % end % cd('..'); %% Save plot of exponent versus range % cd(figPrefix); % if (SARAH_TEST_DATA) % % else % savefig(['ExpVersusRange', num2str(whichDataSet),'.pdf'],rangeFig,'pdf'); % end % cd('..'); %% INLINE FUNCTION TO BE USED FOR CTF MINIMIZATION. % Inline functions have the feature that any variable they use that is % not defined in the function has its value inherited % from the workspace of wherever they were invoked. % % Variables set here are also in the base workspace, and can change the values of % variables with the same name there. This can produce all sorts of problems, % so be careful. function f = InlineMinFunction(x) paramsInline = ListToParams(x,params0); yPred = PredictNRAffineMatches(useDataRef,paramsInline); yPred(yPred <= 0) = 0 + eps; yDiff = log10(useDataMatch)-log10(yPred); f = sum(yDiff.^2) + endPointWeight*yDiff(1).^2 + endPointWeight*yDiff(end).^2; end %% INLINE FUNCTION TO BE USED FOR REF MINIMIZATION. % Inline functions have the feature that any variable they use that is % not defined in the function has its value inherited % from the workspace of wherever they were invoked. % % Variables set here are also in the base workspace, and can change the values of % variables with the same name there. This can produce all sorts of problems, % so be careful. function f = InlineMinFunctionRef(x) paramsInline = ListToParamsRef(x,params0); % Subtract the old offset, and truncate below 0 to zero ySub = paramsInline.gainRef*(useDataRef-paramsInline.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([paramsInline.rmaxRef 1 paramsInline.expRef],ySub); yDiff = targetRespRef-respRef; f = sum(abs(yDiff)); %f = sum(yDiff.^2); end function [g,geq] = InlineConFunctionRef(x) paramsInline = ListToParamsRef(x,params0); % Subtract the old offset, and truncate below 0 to zero ySub = paramsInline.gainRef*(useDataRef-paramsInline.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([paramsInline.rmaxRef 1 paramsInline.expRef],ySub); yDiff = targetRespRef-respRef; g = max(abs(yDiff))-conTolRef; geq = 0; end end %% Param translation function params = ListToParams(x,params0) params = params0; params.gainRef = x(1); params.gain = x(2); params.rmax = x(3); params.offset = x(4); params.exp = x(5); end function x = ParamsToList(params) x = [params.gainRef params.gain params.rmax params.offset params.exp]; end function params = ListToParamsRef(x,params0) params = params0; params.gainRef = x(1); params.rmaxRef = x(2); params.offsetRef = x(3); params.expRef = x(4); end function x = ParamsToListRef(params) x = [params.gainRef params.rmaxRef params.offsetRef params.expRef]; end
github
BrainardLab/TeachingCode-master
TestPredictNRAffineMatchesAna.m
.m
TeachingCode-master/MatlabTutorials/lightessModelsTutorial/TestPredictNRAffineMatchesAna.m
29,372
utf_8
b34c4e02b1fa332bece2bf4d9fc26526
function TestNRAPredictMatches % TestNRAPredictMatches % % Work out what the little model does for various choices of input % % 12/4/10 dhb Wrote it. % 4/20/11 dhb Lot's of little changes. Switch polarity of data plots %% Clear clear; close all; % Define relevant directories. currentDir = pwd; dataDir = '/Users/Shared/Matlab/Experiments/HDRExperiments/HDRAna'; whichDataSet = 2; %% Choose model parameters and generate predictions, plot. % Let's one explore what the model can do. %DO_PRELIM_STUFF = 0; % if (DO_PRELIM_STUFF) % yRef = logspace(-2,4); % % %% Set up parameters % params0.rmaxRef = 1.0; % params0.gainRef = 10e-4; % params0.offsetRef = 0; % params0.expRef = 2.5; % params0.rmax = 1.01; % params0.gain = 0.5*10e-4; % params0.offset = 1; % params0.exp = 1; % % %% Plot effect of mucking with exponent % figure; clf; hold on % exponents = [1.5 2 2.5]; % for i = 1:length(exponents) % params0.exp = exponents(i); % yMatch{i} = NRAPredictMatches(yRef,params0); % % % Plot % plot(log10(yMatch{i}),log10(yRef),'k','LineWidth',3); % xlim([-3 5]); ylim([-3 5]); % xlabel('Log10 Target Lum'); % ylabel('Log10 Standard Lum/Refl'); % end % end paletteGlossy = [-2.0458e+00 -1.8447e+00 -1.6840e+00 -1.4881e+00 -1.3251e+00 -1.1838e+00 -1.0424e+00 -9.2046e-01 -8.1417e-01 -7.1175e-01 ... -6.2160e-01 -5.3180e-01 -4.5087e-01 -3.7192e-01 -2.9654e-01 -2.2746e-01 -1.6488e-01 -1.0768e-01 -4.3064e-02]; paletteMatte = [ NaN NaN NaN -1.4660 -1.3279 -1.1379 -1.0155 -0.8726 -0.7791 -0.6807 -0.6038 ... -0.5046 -0.4332 -0.3622 -0.3050 -0.2280 -0.1671 -0.0941 -0.0472]; paletteGlossyTruncated = [NaN NaN NaN paletteGlossy(:,4:end)]; %% Fit some matching data SARAH_TEST_DATA = 0; if (SARAH_TEST_DATA) else switch whichDataSet case 1 conditionList = {'FullGlossyfull','FullGlossytruncated', 'FullMattetruncated', 'WhiteGlossyfull','WhiteGlossytruncated', 'WhiteMattetruncated'}; subjectList = {'bam', 'cly', 'flv', 'lta' ,'ncd', 'rpd', 'stg', 'tfm'}; keepSomeData = [ [ -1.3802 -1.2294 -0.9707 -0.7100 -0.3612 0.0249 0.3078 0.5715 0.7699 0.9778 1.0846 1.3089 1.4555 1.5644 1.7196 1.9207 2.0673 2.2239 2.3914]; [ NaN NaN NaN -0.9522 -0.6050 -0.2339 0.1047 0.4402 0.6977 0.8384 1.0023 1.2422 1.4114 1.5759 1.7508 1.9397 2.0528 2.2656 2.4112]; [ NaN NaN NaN -1.0312 -0.7059 -0.2358 0.1020 0.4629 0.6309 0.8030 1.0495 1.1958 1.3473 1.5350 1.6646 1.8909 2.0447 2.2378 2.3792]; [ NaN -0.0746 0.0318 0.2519 0.6330 0.9303 1.1223 1.3450 1.5182 1.7405 1.8143 2.0090 1.9072 2.2261 NaN 2.4317 NaN NaN NaN]; [ NaN NaN NaN -0.0043 0.4266 0.6850 0.9769 1.2355 1.4810 1.6573 1.7507 1.9130 2.0836 2.1939 NaN 2.4042 NaN NaN NaN]; [ NaN NaN NaN 0.0356 0.3936 0.7326 0.9986 1.2143 1.4117 1.5808 1.7714 1.9066 2.0828 2.1358 2.3293 2.3833 NaN NaN NaN];]; case 2 conditionList = {'FullGlossyfull2','FullMattetruncated2', 'Full30Glossyfull2', 'Full30Mattetruncated2', 'White30Glossyfull','White30Mattetruncated', 'Gray30Glossyfull', 'Gray30Mattetruncated'}; subjectList = {'bam', 'cly', 'ncd', 'stg', 'tfm'}; keepSomeData = [ [ -1.0849 -0.9622 -0.8648 -0.6281 -0.3869 -0.1036 0.2128 0.4567 0.7647 0.9488 1.1614 ... 1.3723 1.5101 1.6622 1.7990 1.9214 2.0359 2.2311 2.3199]; [ NaN NaN NaN -0.8392 -0.5873 -0.1825 0.1171 0.4655 0.7031 0.9464 1.1034 ... 1.3530 1.4774 1.6270 1.8231 1.9047 2.1262 2.2451 2.2713] [ NaN NaN NaN NaN NaN 1.2849 1.2088 1.2595 1.3693 1.4580 1.5826 ... 1.7126 1.8139 1.9713 2.1010 2.1720 2.3164 2.4515 2.5170]; [ NaN NaN NaN NaN NaN NaN 1.1963 1.2787 1.3236 1.4529 1.5473 ... 1.6579 1.8419 1.8985 2.0625 2.1901 2.3280 2.4015 2.5215]; [ NaN NaN NaN NaN NaN 1.2475 1.2973 1.3907 1.6027 1.7238 1.8637... 1.9849 2.0992 2.2393 2.3454 2.4286 2.5200 2.5425 2.6196]; [NaN NaN NaN NaN NaN 1.2689 1.2883 1.4364 1.5560 1.7329 1.8336... 1.9731 2.1075 2.2431 2.3248 2.4025 2.5065 2.5691 2.6030]; [ NaN NaN NaN -0.0572 -0.0016 0.0921 0.2724 0.4301 0.5819 0.7071 0.7965 ... 0.9089 1.0300 1.0749 1.1734 1.2381 1.2656 NaN NaN]; [NaN NaN NaN NaN -0.0920 0.0354 0.2398 0.4029 0.5708 0.6956 0.7910... 0.9222 1.0426 1.0873 1.1855 1.2379 NaN NaN NaN];]; case 3 subjectList={'ajh', 'arp', 'kjn', 'orp' ,'rvn'}; conditionList = {'FullGlossyfull3', 'FullGlossyfull4','Full30Glossyfull3','Full30Glossyfull4'... , 'Full1000Glossyfull3', 'FullGray30Glossyfull', 'FullGray1000Glossyfull', ... 'FullMeanPlusGlossyfull', 'Full30MeanPlusGlossyfull', 'FullGray30MeanPlusGlossyfull', 'FullMeanPlusGlossyfull2', 'FullMeanMinusGlossyfull2'}; keepSomeData = [[-1.2469 -1.0194 -0.6968 -0.3888 -0.1960 0.1387 0.3627 0.6095 0.8034 0.8159 ... 0.9833 1.1952 1.3942 1.5388 1.5710 1.7905 2.0848 2.0719 2.3168]; % full3 [ -1.4012 -0.9285 -0.7862 -0.4952 -0.2476 0.0172 0.2259 0.4565 0.5586 0.7049 ... 0.8431 1.0677 1.1933 1.3972 1.6246 1.7266 1.8868 2.1460 2.2618]; % full4 [NaN NaN NaN NaN 1.1345 1.1445 1.2867 1.3138 1.3704 1.5017 ... 1.5732 1.6708 1.7791 1.8904 1.9778 2.0832 2.2022 2.3184 2.4071]; % full30 3 [NaN NaN NaN NaN NaN NaN 1.1932 1.2166 1.2841 1.4061 ... 1.4842 1.6065 1.6801 1.8158 1.9317 2.0486 2.1714 2.2893 2.4259]; % full30 4 [ -0.3140 -0.2027 -0.0686 0.0819 0.2873 0.4310 0.5986 0.7905 0.8960 1.0847 ... 1.2355 1.3290 1.4651 1.6356 1.7116 1.8833 1.9983 2.1780 2.3949]; % full 1000 [ NaN NaN NaN NaN 0.4098 0.4786 0.6039 0.7330 0.8416 0.8923 ... 0.9797 1.1226 1.1993 1.3123 1.4279 1.5174 1.6544 1.6851 NaN]; % full Gray30 [ -1.0961 -0.8952 -0.7221 -0.4952 -0.3652 -0.1803 -0.0603 0.0522 0.3139 0.3222 ... 0.4816 0.6810 0.8161 0.9925 1.1563 1.3792 1.5010 1.6713 1.7328]; % full gray 1000; [-1.2028 -0.9204 -0.6084 -0.2414 -0.0021 0.0723 0.2916 0.5297 0.6825 0.8876 ... 0.9969 1.2277 1.2544 1.4292 1.6247 1.8370 2.0001 2.1447 2.2880]; % full mean plus; [NaN NaN NaN NaN NaN NaN 1.1726 1.2939 1.3940 1.5356 ... 1.5940 1.7435 1.8141 1.9606 2.0642 2.1749 2.3042 2.3794 2.4674]; % full30 mean plus; [NaN NaN NaN NaN 0.4270 0.4158 0.5322 0.6765 0.7749 0.8527 ... 0.9992 1.1176 1.2819 1.3642 1.4917 1.6065 1.6876 NaN NaN]; % fullgray30 [-7.5486e-01 -6.3016e-01 -3.7002e-01 -7.5043e-02 2.5521e-01 4.1869e-01 6.5650e-01 8.2140e-01 9.3936e-01 ... 1.1518e+00 1.3266e+00 1.3894e+00 1.4861e+00 1.7282e+00 1.8061e+00 1.9940e+00 2.1053e+00 2.2826e+00 2.3641e+00]; % fullmeanplus2 [-8.8795e-01 -7.5641e-01 -5.6947e-01 -4.3999e-01 -2.9319e-01 -1.1604e-01 5.8502e-02 2.5986e-01 3.7464e-01 ... 5.2778e-01 6.5286e-01 8.2851e-01 9.8959e-01 1.1379e+00 1.4417e+00 1.6340e+00 1.7811e+00 2.0558e+00 2.1961e+00]; % fullmeanminus ]; end for i = 1:length(conditionList) for j=1:length(subjectList) luminanceMatchesPerChip{i,j} = load(fullfile(dataDir,'data',conditionList{i},subjectList{j},[conditionList{i} '-' subjectList{j} '-TestAverages.txt'])); luminanceMatchesPerChip{i,j} = luminanceMatchesPerChip{i,j}(:, 2:end); % averageLumMatchesPerSubject{j}(:,i) = nanmean(luminanceMatchesPerChip{i,j},2); averageLumMatchesPerSubject{i}(:,j) = nanmean(luminanceMatchesPerChip{i,j},2); end end averageLumMatchesPerSubjectAll{i} = averageLumMatchesPerSubject{i}; %% See how many matches per subject are made. % If less than 3 subjects assigned anything to this chip, drop them. for g = 1: length(averageLumMatchesPerSubject) nSubjectMatches{g} = sum(isnan(averageLumMatchesPerSubject{g}),2); end for g = 1: length(nSubjectMatches) for r = 1:length(nSubjectMatches{g}) if (nSubjectMatches{g}(r) > 2) averageLumMatchesPerSubject{g}(r,:) = nan(1, size(averageLumMatchesPerSubject{g},2)); end end end cd(currentDir); xDataLim = [-2 3]; yDataLim = [-3 0]; fid = fopen(['ANA_TEST_DATA/ParamDump_All' num2str(whichDataSet) '.txt'],'w'); figPrefix = 'ANA_TEST_DATA/'; RESPONSE_REMAP = 0; end % Optional search to find reference parameters that put the responses rougly equally spaced on the y-axis. This isn't theoretically critical, but % seems as good an idea as any. FITREF = 0; if (FITREF) if (verLessThan('optim','4.1')) error('Your version of the optimization toolbox is too old. Update it.'); end options = optimset('fmincon'); options = optimset(options,'Diagnostics','off','Display','iter','LargeScale','off','Algorithm','active-set'); options = optimset(options,'MaxFunEvals',1200); targetRespRef = linspace(critValue,1-critValue,length(someDataRef)); conTolRef = (targetRespRef(2)-targetRespRef(1)); x0 = ParamsToListRef(params0); vlb = [x0(1)/100 x0(2) -100*mean(someDataRef) 1]; vub = [x0(1)*100 x0(2) 100*mean(someDataRef) 4]; x1 = fmincon(@InlineMinFunctionRef,x0,[],[],[],[],vlb,vub,@InlineConFunctionRef,options); params0 = ListToParamsRef(x1,params0); end %% Now do the fitting wrt to the reference paramters % rangeFig = figure; rangeFig = figure; dataFig = figure; position = get(gcf,'Position'); position(3) = 1000; position(4) = 400; set(gcf,'Position',position); allData = cell(1,length(conditionList)); for i = 1:length(conditionList) temptemp = []; for j = 1:length(subjectList) temptemp = [temptemp; [averageLumMatchesPerSubject{i}(:,j)']]; end %allDataMean(i,:) = nanmean(temptemp, 1); acrossSubjectLumAverages{i} = NaN(size(paletteGlossy',1),1); for g = 1:size(paletteGlossy',1) okindex = ~isnan(averageLumMatchesPerSubject{i}(g,:)'); tt=mean(averageLumMatchesPerSubject{i}(g,okindex))'; acrossSubjectLumAverages{i}(g,1)=tt; end temptemp = [temptemp; acrossSubjectLumAverages{i}(:)'] ; allData{i} = temptemp; clear temptemp end clear okindex; %% for debugging purposes. for i = 1:length(conditionList) check = keepSomeData(i,:) - acrossSubjectLumAverages{i}(:)'; end %% someData = []; for i = 1:length(conditionList) someData = [someData; acrossSubjectLumAverages{i}(:)']; end check = keepSomeData - someData for whichData = 1:size(someData,1) switch (whichDataSet) case 1 if whichData == 1 || whichData == 4 someDataRef = 10.^[paletteGlossy(1,:)]; elseif whichData == 2 || whichData == 5 someDataRef = 10.^[paletteMatte(1,:)]; elseif whichData == 3 || whichData == 6 someDataRef = 10.^[paletteMatte(1,:)]; end case 2 if whichData == 1 || whichData == 3 || whichData == 5 || whichData == 7 someDataRef = 10.^[paletteGlossy(1,:)]; elseif whichData == 2 || whichData == 4 || whichData == 6 || whichData == 8 someDataRef = 10.^[paletteMatte(1,:)]; end case 3 someDataRef = 10.^[paletteGlossy(1,:)]; end %% Initialize parameters. Set reference rmax to 1 and exponent to 2. Find % gain and offset that map the luminances across the central portion % of the response range. useDataRef = someDataRef; clear params0 params0.rmaxRef = 1.0; params0.expRef = 3; critValue = 0.01; minResp = InvertNakaRushton([params0.rmaxRef 1 params0.expRef],critValue); maxResp = InvertNakaRushton([params0.rmaxRef 1 params0.expRef],1-critValue); minRef = min(someDataRef); maxRef = max(someDataRef); params0.gainRef = (maxResp-minResp)/(maxRef-minRef); params0.offsetRef = minRef-minResp/params0.gainRef; paramsRefNoFit = params0; if whichData == 1 %% Plot of remapping between response and reference log10 % luminance/reflectance lumVals = logspace(log10(someDataRef(1)),log10(someDataRef(end)),1000); lumVals = logspace(-3,0,1000); ySub = params0.gainRef*(lumVals-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRefForRemap = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); respRefRemapped = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefForRemap)/params0.gainRef+params0.offsetRef); remapFig = figure; clf; hold on plot(respRefForRemap,respRefRemapped,'r','LineWidth',2); xlim([0 1]); ylim(yDataLim); xlabel('Visual Response'); ylabel('Predicted Reflectance Match'); cd(figPrefix); %savefig('ResponseRemapping.pdf',remapFig,'pdf'); %save('ResponseRemappingData','respRefForRemap','respRefRemapped'); savefig(['ResponseRemapping' num2str(whichDataSet) '.pdf'],remapFig,'pdf'); save(['ResponseRemappingData' num2str(whichDataSet)],'respRefForRemap','respRefRemapped'); cd .. end someDataMatch = 10.^[someData(whichData,:)] okIndex = find(~isnan(someDataMatch)); useDataMatch = someDataMatch(okIndex); useDataRef = someDataRef(okIndex); figure(dataFig); clf; subplot(1,2,1); hold on plot(log10(useDataMatch),log10(useDataRef),'bo','MarkerFaceColor','b','MarkerSize',8); xlabel('Log10 Target Lum'); ylabel('Log10 Standard Lum/Refl'); % Parameter search options if (verLessThan('optim','4.1')) error('Your version of the optimization toolbox is too old. Update it.'); end options = optimset('fmincon'); options = optimset(options,'Diagnostics','off','Display','off','LargeScale','off','Algorithm','active-set'); % Initialize match parameters in same way endPointWeight = 0; params0.rmax = params0.rmaxRef; params0.exp = params0.expRef; params0.gain = params0.gainRef; params0.offset = params0.offsetRef; someDataPred0 = NRAPredictMatches(someDataRef,params0); %plot(log10(someDataRef),log10(someDataPred0),'y','LineWidth',1); %params0 fprintf(fid,['Dataset ' conditionList{whichData} '\n']); fprintf(fid,'\tReference params: gain = %0.2g, offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',params0.gainRef,params0.offsetRef,params0.rmaxRef,params0.expRef); % Fit, first just gain x0 = ParamsToList(params0); vlb = [x0(1) x0(2)/100 x0(3:end)]; vub = [x0(1) x0(2)*100 x0(3:end)]; x1 = fmincon(@InlineMinFunction,x0,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x1,params0); someDataPred1 = NRAPredictMatches(someDataRef,params0); %plot(log10(someDataPred1),log10(someDataRef),'b','LineWidth',1); %params0 g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tGain only model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); % Fit, gain and offset vlb = [x1(1) x1(2)/100 x1(3) -100*abs(x1(4)) x1(5)]; vub = [x1(1) x1(2)*100 x1(3) 100*abs(x1(4)) x1(5)]; x2 = fmincon(@InlineMinFunction,x1,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x2,params0); someDataPred2 = NRAPredictMatches(someDataRef,params0); g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tGain/Offset model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); paramsGainOffset = params0; %params0 % Exp FITEXP = 1; if (FITEXP) vlb = [x2(1) x2(2)/100 x2(3) -100*abs(x2(4)) 0.5]; vub = [x2(1) x2(2)*100 x2(3) 100*abs(x2(4)) 4]; endPointWeight = 10; x3 = fmincon(@InlineMinFunction,x2,[],[],[],[],vlb,vub,[],options); endPointWeight = 0; x3 = fmincon(@InlineMinFunction,x3,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x3,params0); someDataPred3 = NRAPredictMatches(someDataRef,params0); else x3 = x2; someDataPred3 = NRAPredictMatches(someDataRef,params0); end fprintf(fid,'\tGain/Offset/Exp model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); % Let rMax vary too. This doesn't add much if exponent varies.. Tp the fits, so I % uncluttered plots by removing. Have not looked at whether varying % rMax can be substituted for varying the exponent. FITMAX = 0; if (FITMAX) vlb = [x3(1) x3(2)/100 0.5 -100*abs(x3(4)) x3(5)]; vub = [x3(1) x3(2)*100 2 100*abs(x3(4)) x3(5)]; x = fmincon(@InlineMinFunction,x3,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x,params0); someDataPred = NRAPredictMatches(someDataRef,params0); plot(log10(someDataPred3),log10(someDataRef),'k','LineWidth',1.5); %params0 else x = x3; someDataPred = NRAPredictMatches(someDataRef,params0); end % Dump of interesting parameters g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tPredicted (actual) black point %0.2g (%0.2g); white point %0.2g (%0.2g)\n',someDataPred(1),someDataMatch(1),someDataPred(end),log10(someDataMatch(end))); fprintf(fid,'\tOne-in predicted black point %0.2g (%0.2g); white point %0.2g (%0.2g)\n',someDataPred(2),someDataMatch(2),someDataPred(end-1),log10(someDataMatch(end-1))); % Plot stuff of interest plot(log10(someDataPred),log10(someDataRef),'r','LineWidth',3); plot(log10(someDataPred2),log10(someDataRef),'g','LineWidth',1); xlim(xDataLim); ylim(yDataLim); % Add plot of response functions for ref and match % Subtract the old offset, and truncate below 0 to zero. % We allow an optional remapping of the response back to the % luminance/reflectance space of the reference matches. This % mapping is static across contexts. This turns out not to % terribly interesting. lumVals = logspace(-2,3,1000); ySub = params0.gainRef*(lumVals-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRefSmooth = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); if (RESPONSE_REMAP) respRefSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefSmooth)/params0.gainRef+params0.offsetRef); end ySub = params0.gainRef*(someDataRef-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); if (RESPONSE_REMAP) respRef = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRef)/params0.gainRef+params0.offsetRef); end ySub = params0.gain*(lumVals-params0.offset); ySub(ySub <= 0) = 0+eps; respMatchSmooth = ComputeNakaRushton([params0.rmax 1 params0.exp],ySub); if (RESPONSE_REMAP) respMatchSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respMatchSmooth)/params0.gainRef+params0.offsetRef); end ySub = params0.gain*(someDataMatch-params0.offset); ySub(ySub <= 0) = 0+eps; respMatch = ComputeNakaRushton([params0.rmax 1 params0.exp],ySub); if (RESPONSE_REMAP) respMatch = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respMatch)/params0.gainRef+params0.offsetRef); end ySub = paramsGainOffset.gain*(lumVals-paramsGainOffset.offset); ySub(ySub <= 0) = 0+eps; respGainOffsetSmooth = ComputeNakaRushton([paramsGainOffset.rmax 1 paramsGainOffset.exp],ySub); if (RESPONSE_REMAP) respGainOffsetSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respGainOffsetSmooth)/params0.gainRef+params0.offsetRef); end ySub = paramsRefNoFit.gainRef*(lumVals-paramsRefNoFit.offsetRef); ySub(ySub <= 0) = 0+eps; respRefNoFitSmooth = ComputeNakaRushton([paramsRefNoFit.rmaxRef 1 paramsRefNoFit.expRef],ySub); if (RESPONSE_REMAP) respRefNoFitSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefNoFitSmooth)/params0.gainRef+params0.offsetRef); end subplot(1,2,2); hold on plot(log10(someDataRef),respRef,'ko','MarkerFaceColor','k','MarkerSize',6); plot(log10(lumVals),respRefSmooth,'k:','LineWidth',2); %plot(log10(lumVals),respRefNoFitSmooth,'b','LineWidth',1); plot(log10(someDataMatch),respMatch,'bo','MarkerFaceColor','b','MarkerSize',8); plot(log10(lumVals),respMatchSmooth,'r','LineWidth',2); plot(log10(lumVals),respGainOffsetSmooth,'g','LineWidth',1); xlim(xDataLim); if (RESPONSE_REMAP) ylim(yDataLim); ylabel('Remapped Response'); else ylim([0 1.2]); ylabel('Response'); end xlabel('Log10 luminance'); % Save figure cd(figPrefix); savefig(['TestFit_' num2str(whichDataSet) ' ' conditionList{whichData} '.pdf'],dataFig,'pdf'); cd('..'); fprintf(fid,'\n'); %% Fill output summary structure if (SARAH_TEST_DATA) summaryStructs(whichData-1).whitePoint = someDataPred(end); summaryStructs(whichData-1).blackPoint = someDataPred(1); summaryStructs(whichData-1).range = someDataPred(end) - someDataPred(1); summaryStructs(whichData-1).exp = params0.exp; predictExpFromWB(whichData-1,1) = summaryStructs(whichData-1).whitePoint; predictExpFromWB(whichData-1,2) = log10(summaryStructs(whichData-1).range); expVals(whichData-1,1) = summaryStructs(whichData-1).exp; %% Range versus exp figure figure(rangeFig) subplot(1,2,1); hold on plot(summaryStructs(whichData-1).range,summaryStructs(whichData-1).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('Range'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); subplot(1,2,2); hold on plot(summaryStructs(whichData-1).whitePoint,summaryStructs(whichData-1).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('White Point'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); else summaryStructs(whichData).whitePoint = someDataPred(end); summaryStructs(whichData).blackPoint = someDataPred(1); summaryStructs(whichData).range = someDataPred(end) - someDataPred(1); summaryStructs(whichData).exp = params0.exp; predictExpFromWB(whichData,1) = summaryStructs(whichData).whitePoint; predictExpFromWB(whichData,2) = log10(summaryStructs(whichData).range); expVals(whichData,1) = summaryStructs(whichData).exp; %% Range versus exp figure figure(rangeFig) subplot(1,2,1); hold on plot(summaryStructs(whichData).range,summaryStructs(whichData).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('Range'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); subplot(1,2,2); hold on plot(summaryStructs(whichData).whitePoint,summaryStructs(whichData).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('White Point'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); end end fclose(fid); %% Try to predict exponents % expRegCoefs = predictExpFromWB\expVals; % predictedExpVals = predictExpFromWB*expRegCoefs; % expPredFig = figure; clf; hold on % plot(expVals,predictedExpVals,'ro','MarkerSize',8,'MarkerFaceColor','r'); % plot([0 4],[0 4],'k'); % xlim([0 4]); ylim([0 4]); % xlabel('Exponent'); ylabel('Predicted Exponent'); % axis('square'); %% Write out summary structs cd(figPrefix); if (SARAH_TEST_DATA) WriteStructsToText('SummaryData.txt',summaryStructs); else WriteStructsToText(['SummaryData', num2str(whichDataSet), '.txt'],summaryStructs); end cd('..'); %% Save plot of exponent versus range cd(figPrefix); if (SARAH_TEST_DATA) savefig(['ExpVersusRange.pdf'],rangeFig,'pdf'); else savefig(['ExpVersusRange', num2str(whichDataSet),'.pdf'],rangeFig,'pdf'); end cd('..'); %% INLINE FUNCTION TO BE USED FOR CTF MINIMIZATION. % Inline functions have the feature that any variable they use that is % not defined in the function has its value inherited % from the workspace of wherever they were invoked. % % Variables set here are also in the base workspace, and can change the values of % variables with the same name there. This can produce all sorts of problems, % so be careful. function f = InlineMinFunction(x) paramsInline = ListToParams(x,params0); yPred = NRAPredictMatches(useDataRef,paramsInline); yPred(yPred <= 0) = 0 + eps; yDiff = log10(useDataMatch)-log10(yPred); f = sum(yDiff.^2) + endPointWeight*yDiff(1).^2 + endPointWeight*yDiff(end).^2; end %% INLINE FUNCTION TO BE USED FOR REF MINIMIZATION. % Inline functions have the feature that any variable they use that is % not defined in the function has its value inherited % from the workspace of wherever they were invoked. % % Variables set here are also in the base workspace, and can change the values of % variables with the same name there. This can produce all sorts of problems, % so be careful. function f = InlineMinFunctionRef(x) paramsInline = ListToParamsRef(x,params0); % Subtract the old offset, and truncate below 0 to zero ySub = paramsInline.gainRef*(useDataRef-paramsInline.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([paramsInline.rmaxRef 1 paramsInline.expRef],ySub); yDiff = targetRespRef-respRef; f = sum(abs(yDiff)); %f = sum(yDiff.^2); end function [g,geq] = InlineConFunctionRef(x) paramsInline = ListToParamsRef(x,params0); % Subtract the old offset, and truncate below 0 to zero ySub = paramsInline.gainRef*(useDataRef-paramsInline.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([paramsInline.rmaxRef 1 paramsInline.expRef],ySub); yDiff = targetRespRef-respRef; g = max(abs(yDiff))-conTolRef; geq = 0; end end %% Param translation function params = ListToParams(x,params0) params = params0; params.gainRef = x(1); params.gain = x(2); params.rmax = x(3); params.offset = x(4); params.exp = x(5); end function x = ParamsToList(params) x = [params.gainRef params.gain params.rmax params.offset params.exp]; end function params = ListToParamsRef(x,params0) params = params0; params.gainRef = x(1); params.rmaxRef = x(2); params.offsetRef = x(3); params.expRef = x(4); end function x = ParamsToListRef(params) x = [params.gainRef params.rmaxRef params.offsetRef params.expRef]; end
github
BrainardLab/TeachingCode-master
TestPredictNRAffineMatchesContol.m
.m
TeachingCode-master/MatlabTutorials/lightessModelsTutorial/TestPredictNRAffineMatchesContol.m
21,771
utf_8
3fb8e64c27a74be3bd8a49675a9464b0
function TestPredictNRAffineMatchesContol % TestPredictNRAffineMatchesControl % % Fit the model through the control conditions. % % 05/20/11 ar Adapded it in order to Model bunch of old controls previously done by Sarah. %% Clear clear; close all; % Define relevant directories. currentDir = pwd; dataDir = '/Users/Shared/Matlab/Experiments/HDRExperiments/HDRAna'; whichDataSet = 1; %% Choose model parameters and generate predictions, plot. % Let's one explore what the model can do. %DO_PRELIM_STUFF = 0; % if (DO_PRELIM_STUFF) % yRef = logspace(-2,4); % % %% Set up parameters % params0.rmaxRef = 1.0; % params0.gainRef = 10e-4; % params0.offsetRef = 0; % params0.expRef = 2.5; % params0.rmax = 1.01; % params0.gain = 0.5*10e-4; % params0.offset = 1; % params0.exp = 1; % % %% Plot effect of mucking with exponent % figure; clf; hold on % exponents = [1.5 2 2.5]; % for i = 1:length(exponents) % params0.exp = exponents(i); % yMatch{i} = NRAPredictMatches(yRef,params0); % % % Plot % plot(log10(yMatch{i}),log10(yRef),'k','LineWidth',3); % xlim([-3 5]); ylim([-3 5]); % xlabel('Log10 Target Lum'); % ylabel('Log10 Standard Lum/Refl'); % end % end %% Palette Values from Sarah's old experiments. paletteGlossy = [ -2.1460 -1.8211 -1.7097 -1.5066 -1.3266 -1.1874 -1.0410 -0.9402 -0.8007 -0.7012 -0.6070 ... -0.5109 -0.4395 -0.3639 -0.3139 -0.2053 -0.1452 -0.0880 -0.0307]; paletteMatte = [ NaN NaN NaN -1.3619 -1.3298 -1.1938 -0.9993 -0.9174 -0.8027 -0.7206 -0.6117 ... -0.5474 -0.4374 -0.3707 -0.2806 -0.2226 -0.1525 -0.1009 -0.0419 ]; %% Fit some matching data SARAH_TEST_DATA = 0; if (SARAH_TEST_DATA) else switch whichDataSet case 1 conditionList = {'SIonGlossy','SIoffGlossy', 'SIoldMatte', 'fMonGlossy','fMoffGlossy', 'fMoldMatte',}; % subjectList = {'bam', 'cly', 'flv', 'lta' ,'ncd', 'rpd', 'stg', 'tfm'}; someData = [[-1.1820 -0.7709 -0.5714 -0.2102 -0.0518 0.1396 0.3406 0.4518 0.6188 0.8408 0.9734 1.1930 1.2922 1.4202 1.5267 1.6482 1.7918 2.0094 2.2232 ]; [ -1.2288 -0.7391 -0.3809 -0.2950 -0.1586 0.1467 0.2993 0.4713 0.6734 0.7679 0.9406 1.0131 1.2507 1.3145 1.4443 1.6137 1.7227 2.0653 2.1752]; [ NaN NaN NaN -0.5785 -0.2625 -0.0359 0.2090 0.4355 0.5728 0.7679 0.9699 1.1320 1.2803 1.4505 1.6429 1.7727 1.8928 2.0566 2.1480]; [-1.1133 -0.7398 -0.4359 -0.1763 0.0267 0.3351 0.5433 0.7359 0.8915 1.0952 1.2348 1.3061 1.4766 1.6375 1.7163 1.9082 1.9294 2.1959 2.1790]; [-1.2353 -0.4408 -0.3123 -0.1259 0.1121 0.2837 0.4506 0.7405 0.9927 0.9704 1.2497 1.4010 1.4841 1.6258 1.6844 1.7980 2.0851 2.1959 2.2573]; [ NaN NaN NaN -0.6949 -0.2629 0.0446 0.3898 0.5828 0.8021 1.0371 1.0989 1.3152 1.4972 1.6377 1.7715 1.9127 2.0254 2.1249 2.2717]; ] end cd(currentDir); xDataLim = [-2 3]; yDataLim = [-3 0]; fid = fopen(['ANA_TEST_DATA/ParamDump_Control' num2str(whichDataSet) '.txt'],'w'); figPrefix = 'ANA_TEST_DATA/'; RESPONSE_REMAP = 0; end % Optional search to find reference parameters that put the responses rougly equally spaced on the y-axis. This isn't theoretically critical, but % seems as good an idea as any. FITREF = 0; if (FITREF) if (verLessThan('optim','4.1')) error('Your version of the optimization toolbox is too old. Update it.'); end options = optimset('fmincon'); options = optimset(options,'Diagnostics','off','Display','iter','LargeScale','off','Algorithm','active-set'); options = optimset(options,'MaxFunEvals',1200); targetRespRef = linspace(critValue,1-critValue,length(someDataRef)); conTolRef = (targetRespRef(2)-targetRespRef(1)); x0 = ParamsToListRef(params0); vlb = [x0(1)/100 x0(2) -100*mean(someDataRef) 1]; vub = [x0(1)*100 x0(2) 100*mean(someDataRef) 4]; x1 = fmincon(@InlineMinFunctionRef,x0,[],[],[],[],vlb,vub,@InlineConFunctionRef,options); params0 = ListToParamsRef(x1,params0); end %% Now do the fitting wrt to the reference paramters % rangeFig = figure; rangeFig = figure; dataFig = figure; position = get(gcf,'Position'); position(3) = 1000; position(4) = 400; set(gcf,'Position',position); % allData = cell(1,length(conditionList)); % for i = 1:length(conditionList) % temptemp = []; % for j = 1:length(subjectList) % temptemp = [temptemp; [averageLumMatchesPerSubject{i}(:,j)']]; % end % %allDataMean(i,:) = nanmean(temptemp, 1); % acrossSubjectLumAverages{i} = NaN(size(paletteGlossy',1),1); % for g = 1:size(paletteGlossy',1) % okindex = ~isnan(averageLumMatchesPerSubject{i}(g,:)'); % tt=mean(averageLumMatchesPerSubject{i}(g,okindex))'; % acrossSubjectLumAverages{i}(g,1)=tt; % end % temptemp = [temptemp; acrossSubjectLumAverages{i}(:)'] ; % allData{i} = temptemp; % clear temptemp % end % clear okindex; % %% for debugging purposes. % for i = 1:length(conditionList) % check = keepSomeData(i,:) - acrossSubjectLumAverages{i}(:)'; % end % %% % someData = []; % for i = 1:length(conditionList) % someData = [someData; acrossSubjectLumAverages{i}(:)']; % end for whichData = 1:size(someData,1) switch (whichDataSet) case 1 if whichData == 1 || whichData == 2 || whichData == 4 || whichData == 5 someDataRef = 10.^[paletteGlossy(1,:)]; elseif whichData == 3 || whichData == 6 someDataRef = 10.^[paletteMatte(1,:)]; end end %% Initialize parameters. Set reference rmax to 1 and exponent to 2. Find % gain and offset that map the luminances across the central portion % of the response range. useDataRef = someDataRef; clear params0 params0.rmaxRef = 1.0; params0.expRef = 3; critValue = 0.01; minResp = InvertNakaRushton([params0.rmaxRef 1 params0.expRef],critValue); maxResp = InvertNakaRushton([params0.rmaxRef 1 params0.expRef],1-critValue); minRef = min(someDataRef); maxRef = max(someDataRef); params0.gainRef = (maxResp-minResp)/(maxRef-minRef); params0.offsetRef = minRef-minResp/params0.gainRef; paramsRefNoFit = params0; if whichData == 1 %% Plot of remapping between response and reference log10 % luminance/reflectance lumVals = logspace(log10(someDataRef(1)),log10(someDataRef(end)),1000); lumVals = logspace(-3,0,1000); ySub = params0.gainRef*(lumVals-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRefForRemap = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); respRefRemapped = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefForRemap)/params0.gainRef+params0.offsetRef); remapFig = figure; clf; hold on plot(respRefForRemap,respRefRemapped,'r','LineWidth',2); xlim([0 1]); ylim(yDataLim); xlabel('Visual Response'); ylabel('Predicted Reflectance Match'); cd(figPrefix); %savefig('ResponseRemapping.pdf',remapFig,'pdf'); %save('ResponseRemappingData','respRefForRemap','respRefRemapped'); savefig(['ResponseRemappingControl' num2str(whichDataSet) '.pdf'],remapFig,'pdf'); save(['ResponseRemappingDataControl' num2str(whichDataSet)],'respRefForRemap','respRefRemapped'); cd .. end someDataMatch = 10.^[someData(whichData,:)]; okIndex = find(~isnan(someDataMatch)); useDataMatch = someDataMatch(okIndex); useDataRef = someDataRef(okIndex); figure(dataFig); clf; subplot(1,2,1); hold on plot(log10(useDataMatch),log10(useDataRef),'bo','MarkerFaceColor','b','MarkerSize',8); xlabel('Log10 Target Lum'); ylabel('Log10 Standard Lum/Refl'); % Parameter search options if (verLessThan('optim','4.1')) error('Your version of the optimization toolbox is too old. Update it.'); end options = optimset('fmincon'); options = optimset(options,'Diagnostics','off','Display','off','LargeScale','off','Algorithm','active-set'); % Initialize match parameters in same way endPointWeight = 0; params0.rmax = params0.rmaxRef; params0.exp = params0.expRef; params0.gain = params0.gainRef; params0.offset = params0.offsetRef; someDataPred0 = NRAPredictMatches(someDataRef,params0); %plot(log10(someDataRef),log10(someDataPred0),'y','LineWidth',1); %params0 fprintf(fid,['Dataset ' conditionList{whichData} '\n']); fprintf(fid,'\tReference params: gain = %0.2g, offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',params0.gainRef,params0.offsetRef,params0.rmaxRef,params0.expRef); % Fit, first just gain x0 = ParamsToList(params0); vlb = [x0(1) x0(2)/100 x0(3:end)]; vub = [x0(1) x0(2)*100 x0(3:end)]; x1 = fmincon(@InlineMinFunction,x0,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x1,params0); someDataPred1 = NRAPredictMatches(someDataRef,params0); %plot(log10(someDataPred1),log10(someDataRef),'b','LineWidth',1); %params0 g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tGain only model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); % Fit, gain and offset vlb = [x1(1) x1(2)/100 x1(3) -100*abs(x1(4)) x1(5)]; vub = [x1(1) x1(2)*100 x1(3) 100*abs(x1(4)) x1(5)]; x2 = fmincon(@InlineMinFunction,x1,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x2,params0); someDataPred2 = NRAPredictMatches(someDataRef,params0); g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tGain/Offset model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); paramsGainOffset = params0; %params0 % Exp FITEXP = 1; if (FITEXP) vlb = [x2(1) x2(2)/100 x2(3) -100*abs(x2(4)) 0.5]; vub = [x2(1) x2(2)*100 x2(3) 100*abs(x2(4)) 4]; endPointWeight = 10; x3 = fmincon(@InlineMinFunction,x2,[],[],[],[],vlb,vub,[],options); endPointWeight = 0; x3 = fmincon(@InlineMinFunction,x3,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x3,params0); someDataPred3 = NRAPredictMatches(someDataRef,params0); else x3 = x2; someDataPred3 = NRAPredictMatches(someDataRef,params0); end fprintf(fid,'\tGain/Offset/Exp model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); % Let rMax vary too. This doesn't add much if exponent varies.. Tp the fits, so I % uncluttered plots by removing. Have not looked at whether varying % rMax can be substituted for varying the exponent. FITMAX = 0; if (FITMAX) vlb = [x3(1) x3(2)/100 0.5 -100*abs(x3(4)) x3(5)]; vub = [x3(1) x3(2)*100 2 100*abs(x3(4)) x3(5)]; x = fmincon(@InlineMinFunction,x3,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x,params0); someDataPred = NRAPredictMatches(someDataRef,params0); plot(log10(someDataPred3),log10(someDataRef),'k','LineWidth',1.5); %params0 else x = x3; someDataPred = NRAPredictMatches(someDataRef,params0); end % Dump of interesting parameters g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tPredicted (actual) black point %0.2g (%0.2g); white point %0.2g (%0.2g)\n',someDataPred(1),someDataMatch(1),someDataPred(end),someDataMatch(end)); fprintf(fid,'\tOne-in predicted black point %0.2g (%0.2g); white point %0.2g (%0.2g)\n',someDataPred(2),someDataMatch(2),someDataPred(end-1),someDataMatch(end-1)); % Plot stuff of interest plot(log10(someDataPred),log10(someDataRef),'r','LineWidth',3); plot(log10(someDataPred2),log10(someDataRef),'g','LineWidth',1); xlim(xDataLim); ylim(yDataLim); % Add plot of response functions for ref and match % Subtract the old offset, and truncate below 0 to zero. % We allow an optional remapping of the response back to the % luminance/reflectance space of the reference matches. This % mapping is static across contexts. This turns out not to % terribly interesting. lumVals = logspace(-2,3,1000); ySub = params0.gainRef*(lumVals-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRefSmooth = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); if (RESPONSE_REMAP) respRefSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefSmooth)/params0.gainRef+params0.offsetRef); end ySub = params0.gainRef*(someDataRef-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); if (RESPONSE_REMAP) respRef = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRef)/params0.gainRef+params0.offsetRef); end ySub = params0.gain*(lumVals-params0.offset); ySub(ySub <= 0) = 0+eps; respMatchSmooth = ComputeNakaRushton([params0.rmax 1 params0.exp],ySub); if (RESPONSE_REMAP) respMatchSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respMatchSmooth)/params0.gainRef+params0.offsetRef); end ySub = params0.gain*(someDataMatch-params0.offset); ySub(ySub <= 0) = 0+eps; respMatch = ComputeNakaRushton([params0.rmax 1 params0.exp],ySub); if (RESPONSE_REMAP) respMatch = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respMatch)/params0.gainRef+params0.offsetRef); end ySub = paramsGainOffset.gain*(lumVals-paramsGainOffset.offset); ySub(ySub <= 0) = 0+eps; respGainOffsetSmooth = ComputeNakaRushton([paramsGainOffset.rmax 1 paramsGainOffset.exp],ySub); if (RESPONSE_REMAP) respGainOffsetSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respGainOffsetSmooth)/params0.gainRef+params0.offsetRef); end ySub = paramsRefNoFit.gainRef*(lumVals-paramsRefNoFit.offsetRef); ySub(ySub <= 0) = 0+eps; respRefNoFitSmooth = ComputeNakaRushton([paramsRefNoFit.rmaxRef 1 paramsRefNoFit.expRef],ySub); if (RESPONSE_REMAP) respRefNoFitSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefNoFitSmooth)/params0.gainRef+params0.offsetRef); end subplot(1,2,2); hold on plot(log10(someDataRef),respRef,'ko','MarkerFaceColor','k','MarkerSize',6); plot(log10(lumVals),respRefSmooth,'k:','LineWidth',2); %plot(log10(lumVals),respRefNoFitSmooth,'b','LineWidth',1); plot(log10(someDataMatch),respMatch,'bo','MarkerFaceColor','b','MarkerSize',8); plot(log10(lumVals),respMatchSmooth,'r','LineWidth',2); plot(log10(lumVals),respGainOffsetSmooth,'g','LineWidth',1); xlim(xDataLim); if (RESPONSE_REMAP) ylim(yDataLim); ylabel('Remapped Response'); else ylim([0 1.2]); ylabel('Response'); end xlabel('Log10 luminance'); % Save figure cd(figPrefix); savefig(['TestFit_Control' num2str(whichDataSet) ' ' conditionList{whichData} '.pdf'],dataFig,'pdf'); cd('..'); fprintf(fid,'\n'); %% Fill output summary structure if (SARAH_TEST_DATA) summaryStructs(whichData-1).whitePoint = someDataPred(end); summaryStructs(whichData-1).blackPoint = someDataPred(1); summaryStructs(whichData-1).range = someDataPred(end) - someDataPred(1); summaryStructs(whichData-1).exp = params0.exp; predictExpFromWB(whichData-1,1) = summaryStructs(whichData-1).whitePoint; predictExpFromWB(whichData-1,2) = log10(summaryStructs(whichData-1).range); expVals(whichData-1,1) = summaryStructs(whichData-1).exp; %% Range versus exp figure figure(rangeFig) subplot(1,2,1); hold on plot(summaryStructs(whichData-1).range,summaryStructs(whichData-1).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('Range'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); subplot(1,2,2); hold on plot(summaryStructs(whichData-1).whitePoint,summaryStructs(whichData-1).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('White Point'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); else summaryStructs(whichData).whitePoint = someDataPred(end); summaryStructs(whichData).blackPoint = someDataPred(1); summaryStructs(whichData).range = someDataPred(end) - someDataPred(1); summaryStructs(whichData).exp = params0.exp; predictExpFromWB(whichData,1) = summaryStructs(whichData).whitePoint; predictExpFromWB(whichData,2) = log10(summaryStructs(whichData).range); expVals(whichData,1) = summaryStructs(whichData).exp; %% Range versus exp figure figure(rangeFig) subplot(1,2,1); hold on plot(summaryStructs(whichData).range,summaryStructs(whichData).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('Range'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); subplot(1,2,2); hold on plot(summaryStructs(whichData).whitePoint,summaryStructs(whichData).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('White Point'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); end end fclose(fid); %% Try to predict exponents expRegCoefs = predictExpFromWB\expVals; predictedExpVals = predictExpFromWB*expRegCoefs; expPredFig = figure; clf; hold on plot(expVals,predictedExpVals,'ro','MarkerSize',8,'MarkerFaceColor','r'); plot([0 4],[0 4],'k'); xlim([0 4]); ylim([0 4]); xlabel('Exponent'); ylabel('Predicted Exponent'); axis('square'); %% Write out summary structs cd(figPrefix); if (SARAH_TEST_DATA) WriteStructsToText('SummaryDataControl.txt',summaryStructs); else WriteStructsToText(['SummaryDataControl', num2str(whichDataSet), '.txt'],summaryStructs); end cd('..'); %% Save plot of exponent versus range cd(figPrefix); if (SARAH_TEST_DATA) savefig(['ExpVersusRangeControl.pdf'],rangeFig,'pdf'); else savefig(['ExpVersusRangeControl', num2str(whichDataSet),'.pdf'],rangeFig,'pdf'); end cd('..'); %% INLINE FUNCTION TO BE USED FOR CTF MINIMIZATION. % Inline functions have the feature that any variable they use that is % not defined in the function has its value inherited % from the workspace of wherever they were invoked. % % Variables set here are also in the base workspace, and can change the values of % variables with the same name there. This can produce all sorts of problems, % so be careful. function f = InlineMinFunction(x) paramsInline = ListToParams(x,params0); yPred = NRAPredictMatches(useDataRef,paramsInline); yPred(yPred <= 0) = 0 + eps; yDiff = log10(useDataMatch)-log10(yPred); f = sum(yDiff.^2) + endPointWeight*yDiff(1).^2 + endPointWeight*yDiff(end).^2; end %% INLINE FUNCTION TO BE USED FOR REF MINIMIZATION. % Inline functions have the feature that any variable they use that is % not defined in the function has its value inherited % from the workspace of wherever they were invoked. % % Variables set here are also in the base workspace, and can change the values of % variables with the same name there. This can produce all sorts of problems, % so be careful. function f = InlineMinFunctionRef(x) paramsInline = ListToParamsRef(x,params0); % Subtract the old offset, and truncate below 0 to zero ySub = paramsInline.gainRef*(useDataRef-paramsInline.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([paramsInline.rmaxRef 1 paramsInline.expRef],ySub); yDiff = targetRespRef-respRef; f = sum(abs(yDiff)); %f = sum(yDiff.^2); end function [g,geq] = InlineConFunctionRef(x) paramsInline = ListToParamsRef(x,params0); % Subtract the old offset, and truncate below 0 to zero ySub = paramsInline.gainRef*(useDataRef-paramsInline.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([paramsInline.rmaxRef 1 paramsInline.expRef],ySub); yDiff = targetRespRef-respRef; g = max(abs(yDiff))-conTolRef; geq = 0; end end %% Param translation function params = ListToParams(x,params0) params = params0; params.gainRef = x(1); params.gain = x(2); params.rmax = x(3); params.offset = x(4); params.exp = x(5); end function x = ParamsToList(params) x = [params.gainRef params.gain params.rmax params.offset params.exp]; end function params = ListToParamsRef(x,params0) params = params0; params.gainRef = x(1); params.rmaxRef = x(2); params.offsetRef = x(3); params.expRef = x(4); end function x = ParamsToListRef(params) x = [params.gainRef params.rmaxRef params.offsetRef params.expRef]; end
github
BrainardLab/TeachingCode-master
TestPredictNRAffineMatches.m
.m
TeachingCode-master/MatlabTutorials/lightessModelsTutorial/TestPredictNRAffineMatches.m
21,578
utf_8
ebf3f7a8b2bbe30f79780c97aeb9448a
function TestPredictNRAffineMatches % TestPredictNRAffineMatches % % Work out what the little model does for various choices of input % % 12/4/10 dhb Wrote it. % 4/20/11 dhb Lot's of little changes. Switch polarity of data plots %% Clear clear; close all; %% Choose model parameters and generate predictions, plot. % Let's one explore what the model can do. DO_PRELIM_STUFF = 0; if (DO_PRELIM_STUFF) yRef = logspace(-2,4); %% Set up parameters params0.rmaxRef = 1.0; params0.gainRef = 10e-4; params0.offsetRef = 0; params0.expRef = 2.5; params0.rmax = 1.01; params0.gain = 0.5*10e-4; params0.offset = 1; params0.exp = 1; %% Plot effect of mucking with exponent figure; clf; hold on exponents = [1.5 2 2.5]; for i = 1:length(exponents) params0.exp = exponents(i); yMatch{i} = PredictNRAffineMatches(yRef,params0); % Plot plot(log10(yMatch{i}),log10(yRef),'k','LineWidth',3); xlim([-3 5]); ylim([-3 5]); xlabel('Log10 Target Lum'); ylabel('Log10 Standard Lum/Refl'); end end %% Fit some matching data SARAH_TEST_DATA = 0; if (SARAH_TEST_DATA) someData = [ ... %[-1.4666 -1.3279 -1.1376 -1.0155 -0.8727 -0.7791 -0.6807 -0.6039 -0.5046 -0.4332 -0.3622 -0.3050 -0.2280 -0.1671 -0.0941 -0.0472]; ... -0.3425 -0.1963 0.0211 0.2595 0.4734 0.5964 0.8080 0.9776 1.1431 1.3214 1.4757 1.6494 1.8117 1.9341 2.0687 2.1320;... NaN -0.7632 -0.6575 -0.4410 -0.3869 -0.2870 -0.0619 -0.0495 0.1377 0.3261 0.5331 0.8137 1.0949 1.2788 1.4755 1.7163;... -0.8488 -0.6492 -0.3507 -0.1405 0.0320 0.1059 0.5055 0.5369 0.6712 0.9123 1.1550 1.4602 1.6382 1.7404 1.9184 2.0872;... -0.7557 -0.5774 -0.3305 -0.0248 0.1117 0.4900 0.5283 0.7715 0.8772 1.0994 1.3277 1.4880 1.7048 1.7955 2.0763 2.1066;... -0.6644 -0.3730 -0.2039 -0.0068 0.2048 0.4702 0.6319 0.8008 0.9775 1.1454 1.4122 1.5620 1.6963 1.8275 1.8847 2.1487;... -0.4542 -0.1567 0.0871 0.3464 0.5848 0.7929 1.0680 1.1379 1.2462 1.4850 1.6129 1.7910 1.9263 1.9863 2.2012 NaN;... -0.3636 -0.1035 0.2051 0.4746 0.7457 0.9043 1.1863 1.2533 1.4154 1.6568 1.7909 1.9330 2.0616 2.0808 2.1693 2.2539;... -0.1974 0.0098 0.2721 0.6128 0.8488 1.0728 1.2161 1.3985 1.4178 1.6738 1.7163 1.9348 1.9615 2.1480 2.1840 2.2982;... -0.2089 0.1448 0.4346 0.7253 0.9232 1.1556 1.3072 1.4958 1.5687 1.7282 1.8244 2.0339 2.0361 2.1448 2.2066 NaN]; someDataRef = 10.^[someData(1,:)]; xDataLim = [-2 3]; yDataLim = [-2 3]; fid = fopen('SARAH_TEST_DATA/ParamDump.txt','w'); figPrefix = 'SARAH_TEST_DATA/'; RESPONSE_REMAP = 0; else someData = [ ... [-2.0458e+00 -1.8447e+00 -1.6840e+00 -1.4881e+00 -1.3251e+00 -1.1838e+00 -1.0424e+00 -9.2046e-01 -8.1417e-01 -7.1175e-01 ... -6.2160e-01 -5.3180e-01 -4.5087e-01 -3.7192e-01 -2.9654e-01 -2.2746e-01 -1.6488e-01 -1.0768e-01 -4.3064e-02]; %palette [-1.4012 -0.9285 -0.7862 -0.4952 -0.2476 0.0172 0.2259 0.4565 0.5586 0.7049 ... 0.8431 1.0677 1.1933 1.3972 1.6246 1.7266 1.8868 2.1460 2.2618]; % full4 [-1.2469 -1.0194 -0.6968 -0.3888 -0.1960 0.1387 0.3627 0.6095 0.8034 0.8159 ... 0.9833 1.1952 1.3942 1.5388 1.5710 1.7905 2.0848 2.0719 2.3168]; % full3 [NaN NaN NaN NaN 1.1345 1.1445 1.2867 1.3138 1.3704 1.5017 ... 1.5732 1.6708 1.7791 1.8904 1.9778 2.0832 2.2022 2.3184 2.4071]; % full30 3 [NaN NaN NaN NaN NaN NaN 1.1932 1.2166 1.2841 1.4061 ... 1.4842 1.6065 1.6801 1.8158 1.9317 2.0486 2.1714 2.2893 2.4259]; % full30 4 [ -0.3140 -0.2027 -0.0686 0.0819 0.2873 0.4310 0.5986 0.7905 0.8960 1.0847 ... 1.2355 1.3290 1.4651 1.6356 1.7116 1.8833 1.9983 2.1780 2.3949]; % full 1000 [ NaN NaN NaN NaN 0.4098 0.4786 0.6039 0.7330 0.8416 0.8923 ... 0.9797 1.1226 1.1993 1.3123 1.4279 1.5174 1.6544 1.6851 NaN]; % full Gray30 [ -1.0961 -0.8952 -0.7221 -0.4952 -0.3652 -0.1803 -0.0603 0.0522 0.3139 0.3222 ... 0.4816 0.6810 0.8161 0.9925 1.1563 1.3792 1.5010 1.6713 1.7328]; % full gray 1000; [-1.2028 -0.9204 -0.6084 -0.2414 -0.0021 0.0723 0.2916 0.5297 0.6825 0.8876 ... 0.9969 1.2277 1.2544 1.4292 1.6247 1.8370 2.0001 2.1447 2.2880]; % full mean plus; [NaN NaN NaN NaN NaN NaN 1.1726 1.2939 1.3940 1.5356 ... 1.5940 1.7435 1.8141 1.9606 2.0642 2.1749 2.3042 2.3794 2.4674]; % full30 mean plus; [NaN NaN NaN NaN 0.4270 0.4158 0.5322 0.6765 0.7749 0.8527 ... 0.9992 1.1176 1.2819 1.3642 1.4917 1.6065 1.6876 NaN NaN]; % fullgray30 [-7.5486e-01 -6.3016e-01 -3.7002e-01 -7.5043e-02 2.5521e-01 4.1869e-01 6.5650e-01 8.2140e-01 9.3936e-01 ... 1.1518e+00 1.3266e+00 1.3894e+00 1.4861e+00 1.7282e+00 1.8061e+00 1.9940e+00 2.1053e+00 2.2826e+00 2.3641e+00]; % fullmeanplus2 [-8.8795e-01 -7.5641e-01 -5.6947e-01 -4.3999e-01 -2.9319e-01 -1.1604e-01 5.8502e-02 2.5986e-01 3.7464e-01 ... 5.2778e-01 6.5286e-01 8.2851e-01 9.8959e-01 1.1379e+00 1.4417e+00 1.6340e+00 1.7811e+00 2.0558e+00 2.1961e+00]; % fullmeanminus ]; someDataRef = 10.^[someData(1,:)]; xDataLim = [-2 3]; yDataLim = [-3 0]; fid = fopen('ANA_TEST_DATA/ParamDump.txt','w'); figPrefix = 'ANA_TEST_DATA/'; RESPONSE_REMAP = 0; end %% Initialize parameters. Set reference rmax to 1 and exponent to 2. Find % gain and offset that map the luminances across the central portion % of the response range. useDataRef = someDataRef; clear params0 params0.rmaxRef = 1.0; params0.expRef = 3; critValue = 0.01; minResp = InvertNakaRushton([params0.rmaxRef 1 params0.expRef],critValue); maxResp = InvertNakaRushton([params0.rmaxRef 1 params0.expRef],1-critValue); minRef = min(someDataRef); maxRef = max(someDataRef); params0.gainRef = (maxResp-minResp)/(maxRef-minRef); params0.offsetRef = minRef-minResp/params0.gainRef; paramsRefNoFit = params0; % Optional search to find reference parameters that put the responses rougly equally spaced on the y-axis. This isn't theoretically critical, but % seems as good an idea as any. FITREF = 0; if (FITREF) if (verLessThan('optim','4.1')) error('Your version of the optimization toolbox is too old. Update it.'); end options = optimset('fmincon'); options = optimset(options,'Diagnostics','off','Display','iter','LargeScale','off','Algorithm','active-set'); options = optimset(options,'MaxFunEvals',1200); targetRespRef = linspace(critValue,1-critValue,length(someDataRef)); conTolRef = (targetRespRef(2)-targetRespRef(1)); x0 = ParamsToListRef(params0); vlb = [x0(1)/100 x0(2) -100*mean(someDataRef) 1]; vub = [x0(1)*100 x0(2) 100*mean(someDataRef) 4]; x1 = fmincon(@InlineMinFunctionRef,x0,[],[],[],[],vlb,vub,@InlineConFunctionRef,options); params0 = ListToParamsRef(x1,params0); end %% Plot of remapping between response and reference log10 % luminance/reflectance lumVals = logspace(log10(someDataRef(1)),log10(someDataRef(end)),1000); lumVals = logspace(-3,0,1000); ySub = params0.gainRef*(lumVals-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRefForRemap = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); respRefRemapped = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefForRemap)/params0.gainRef+params0.offsetRef); remapFig = figure; clf; hold on plot(respRefForRemap,respRefRemapped,'r','LineWidth',2); xlim([0 1]); ylim(yDataLim); xlabel('Visual Response'); ylabel('Predicted Reflectance Match'); cd(figPrefix); savefig('ResponseRemapping.pdf',remapFig,'pdf'); save('ResponseRemappingData','respRefForRemap','respRefRemapped'); cd .. %% Now do the fitting wrt to the reference paramters rangeFig = figure; dataFig = figure; position = get(gcf,'Position'); position(3) = 1000; position(4) = 400; set(gcf,'Position',position); for whichData = 2:size(someData,1) %clear params0 someDataMatch = 10.^[someData(whichData,:)]; okIndex = find(~isnan(someDataMatch)); useDataMatch = someDataMatch(okIndex); useDataRef = someDataRef(okIndex); figure(dataFig); clf; subplot(1,2,1); hold on plot(log10(useDataMatch),log10(useDataRef),'bo','MarkerFaceColor','b','MarkerSize',8); xlabel('Log10 Target Lum'); ylabel('Log10 Standard Lum/Refl'); % Parameter search options if (verLessThan('optim','4.1')) error('Your version of the optimization toolbox is too old. Update it.'); end options = optimset('fmincon'); options = optimset(options,'Diagnostics','off','Display','off','LargeScale','off','Algorithm','active-set'); % Initialize match parameters in same way endPointWeight = 0; params0.rmax = params0.rmaxRef; params0.exp = params0.expRef; params0.gain = params0.gainRef; params0.offset = params0.offsetRef; someDataPred0 = PredictNRAffineMatches(someDataRef,params0); %plot(log10(someDataRef),log10(someDataPred0),'y','LineWidth',1); %params0 fprintf(fid,'Dataset %d\n',whichData); fprintf(fid,'\tReference params: gain = %0.2g, offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',params0.gainRef,params0.offsetRef,params0.rmaxRef,params0.expRef); % Fit, first just gain x0 = ParamsToList(params0); vlb = [x0(1) x0(2)/100 x0(3:end)]; vub = [x0(1) x0(2)*100 x0(3:end)]; x1 = fmincon(@InlineMinFunction,x0,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x1,params0); someDataPred1 = PredictNRAffineMatches(someDataRef,params0); %plot(log10(someDataPred1),log10(someDataRef),'b','LineWidth',1); %params0 g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tGain only model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); % Fit, gain and offset vlb = [x1(1) x1(2)/100 x1(3) -100*abs(x1(4)) x1(5)]; vub = [x1(1) x1(2)*100 x1(3) 100*abs(x1(4)) x1(5)]; x2 = fmincon(@InlineMinFunction,x1,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x2,params0); someDataPred2 = PredictNRAffineMatches(someDataRef,params0); g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tGain/Offset model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); paramsGainOffset = params0; %params0 % Exp FITEXP = 1; if (FITEXP) vlb = [x2(1) x2(2)/100 x2(3) -100*abs(x2(4)) 0.5]; vub = [x2(1) x2(2)*100 x2(3) 100*abs(x2(4)) 4]; endPointWeight = 10; x3 = fmincon(@InlineMinFunction,x2,[],[],[],[],vlb,vub,[],options); endPointWeight = 0; x3 = fmincon(@InlineMinFunction,x3,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x3,params0); someDataPred3 = PredictNRAffineMatches(someDataRef,params0); else x3 = x2; someDataPred3 = PredictNRAffineMatches(someDataRef,params0); end fprintf(fid,'\tGain/Offset/Exp model: gain = %0.2g, offset = %0.2g, log10 gain change = %0.2g, log10 effective offset = %0.2g, rmax = %0.5g, exp = %0.2g\n',... params0.gain,params0.offset,log10(g),log10(l0),params0.rmax,params0.exp); % Let rMax vary too. This doesn't add much if exponent varies.. Tp the fits, so I % uncluttered plots by removing. Have not looked at whether varying % rMax can be substituted for varying the exponent. FITMAX = 0; if (FITMAX) vlb = [x3(1) x3(2)/100 0.5 -100*abs(x3(4)) x3(5)]; vub = [x3(1) x3(2)*100 2 100*abs(x3(4)) x3(5)]; x = fmincon(@InlineMinFunction,x3,[],[],[],[],vlb,vub,[],options); params0 = ListToParams(x,params0); someDataPred = PredictNRAffineMatches(someDataRef,params0); plot(log10(someDataPred3),log10(someDataRef),'k','LineWidth',1.5); %params0 else x = x3; someDataPred = PredictNRAffineMatches(someDataRef,params0); end % Dump of interesting parameters g = params0.gainRef/params0.gain; l0 = -params0.offsetRef + params0.offset/g; fprintf(fid,'\tPredicted (actual) black point %0.2g (%0.2g); white point %0.2g (%0.2g)\n',someDataPred(1),someDataMatch(1),someDataPred(end),someDataMatch(end)); fprintf(fid,'\tOne-in predicted black point %0.2g (%0.2g); white point %0.2g (%0.2g)\n',someDataPred(2),someDataMatch(2),someDataPred(end-1),someDataMatch(end-1)); % Plot stuff of interest plot(log10(someDataPred),log10(someDataRef),'r','LineWidth',3); plot(log10(someDataPred2),log10(someDataRef),'g','LineWidth',1); xlim(xDataLim); ylim(yDataLim); % Add plot of response functions for ref and match % Subtract the old offset, and truncate below 0 to zero. % We allow an optional remapping of the response back to the % luminance/reflectance space of the reference matches. This % mapping is static across contexts. This turns out not to % terribly interesting. lumVals = logspace(-2,3,1000); ySub = params0.gainRef*(lumVals-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRefSmooth = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); if (RESPONSE_REMAP) respRefSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefSmooth)/params0.gainRef+params0.offsetRef); end ySub = params0.gainRef*(someDataRef-params0.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([params0.rmaxRef 1 params0.expRef],ySub); if (RESPONSE_REMAP) respRef = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRef)/params0.gainRef+params0.offsetRef); end ySub = params0.gain*(lumVals-params0.offset); ySub(ySub <= 0) = 0+eps; respMatchSmooth = ComputeNakaRushton([params0.rmax 1 params0.exp],ySub); if (RESPONSE_REMAP) respMatchSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respMatchSmooth)/params0.gainRef+params0.offsetRef); end ySub = params0.gain*(someDataMatch-params0.offset); ySub(ySub <= 0) = 0+eps; respMatch = ComputeNakaRushton([params0.rmax 1 params0.exp],ySub); if (RESPONSE_REMAP) respMatch = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respMatch)/params0.gainRef+params0.offsetRef); end ySub = paramsGainOffset.gain*(lumVals-paramsGainOffset.offset); ySub(ySub <= 0) = 0+eps; respGainOffsetSmooth = ComputeNakaRushton([paramsGainOffset.rmax 1 paramsGainOffset.exp],ySub); if (RESPONSE_REMAP) respGainOffsetSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respGainOffsetSmooth)/params0.gainRef+params0.offsetRef); end ySub = paramsRefNoFit.gainRef*(lumVals-paramsRefNoFit.offsetRef); ySub(ySub <= 0) = 0+eps; respRefNoFitSmooth = ComputeNakaRushton([paramsRefNoFit.rmaxRef 1 paramsRefNoFit.expRef],ySub); if (RESPONSE_REMAP) respRefNoFitSmooth = log10(InvertNakaRushton([params0.rmaxRef 1 params0.expRef],respRefNoFitSmooth)/params0.gainRef+params0.offsetRef); end subplot(1,2,2); hold on plot(log10(someDataRef),respRef,'ko','MarkerFaceColor','k','MarkerSize',6); plot(log10(lumVals),respRefSmooth,'k:','LineWidth',2); %plot(log10(lumVals),respRefNoFitSmooth,'b','LineWidth',1); plot(log10(someDataMatch),respMatch,'bo','MarkerFaceColor','b','MarkerSize',8); plot(log10(lumVals),respMatchSmooth,'r','LineWidth',2); plot(log10(lumVals),respGainOffsetSmooth,'g','LineWidth',1); xlim(xDataLim); if (RESPONSE_REMAP) ylim(yDataLim); ylabel('Remapped Response'); else ylim([0 1.2]); ylabel('Response'); end xlabel('Log10 luminance'); % Save figure cd(figPrefix); savefig(['TestFit_' num2str(whichData) '.pdf'],dataFig,'pdf'); cd('..'); fprintf(fid,'\n'); %% Fill output summary structure summaryStructs(whichData-1).whitePoint = someDataPred(end); summaryStructs(whichData-1).blackPoint = someDataPred(1); summaryStructs(whichData-1).range = someDataPred(end) - someDataPred(1); summaryStructs(whichData-1).exp = params0.exp; predictExpFromWB(whichData-1,1) = summaryStructs(whichData-1).whitePoint; predictExpFromWB(whichData-1,2) = log10(summaryStructs(whichData-1).range); expVals(whichData-1,1) = summaryStructs(whichData-1).exp; %% Range versus exp figure figure(rangeFig) subplot(1,2,1); hold on plot(summaryStructs(whichData-1).range,summaryStructs(whichData-1).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('Range'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); subplot(1,2,2); hold on plot(summaryStructs(whichData-1).whitePoint,summaryStructs(whichData-1).exp,'ro','MarkerFaceColor','r','MarkerSize',8); xlabel('White Point'); ylabel('Exponent'); xlim([0 300]); ylim([0 4]); end fclose(fid); %% Try to predict exponents expRegCoefs = predictExpFromWB\expVals; predictedExpVals = predictExpFromWB*expRegCoefs; expPredFig = figure; clf; hold on plot(expVals,predictedExpVals,'ro','MarkerSize',8,'MarkerFaceColor','r'); plot([0 4],[0 4],'k'); xlim([0 4]); ylim([0 4]); xlabel('Exponent'); ylabel('Predicted Exponent'); axis('square'); %% Write out summary structs cd(figPrefix); WriteStructsToText('SummaryData.txt',summaryStructs); cd('..'); %% Save plot of exponent versus range cd(figPrefix); savefig(['ExpVersusRange.pdf'],rangeFig,'pdf'); cd('..'); %% INLINE FUNCTION TO BE USED FOR CTF MINIMIZATION. % Inline functions have the feature that any variable they use that is % not defined in the function has its value inherited % from the workspace of wherever they were invoked. % % Variables set here are also in the base workspace, and can change the values of % variables with the same name there. This can produce all sorts of problems, % so be careful. function f = InlineMinFunction(x) paramsInline = ListToParams(x,params0); yPred = PredictNRAffineMatches(useDataRef,paramsInline); yPred(yPred <= 0) = 0 + eps; yDiff = log10(useDataMatch)-log10(yPred); f = sum(yDiff.^2) + endPointWeight*yDiff(1).^2 + endPointWeight*yDiff(end).^2; end %% INLINE FUNCTION TO BE USED FOR REF MINIMIZATION. % Inline functions have the feature that any variable they use that is % not defined in the function has its value inherited % from the workspace of wherever they were invoked. % % Variables set here are also in the base workspace, and can change the values of % variables with the same name there. This can produce all sorts of problems, % so be careful. function f = InlineMinFunctionRef(x) paramsInline = ListToParamsRef(x,params0); % Subtract the old offset, and truncate below 0 to zero ySub = paramsInline.gainRef*(useDataRef-paramsInline.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([paramsInline.rmaxRef 1 paramsInline.expRef],ySub); yDiff = targetRespRef-respRef; f = sum(abs(yDiff)); %f = sum(yDiff.^2); end function [g,geq] = InlineConFunctionRef(x) paramsInline = ListToParamsRef(x,params0); % Subtract the old offset, and truncate below 0 to zero ySub = paramsInline.gainRef*(useDataRef-paramsInline.offsetRef); ySub(ySub <= 0) = 0+eps; respRef = ComputeNakaRushton([paramsInline.rmaxRef 1 paramsInline.expRef],ySub); yDiff = targetRespRef-respRef; g = max(abs(yDiff))-conTolRef; geq = 0; end end %% Param translation function params = ListToParams(x,params0) params = params0; params.gainRef = x(1); params.gain = x(2); params.rmax = x(3); params.offset = x(4); params.exp = x(5); end function x = ParamsToList(params) x = [params.gainRef params.gain params.rmax params.offset params.exp]; end function params = ListToParamsRef(x,params0) params = params0; params.gainRef = x(1); params.rmaxRef = x(2); params.offsetRef = x(3); params.expRef = x(4); end function x = ParamsToListRef(params) x = [params.gainRef params.rmaxRef params.offsetRef params.expRef]; end
github
BrainardLab/TeachingCode-master
rayleighMatchPittDiagramTutorial.m
.m
TeachingCode-master/MatlabTutorials/rayleighMatchPittDiagramTutorial/rayleighMatchPittDiagramTutorial.m
12,692
utf_8
8f45f8a84d49fb70384e5e670eaac090
% Illustrate how Rayleigh matches and Pitt diagram work % % Description: % Simulate Rayleigh match performance and plot in the form of what % I think is called a Pitt diagram. Illustrates the principles of % color vision testing by anomaloscope. % % The simulated anomaloscope allows adjustment of a monochromatic test % and the ratio of two monochromatic primaries in the match. The routine % computes the cone responses to the test and match and from these a % color difference. Matches are predicted for test intensity and mixing % ratio parameters where the color difference is below a criterion. % % The locus of matches is plotted in a Pitt diagram, where the x-axis is % the mixing ratio and the y-axis is the test intensity. The output % diagram reproduces the qualitative features of the one that came in the % manual for our anamoloscope. % % The color difference model is very simple and is briefly described in % the header comments for routine ComputeConfusions, which is at the % bottom of this file. % % You can play around with the modeled observers and the properties of % the simulated anomaloscope by adjusting parameters. % History % 07/03/19 dhb Wrote it. % 09/03/19 dhb, dce Modified to use Asano et al. individual difference % parameters, but in the end does the same thing. % However, and enterprising person can now examine % the effect of changing photopigment density. %% Clear clear; close all; %% Parameters % % Cone lambda max. Set two of them to be the same % to create a dichromat, etc. lambdaMaxes = [ ... [558.9 550 420.7]' ... % Deuteranomalous [538 530.3 420.7]' ... % Protanomalous [558.9 530.3 420.7]' ... % Normal trichromat [558.9 530.3 420.7]' ... % Normal trichromat [558.9 530.3 420.7]']; % Normal trichromat % We actually specify the cones as a shift relative to a % nomogram generated lambda max. These base values are given % here. If you make this match the above, then all shifts % end up as zero. But you can specify deviations, and control % what the shift is relative to. baseLambdaMaxes = [ ... [558.9 550 420.7]' ... [538 530.3 420.7]' ... [558.9 530.3 420.7]' ... [558.9 530.3 420.7]' ... [558.9 530.3 420.7]']; % You can also allow the specified photopigment density to % vary. Enter these as percent changes relative to nominal % values. Can be positive or negative. dphotopigments = [ ... [0 0 0]' ... [0 0 0]' ... [0 0 0]' ... [-90 0 0]' ... [0 90 0]']; theColors = [ 'r' 'g' 'k' 'b' 'y']; theLegend = {'DA' 'PA' 'N' 'LDen' 'MDen' }; % Convert specified lambda max values to shifts from the nominal CIE % standard values. nominalLambdaMax = [558.9 530.3 420.7]; for ii = 1:size(lambdaMaxes,2) indDiffParams(ii).dlens= 0; indDiffParams(ii).dmac = 0; indDiffParams(ii).dphotopigment = dphotopigments(:,ii)'; indDiffParams(ii).lambdaMaxShift = lambdaMaxes(:,ii)' - baseLambdaMaxes(:,ii)'; indDiffParams(ii).shiftType = 'linear'; end % Threshold difference below which it is a match % Fussed with this by hand to adjust plot to taste. thresholdVal = 0.12; % Apparatus range parameters % % Mixing ratio of zero is all green primary, 1 is all red % (assuming shorter primary is first one specified in routine % below.) testIntensityRange = 0.01:0.001:0.4; mixingRatioRange = 0.1:0.001:1; %% Loop to calculate matching locus for each set of cones % % For each set of specified cone pigment lambda max, this % computes the matching range and adds to the Pitt diagram % plot. theFigure = figure; clf; hold on for kk = 1:size(lambdaMaxes,2) %lambdaMax = lambdaMaxes(:,kk); % Function below does the work, based on lambdaMax. % Most operating parameters are set in the function itself. [testIntensity{kk},mixingRatio{kk},matchDiff{kk}] = ComputeConfusions(baseLambdaMaxes(:,kk),indDiffParams(kk),testIntensityRange,mixingRatioRange); % This plot will show the color difference as a function of mixing ratio % and test intensity, one plot per set of lambda max values. I found these % useful for development but not all that instructive in the end, so % they conditional and off by default. diffPlots = false; if (diffPlots) figure; clf; hold on mesh(mixingRatio{kk},testIntensity{kk},matchDiff{kk}); colormap(winter) view([2 14]); zlim([0 2]); xlim([min(mixingRatioRange) max(mixingRatioRange)]); ylim([min(testIntensityRange) max(testIntensityRange)]); xlabel(' Mixing Ratio (0 -> green; 1 -> red)'); ylabel('Test Intensity'); zlabel('Color Difference'); end figure(theFigure); index = find(matchDiff{kk} < thresholdVal); plot(mixingRatio{kk}(index),testIntensity{kk}(index),[theColors(kk) 'o'],'MarkerFaceColor',theColors(kk)); end % Finish off the plot figure(theFigure); xlim([min(mixingRatioRange) max(mixingRatioRange)]); ylim([min(testIntensityRange) max(testIntensityRange)]); xlabel(' Mixing Ratio (0 -> green; 1 -> red)'); ylabel('Test Intensity'); axis('square') legend(theLegend); title('Pitt Diagram') FigureSave('pittDiagram.pdf',theFigure,'pdf'); % Compute locus of confusions in intensity-ratio plot % % Syntax: % [testIntensity,mixingRatio,matchDiff] = ComputeConfusions(lambdaMax,indDiffParams,testIntensityRange,mixingRatioRange) % % Description: % Take lambdaMax values and generate receptor fundamentals. Then loop % over all test intensities and mixing ratio combinations and compute a % measure of color difference between test and corresponding match. % % Many key parameters are specified within this routine rather than % passed, because this is a tutorial script. These include primary % wavelengths, matching primary intensities, parameters describing color % difference calculation, etc. % % The color difference is computed based on vector length in an % post-receptoral contrast space, with different weights applied to the % different post-receptoral contrast directions. It is a very rough and % ready calculation, but this aspect is not key to demonstrate the % principles we are interested in here. % % Inputs: % lambdaMax Column vector of three receptor photopigment lambda % max (wavelength of peak sensitivity) values, in nm. % indDiffParams Passed to ComputeCIEConeFundamentals. % Ignored if empty. If you pass this % structure, then lambdaMax should be empty, % and vice-versa. That is, only adjust the % fundamentals using one of the two available % methods. % testIntensityRange Row vector of test intensities. Arbitrary % units. Values between 0 and 1 are about % right given the way the other parameters are % set. % mixingRatioRange Row vector of g/r mixing ratios. 0 means all % green primary, 1 means all red. Here green % and red are really defined by the % wavelengths of the two matching primaries % defined in the parameters for this routine. % % Outputs: % testIntensity Matrix where entry i,j is the test intensity % given by the ith intensity in testIntensityRange, % and j indexes the mixing ratios. % mixingRatio Matrix where entry i,j is the mixingRatio % given by the jth tentry of mixingRatioRange, % and i indexes the test intensities % matchDiff Matrix of color differences, where entry i,j % corresponds to the test intensity and mixing % ratio in entry i,j of matrices testIntensity % and mixingRatio. % History: % 07/04/19 dhb Made this its own routine. function [testIntensity,mixingRatio,matchDiff] = ComputeConfusions(lambdaMax,indDiffParams,testIntensityRange,mixingRatioRange) % Check % if (~isempty(indDiffParams) & ~isempty(lambdaMax)) % error('Don''t risk using two different ways to adjust cone fundamentals.'); % end % Observer parameters fieldSizeDegs = 2; observerAge = 32; pupilDiameterMM = 3; % Wavelength sampling. Life is easiest at 1 nm sampling. S = [380 1 401]; wls = SToWls(S); % Apparatus parameters. These match the Nagel in wavelengths. testWavelength = 589; matchWavelength1 = 545; matchWavelength2 = 670; % I fussed with these to rotate the D line to be horizontal in the plot. % In real life, they are parameters of the apparatus. matchIntensity1 = 0.12; matchIntensity2 = 2.5; % Compute indices so that we can set spectra below testIndex = find(wls == testWavelength); matchIndex1 = find(wls == matchWavelength1); matchIndex2 = find(wls == matchWavelength2); % Color difference computation parameters. % I fussed with these to make the uncertainty % regions look a bit like those in our device's % diagram. LMRatio = 2; lumWeight = 4; rgWeight = 2; sWeight = 0.5; % Act like we have an added background that suppresses S cone signals. % Otherwise small S cone differences explode when we compute contrast, % because of small denominator. addedBackgroundCones = [0 0 1]'; % Generate match spectra before application of mixing ratio matchSpectrum1 = zeros(size(wls)); matchSpectrum1(matchIndex1) = matchIntensity1; matchSpectrum2 = zeros(size(wls)); matchSpectrum2(matchIndex2) = matchIntensity2; % Generate the cones % % The weird looking call around the CompueCIEConeFundamentals has the net % effect of putting the cone fundamentals into energy units, and then we % normalize each to a peak of one. % % See ComputeCIEConeFundamentals for more info, and for other ways to shift % individual difference parameters. T_cones = EnergyToQuanta(S, ... ComputeCIEConeFundamentals(S,fieldSizeDegs,observerAge,pupilDiameterMM,lambdaMax, ... [],[],[],[],[],indDiffParams)')'; for ii = 1:size(T_cones,1) T_cones(ii,:) = T_cones(ii,:)/max(T_cones(ii,:)); end % Make diagnostic plot of cone fundamentals? FUNDAMENTAL_PLOTS = false; figure; clf; hold on; plot(SToWls(S),T_cones(1,:),'r','LineWidth',2); plot(SToWls(S),T_cones(2,:),'g','LineWidth',2); plot(SToWls(S),T_cones(3,:),'b','LineWidth',2); xlabel('Wavelength'); ylabel('Fundamental'); % Compute cone respones to test and match % % We just do this for all possible test intensities and match ratios, as % specified in the parameters section. % Construct each test and compute cone responses for ii = 1:length(testIntensityRange) testIntensity = testIntensityRange(ii); testSpectrum{ii} = zeros(size(wls)); testSpectrum{ii}(testIndex) = testIntensity; testCones{ii} = T_cones*testSpectrum{ii}; end % Construct each match and compute cone responses for jj = 1:length(mixingRatioRange) mixingRatio = mixingRatioRange(jj); matchSpectrum{jj} = (1-mixingRatio)*matchSpectrum1 + (mixingRatio)*matchSpectrum2; matchCones{jj} = T_cones*matchSpectrum{jj}; end % Compute a measure of color difference for each test/match pairing % % We'll take the test as contributing to the adapting background and compute difference as % cone contrast with respect to that plus the added background as specfied % above. for ii = 1:length(testIntensityRange) for jj = 1:length(mixingRatioRange) effectiveBackgroundCones{ii} = testCones{ii} + addedBackgroundCones; coneContrastDiff = (testCones{ii}-matchCones{jj})./effectiveBackgroundCones{ii}; % Approximate three post-receptoral constrasts lumContrast(ii,jj) = (LMRatio*coneContrastDiff(1)+coneContrastDiff(2))/(LMRatio+1); rgContrast(ii,jj) = coneContrastDiff(1)-coneContrastDiff(2); sContrast(ii,jj) = coneContrastDiff(3); % Take weighted sum of squares. I'm making weights up on grounds % that rg is most sensitive, lum next, and s last. Very back of % envelope and may not be right for uniform fields. testIntensity(ii,jj) = testIntensityRange(ii); mixingRatio(ii,jj) = mixingRatioRange(jj); matchDiff(ii,jj) = sqrt((lumWeight*lumContrast(ii,jj))^2 + (rgWeight*rgContrast(ii,jj))^2 + (sWeight*sContrast(ii,jj))^2); end end end
github
BrainardLab/TeachingCode-master
rayleighMatchPittDiagramTutorialDensity.m
.m
TeachingCode-master/MatlabTutorials/rayleighMatchPittDiagramTutorial/rayleighMatchPittDiagramTutorialDensity.m
12,691
utf_8
b6b9153e08cc556256ce82415e7128ba
% Illustrate how Rayleigh matches and Pitt diagram work % % Description: % Simulate Rayleigh match performance and plot in the form of what % I think is called a Pitt diagram. Illustrates the principles of % color vision testing by anomaloscope. % % The simulated anomaloscope allows adjustment of a monochromatic test % and the ratio of two monochromatic primaries in the match. The routine % computes the cone responses to the test and match and from these a % color difference. Matches are predicted for test intensity and mixing % ratio parameters where the color difference is below a criterion. % % The locus of matches is plotted in a Pitt diagram, where the x-axis is % the mixing ratio and the y-axis is the test intensity. The output % diagram reproduces the qualitative features of the one that came in the % manual for our anamoloscope. % % The color difference model is very simple and is briefly described in % the header comments for routine ComputeConfusions, which is at the % bottom of this file. % % You can play around with the modeled observers and the properties of % the simulated anomaloscope by adjusting parameters. % History % 07/03/19 dhb Wrote it. % 09/03/19 dhb, dce Modified to use Asano et al. individual difference % parameters, but in the end does the same thing. % However, and enterprising person can now examine % the effect of changing photopigment density. %% Clear clear; close all; %% Parameters % % Cone lambda max. Set two of them to be the same % to create a dichromat, etc. lambdaMaxes = [ ... [558.9 550 420.7]' ... % Deuteranomalous [538 530.3 420.7]' ... % Protanomalous [558.9 530.3 420.7]' ... % Normal trichromat [558.9 530.3 420.7]' ... % Normal trichromat [558.9 530.3 420.7]']; % Normal trichromat % We actually specify the cones as a shift relative to a % nomogram generated lambda max. These base values are given % here. If you make this match the above, then all shifts % end up as zero. But you can specify deviations, and control % what the shift is relative to. baseLambdaMaxes = [ ... [558.9 550 420.7]' ... [538 530.3 420.7]' ... [558.9 530.3 420.7]' ... [558.9 530.3 420.7]' ... [558.9 530.3 420.7]']; % You can also allow the specified photopigment density to % vary. Enter these as percent changes relative to nominal % values. Can be positive or negative. dphotopigments = [ ... [0 0 0]' ... [0 0 0]' ... [0 0 0]' ... [-90 0 0]' ... [0 90 0]']; theColors = [ 'r' 'g' 'k' 'b' 'y']; theLegend = {'DA' 'PA' 'N' 'LDen' 'MDen' }; % Convert specified lambda max values to shifts from the nominal CIE % standard values. nominalLambdaMax = [558.9 530.3 420.7]; for ii = 1:size(lambdaMaxes,2) indDiffParams(ii).dlens= 0; indDiffParams(ii).dmac = 0; indDiffParams(ii).dphotopigment = dphotopigments(:,ii)'; indDiffParams(ii).lambdaMaxShift = lambdaMaxes(:,ii)' - baseLambdaMaxes(:,ii)'; indDiffParams(ii).shiftType = 'linear'; end % Threshold difference below which it is a match % Fussed with this by hand to adjust plot to taste. thresholdVal = 0.12; % Apparatus range parameters % % Mixing ratio of zero is all green primary, 1 is all red % (assuming shorter primary is first one specified in routine % below.) testIntensityRange = 0.01:0.001:0.4; mixingRatioRange = 0.1:0.001:1; %% Loop to calculate matching locus for each set of cones % % For each set of specified cone pigment lambda max, this % computes the matching range and adds to the Pitt diagram % plot. theFigure = figure; clf; hold on for kk = 1:size(lambdaMaxes,2) %lambdaMax = lambdaMaxes(:,kk); % Function below does the work, based on lambdaMax. % Most operating parameters are set in the function itself. [testIntensity{kk},mixingRatio{kk},matchDiff{kk}] = ComputeConfusions(baseLambdaMaxes(:,kk),indDiffParams(kk),testIntensityRange,mixingRatioRange); % This plot will show the color difference as a function of mixing ratio % and test intensity, one plot per set of lambda max values. I found these % useful for development but not all that instructive in the end, so % they conditional and off by default. diffPlots = false; if (diffPlots) figure; clf; hold on mesh(mixingRatio{kk},testIntensity{kk},matchDiff{kk}); colormap(winter) view([2 14]); zlim([0 2]); xlim([min(mixingRatioRange) max(mixingRatioRange)]); ylim([min(testIntensityRange) max(testIntensityRange)]); xlabel(' Mixing Ratio (0 -> green; 1 -> red)'); ylabel('Test Intensity'); zlabel('Color Difference'); end figure(theFigure); index = find(matchDiff{kk} < thresholdVal); plot(mixingRatio{kk}(index),testIntensity{kk}(index),[theColors(kk) 'o'],'MarkerFaceColor',theColors(kk)); end % Finish off the plot figure(theFigure); xlim([min(mixingRatioRange) max(mixingRatioRange)]); ylim([min(testIntensityRange) max(testIntensityRange)]); xlabel(' Mixing Ratio (0 -> green; 1 -> red)'); ylabel('Test Intensity'); axis('square') legend(theLegend); title('Pitt Diagram') FigureSave('pittDiagram.pdf',theFigure,'pdf'); % Compute locus of confusions in intensity-ratio plot % % Syntax: % [testIntensity,mixingRatio,matchDiff] = ComputeConfusions(lambdaMax,indDiffParams,testIntensityRange,mixingRatioRange) % % Description: % Take lambdaMax values and generate receptor fundamentals. Then loop % over all test intensities and mixing ratio combinations and compute a % measure of color difference between test and corresponding match. % % Many key parameters are specified within this routine rather than % passed, because this is a tutorial script. These include primary % wavelengths, matching primary intensities, parameters describing color % difference calculation, etc. % % The color difference is computed based on vector length in an % post-receptoral contrast space, with different weights applied to the % different post-receptoral contrast directions. It is a very rough and % ready calculation, but this aspect is not key to demonstrate the % principles we are interested in here. % % Inputs: % lambdaMax Column vector of three receptor photopigment lambda % max (wavelength of peak sensitivity) values, in nm. % indDiffParams Passed to ComputeCIEConeFundamentals. % Ignored if empty. If you pass this % structure, then lambdaMax should be empty, % and vice-versa. That is, only adjust the % fundamentals using one of the two available % methods. % testIntensityRange Row vector of test intensities. Arbitrary % units. Values between 0 and 1 are about % right given the way the other parameters are % set. % mixingRatioRange Row vector of g/r mixing ratios. 0 means all % green primary, 1 means all red. Here green % and red are really defined by the % wavelengths of the two matching primaries % defined in the parameters for this routine. % % Outputs: % testIntensity Matrix where entry i,j is the test intensity % given by the ith intensity in testIntensityRange, % and j indexes the mixing ratios. % mixingRatio Matrix where entry i,j is the mixingRatio % given by the jth tentry of mixingRatioRange, % and i indexes the test intensities % matchDiff Matrix of color differences, where entry i,j % corresponds to the test intensity and mixing % ratio in entry i,j of matrices testIntensity % and mixingRatio. % History: % 07/04/19 dhb Made this its own routine. function [testIntensity,mixingRatio,matchDiff] = ComputeConfusions(lambdaMax,indDiffParams,testIntensityRange,mixingRatioRange) % Check % if (~isempty(indDiffParams) & ~isempty(lambdaMax)) % error('Don''t risk using two different ways to adjust cone fundamentals.'); % end % Observer parameters fieldSizeDegs = 2; observerAge = 32; pupilDiameterMM = 3; % Wavelength sampling. Life is easiest at 1 nm sampling. S = [380 1 401]; wls = SToWls(S); % Apparatus parameters. These match the Nagel in wavelengths. testWavelength = 589; matchWavelength1 = 545; matchWavelength2 = 670; % I fussed with these to rotate the D line to be horizontal in the plot. % In real life, they are parameters of the apparatus. matchIntensity1 = 0.12; matchIntensity2 = 2.5; % Compute indices so that we can set spectra below testIndex = find(wls == testWavelength); matchIndex1 = find(wls == matchWavelength1); matchIndex2 = find(wls == matchWavelength2); % Color difference computation parameters. % I fussed with these to make the uncertainty % regions look a bit like those in our device's % diagram. LMRatio = 2; lumWeight = 4; rgWeight = 2; sWeight = 0.5; % Act like we have an added background that suppresses S cone signals. % Otherwise small S cone differences explode when we compute contrast, % because of small denominator. addedBackgroundCones = [0 0 1]'; % Generate match spectra before application of mixing ratio matchSpectrum1 = zeros(size(wls)); matchSpectrum1(matchIndex1) = matchIntensity1; matchSpectrum2 = zeros(size(wls)); matchSpectrum2(matchIndex2) = matchIntensity2; % Generate the cones % % The weird looking call around the CompueCIEConeFundamentals has the net % effect of putting the cone fundamentals into energy units, and then we % normalize each to a peak of one. % % See ComputeCIEConeFundamentals for more info, and for other ways to shift % individual difference parameters. T_cones = EnergyToQuanta(S, ... ComputeCIEConeFundamentals(S,fieldSizeDegs,observerAge,pupilDiameterMM,lambdaMax, ... [],[],[],[],[],indDiffParams)')'; for ii = 1:size(T_cones,1) T_cones(ii,:) = T_cones(ii,:)/max(T_cones(ii,:)); end % Make diagnostic plot of cone fundamentals? FUNDAMENTAL_PLOTS = true; figure; clf; hold on; plot(SToWls(S),T_cones(1,:),'r','LineWidth',2); plot(SToWls(S),T_cones(2,:),'g','LineWidth',2); plot(SToWls(S),T_cones(3,:),'b','LineWidth',2); xlabel('Wavelength'); ylabel('Fundamental'); % Compute cone respones to test and match % % We just do this for all possible test intensities and match ratios, as % specified in the parameters section. % Construct each test and compute cone responses for ii = 1:length(testIntensityRange) testIntensity = testIntensityRange(ii); testSpectrum{ii} = zeros(size(wls)); testSpectrum{ii}(testIndex) = testIntensity; testCones{ii} = T_cones*testSpectrum{ii}; end % Construct each match and compute cone responses for jj = 1:length(mixingRatioRange) mixingRatio = mixingRatioRange(jj); matchSpectrum{jj} = (1-mixingRatio)*matchSpectrum1 + (mixingRatio)*matchSpectrum2; matchCones{jj} = T_cones*matchSpectrum{jj}; end % Compute a measure of color difference for each test/match pairing % % We'll take the test as contributing to the adapting background and compute difference as % cone contrast with respect to that plus the added background as specfied % above. for ii = 1:length(testIntensityRange) for jj = 1:length(mixingRatioRange) effectiveBackgroundCones{ii} = testCones{ii} + addedBackgroundCones; coneContrastDiff = (testCones{ii}-matchCones{jj})./effectiveBackgroundCones{ii}; % Approximate three post-receptoral constrasts lumContrast(ii,jj) = (LMRatio*coneContrastDiff(1)+coneContrastDiff(2))/(LMRatio+1); rgContrast(ii,jj) = coneContrastDiff(1)-coneContrastDiff(2); sContrast(ii,jj) = coneContrastDiff(3); % Take weighted sum of squares. I'm making weights up on grounds % that rg is most sensitive, lum next, and s last. Very back of % envelope and may not be right for uniform fields. testIntensity(ii,jj) = testIntensityRange(ii); mixingRatio(ii,jj) = mixingRatioRange(jj); matchDiff(ii,jj) = sqrt((lumWeight*lumContrast(ii,jj))^2 + (rgWeight*rgContrast(ii,jj))^2 + (sWeight*sContrast(ii,jj))^2); end end end
github
BrainardLab/TeachingCode-master
exploreMemBiasTutorial.m
.m
TeachingCode-master/MatlabTutorials/exploreMemBiasTutorial/exploreMemBiasTutorial.m
10,221
utf_8
53a869d8f12366bbce514f93cab2eb50
function exploreMemBiasTutorial % exploreMemBiasTutorial % % Work out predictions of a very simple memory model. The idea is to see % what the predictions are if we start with the ideas that % a) there is a non-linear transduction between the stimulus variable and perceptual response. % b) noise is added in the perceptual domain % c) noise can have different variance depending on delay. % % This is worked out for the circular stimulus variable hue, but nothing % much would change in the model for an intensive variable. % % 4/25/09 dhb Started on it. %% Clear clear; close all; %% Parameters % Specify precision as noise of a Gaussian variable. There is a separate % noise for the test stimulus and the comparison stimulus. This is % because we want to model both simultaneous presentation and delayed, and we'll % do this by mucking with the variances. testSd = 0.06; comparisonSd = 0.06; scaleBase = 2*max([testSd comparisonSd]); testHueRawIndex = 300; nComparison = 100; nMatchSimulate = 10000; nPsychoSimulate = 1000; nFitSimulate = nPsychoSimulate; nStimulusHues = 600; respType = 'naka'; responseOrder = 2; responseCoeefs = 0.1*[0 1 1 0.4 0.25 0.5 0.2]; fittype = 'c'; %% Generate the non-linear response function. This is veridical plus a sum of some % sinusoids. stimulusHues = linspace(0,1,nStimulusHues); stimulusHues = [stimulusHues]; switch (respType) case 'fourier' responseFun = stimulusHues + ComputeFourierModel(responseCoeefs,stimulusHues); case 'naka' responseFun = (stimulusHues.^6)./(stimulusHues.^6 + 0.4.^6); end sumPlot = figure('WindowStyle','docked'); clf; subplot(4,1,1); hold on plot(stimulusHues,responseFun,'r','LineWidth',2); xlim([0 1]); ylim([0 1]); xlabel('Hue','FontSize',16); ylabel('Response','FontSize',16); title('Underlying Psychophysical Function','FontSize',16); %% Compute psychometric function through a specified test hue. Response will be 1 (aka "yes") % if subjects thinks comparison presentation is of higher perceptual hue, 0 (aka "no") otherwise. testHueIndex = testHueRawIndex; testHue = stimulusHues(testHueIndex); meanResponseTest = responseFun(testHueIndex); comparisonIndices = testHueIndex-nComparison:testHueIndex+nComparison; comparisonHues = stimulusHues(comparisonIndices); for i = 1:length(comparisonIndices) meanResponseComparison = responseFun(comparisonIndices(i)); probYes(i) = SimulateProbYes(meanResponseTest,meanResponseComparison,testSd,comparisonSd,nPsychoSimulate); %#ok<AGROW> end % Fit simulated data pfitdata = [comparisonHues', probYes', nFitSimulate*ones(size(probYes'))]; pfitstruct = pfit(pfitdata,'no plot','matrix_format','xyn', ... 'shape', fittype, 'n_intervals', 1, 'runs',0, 'sens',0, ... 'compute_stats', 0, 'cuts', [0.5], 'verbose', 0); probYesFit = psigpsi(fittype, pfitstruct.params.est, comparisonHues'); pse = findthreshold(fittype,pfitstruct.params.est,0.5,'performance'); thresh = findthreshold(fittype,pfitstruct.params.est,0.75,'performance') - ... findthreshold(fittype,pfitstruct.params.est,0.25,'performance'); % Little plot figure('WindowStyle','docked'); clf; hold on plot(comparisonHues,probYes,'ko','MarkerSize',2,'MarkerFaceColor','k'); plot([testHue testHue],[0 0.5],'b'); plot([comparisonHues(1) testHue],[0.5 0.5],'b'); plot(comparisonHues,probYesFit,'r','LineWidth',2); plot([pse pse],[0 0.5],'g'); xlabel('Comparison Hue','FontSize',16); ylabel('Prob "Yes"','FontSize',16); title(sprintf('Psychometric function, test hue %g',testHue),'FontSize',16); xlim([comparisonHues(1) comparisonHues(end)]) ylim([0 1]); %% Find average match for each test hue nPrint = 25; theMatchedStimuli = zeros(nMatchSimulate,nStimulusHues-2*nComparison-1); matchProgPlot = figure('WindowStyle','docked'); for t = 1:nStimulusHues-2*nComparison-1 testHueIndex = nComparison+t; testHuesMatch(t) = stimulusHues(testHueIndex); meanResponseTest = responseFun(testHueIndex); noiseDrawsTest = normrnd(0,testSd,nMatchSimulate,1); for i = 1:nMatchSimulate theResponse = meanResponseTest + noiseDrawsTest(i); noiseDrawsComparison = normrnd(0,comparisonSd,size(responseFun)); comparisonResponses = responseFun + noiseDrawsComparison; [nil,index] = min(abs(comparisonResponses-theResponse)); theMatchedStimuli(i,t) = stimulusHues(index(1)); end meanMatch(t) = mean(theMatchedStimuli(:,t)); medianMatch(t) = median(theMatchedStimuli(:,t)); % Diagnostic plot if desired if (rem(t,nPrint) == 0) figure(matchProgPlot); clf; hold on [n,x] = hist(theMatchedStimuli(:,t),25); bar(x,n); plot([testHuesMatch(t) testHuesMatch(t)],[0 1.2*max(n)],'k','LineWidth',2); plot([meanMatch(t) meanMatch(t)],[0 1.2*max(n)],'r','LineWidth',2); %plot([medianMatch(t) medianMatch(t)],[0 1.2*max(n)],'g','LineWidth',2); xlabel('Matches','FontSize',16); ylabel('Count','FontSize',16); xlim([0 1]); ylim([0 1.2*max(n)]); title(sprintf('Match distribution, test hue %0.2g',testHuesMatch(t)),'FontSize',16); drawnow; saveas(matchProgPlot,sprintf('Matches_%g_%g_%0.2g.png',testSd,comparisonSd,testHuesMatch(t)),'png'); fprintf('Computing mean match for test hue %d of %d\n',t,nStimulusHues-2*nComparison-1); end end % Plot of simulated matches figure(sumPlot); subplot(4,1,3); hold on plot(testHuesMatch,meanMatch-testHuesMatch,'r','LineWidth',2); %plot(testHuesMatch,medianMatch-testHuesMatch,'b','LineWidth',2); xlim([0 1]); ylim([-scaleBase scaleBase]); xlabel('Test Hue','FontSize',16); ylabel('Match Bias','FontSize',16); %% Now compute out PSE as a function of test hue, as well as threshold nPrint = 25; progPlot = figure('WindowStyle','docked'); for t = 1:nStimulusHues-2*nComparison-1 testHueIndex = nComparison+t; testHues(t) = stimulusHues(testHueIndex); meanResponseTest = responseFun(testHueIndex); comparisonIndices = testHueIndex-nComparison:testHueIndex+nComparison; comparisonHues = stimulusHues(comparisonIndices); for i = 1:length(comparisonIndices) meanResponseComparison = responseFun(comparisonIndices(i)); probYes(i) = SimulateProbYes(meanResponseTest,meanResponseComparison,testSd,comparisonSd,nPsychoSimulate); %#ok<AGROW> end % Fit pfitdata = [comparisonHues', probYes', nFitSimulate*ones(size(probYes'))]; pfitstruct = pfit(pfitdata,'no plot','matrix_format','xyn', ... 'shape', fittype, 'n_intervals', 1, 'runs',0, 'sens',0, ... 'compute_stats', 0, 'cuts', [0.5], 'verbose', 0); probYesFit = psigpsi(fittype, pfitstruct.params.est, comparisonHues'); pses(t) = findthreshold(fittype,pfitstruct.params.est,0.5,'performance'); threshs(t) = findthreshold(fittype,pfitstruct.params.est,0.75,'performance') - ... findthreshold(fittype,pfitstruct.params.est,0.25,'performance'); % Fit central part centralIndex = nComparison-10:nComparison+10; pfitdata = [comparisonHues(centralIndex)', probYes(centralIndex)', nFitSimulate*ones(size(centralIndex'))]; pfitstruct1 = pfit(pfitdata,'no plot','matrix_format','xyn', ... 'shape', fittype, 'n_intervals', 1, 'runs',0, 'sens',0, ... 'compute_stats', 0, 'cuts', [0.5], 'verbose', 0); probYesFit1 = psigpsi(fittype, pfitstruct1.params.est, comparisonHues(centralIndex)'); pses1(t) = findthreshold(fittype,pfitstruct1.params.est,0.5,'performance'); % Diagnostic plot if desired if (rem(t,nPrint) == 0) figure(progPlot); clf; hold on plot(comparisonHues,probYes,'ko','MarkerSize',2,'MarkerFaceColor','k'); plot(comparisonHues,probYesFit,'r','LineWidth',2); plot(comparisonHues(centralIndex),probYesFit1,'b','LineWidth',2); plot([testHues(t) testHues(t)],[0 1],'b'); plot([pses(t) pses(t)],[0 1],'g'); xlabel('Comparison Hue','FontSize',16); ylabel('Prob "Yes"','FontSize',16); title(sprintf('Psychometric function, test hue %0.2g',testHues(t)),'FontSize',16); xlim([comparisonHues(1) comparisonHues(end)]) xlim([0 1]); ylim([0 1]); drawnow; saveas(progPlot,sprintf('Psycho_%g_%g_%0.2g.png',testSd,comparisonSd,testHues(t)),'png'); fprintf('Computing PSE for test hue %d of %d\n',t,nStimulusHues-2*nComparison-1); end end % Plot of simulated PSEs figure(sumPlot); subplot(4,1,2); hold on plot(testHues,1./threshs,'r','LineWidth',2); xlim([0 1]); %ylim([0 scaleBase]); xlabel('Test Hue','FontSize',16); ylabel('Inverse Threshold','FontSize',16); subplot(4,1,4); hold on plot(testHues,pses-testHues,'r','LineWidth',2); plot(testHues,pses1-testHues,'b','LineWidth',2); xlim([0 1]); ylim([-scaleBase scaleBase]); xlabel('Test Hue','FontSize',16); ylabel('PSE Bias','FontSize',16); saveas(sumPlot,sprintf('Summary_%g_%g.png',testSd,comparisonSd),'png'); end %% Subfunctions function probYes = SimulateProbYes(responseTest,responseComparison,testSd,comparisonSd,nSimulate) % probYes = SimulateProbYes(responseTest,responseComparison,testSd,comparisonSd,nSimulate) % % Simulate out the number of times that the comparison is judged as larger on the response variable % than the test. I'm sure there is an analytic solution, but it's a little tricky because we % allow different standard deviations for the test and comparison noise. % % 4/25/09 dhb Wrote it. diffNoise = normrnd(0,comparisonSd,nSimulate,1)-normrnd(0,testSd,nSimulate,1); nYes = length(find(responseComparison-responseTest+diffNoise > 0)); probYes = nYes/nSimulate; end function ypred = ComputeFourierModel(coeffs,x) % ypred = ComputeFourierModel(coeffs,x) % % ypred = coeffs(1) + coeffs(2)*(sin(2*pi*x) + coeffs(3)*cos(2*pi*x) + coeffs(4)*sin(2*pi*2*x) + coeffs(5)*cos(2*pi*2*x) + ... % % The order of the equation is determined from the length of coeffs. % The input x is assumed to be in the range [0-1]. % % 4/21/09 dhb Wrote it. % Modulation a = coeffs(1); b = coeffs(2); modulation = sin(2*pi*x) + coeffs(3)*cos(2*pi*x); for i = 1:length(coeffs(4:end))/2 modulation = modulation + coeffs(2*(i-1)+4)*sin(2*pi*(i+1)*x) + coeffs(2*(i-1)+5)*cos(2*pi*(i+1)*x); end ypred = a + b*modulation; end
github
BrainardLab/TeachingCode-master
psychofitTutorialYN.m
.m
TeachingCode-master/MatlabTutorials/psychofitTutorial/psychofitTutorialYN.m
6,771
utf_8
875ba9d234f3d08d50560f4097522ab0
function psychofitTutorialYN % psychofitTutorialYN % % Show basic use Palamedes toolboxe to simulate and % fit psychophysical data. This one for Y/N method of constant stimuli. % % You need both the psignifit and Palamedes toolboxes on your path, as well % as the Brainard lab staircase class and the Psychtoolbox. % % 4/30/09 dhb Wrote it. % 10/18/09 dhb Add some fits with Palamedes, just for grins % 10/19/09 dhb Added TAFC example as well as Y/N. Cleaned up and added comments. % 10/19/09 dhb Use staircase class for a TAFC staircase example. % 5/6/11 dhb Fix initial guess of slope for Palamedes. This was inverted, but worked by luck previously. % 10/31/12 dhb Fix what is printed out for Y/N staircase threshold. % dhb Y/N thresh defined as 75% point minus 50% point. % dhb Save figures, and a few more lines on the figs. % dhb Add option to simulate adapting bias. % 11/14/13 dhb Tune up a bunch of little things. % 10/21/14 dhb Added better comments for staircasing stuff. % 11/22/17 dhb Strip down to Y/N Palemedes and ver 1.8.2 of Palemedes. %% Clear clear; close all; %% Specify precision as noise of a Gaussian variable % % Simulated Y/N experiment is for test bigger or less than % comparison. noiseSd = 0.06; testStimulus = 100; nComparisonFit = 100; adaptingBias = 0; nComparison = 10; nSimulate = 40; %% Simulate Y/N psychometric function and fit. The cumulative normal is a pretty natural choice % for y/n psychometric data, and that's what's shown here. % % There are lots of variants to the fitting that could be used, in the sense that we could % allow for lapse rates, etc. But this form should work pretty well for most purposes. It's % always a good idea to plot the fit against the actual data and make sure it is reasonable. % For staircase data, this requires some binning (not demonstrated here.) comparisonStimuli = linspace(testStimulus-4*noiseSd,testStimulus+4*noiseSd,nComparison); comparisonStimuliFit = linspace(testStimulus-4*noiseSd,testStimulus+4*noiseSd,nComparisonFit); for i = 1:nComparison nYes(i) = SimulateProbYes(testStimulus,comparisonStimuli(i),0,noiseSd,nSimulate,adaptingBias); %#ok<AGROW> end % PALAMEDES % Psychometric function form PF = @PAL_CumulativeNormal; % Alternatives: PAL_Gumbel, PAL_Weibull, PAL_CumulativeNormal, PAL_HyperbolicSecant % The first two parameters of the psychometric function define its position and shape. % % The third is the guess rate, which determines the value the function % takes on at low values of x. For a perfect subject this would be 0, % but there might be lapses (see below) for small x as well as high x. % % The fourth parameter is the lapse rate - the asymptotic performance at % high values of x. For a perfect subject, this would be 0, but sometimes % subjects have a "lapse" and get the answer wrong even when the stimulus % is easy to see. We can search over this, but shouldn't allow it to take % on unreasonable values. 0.05 as an upper limit isn't crazy. % % paramsFree is a boolean vector that determins what parameters get % searched over. 1: free parameter, 0: fixed parameter paramsFree = [1 1 1 1]; % Initial guess. Setting the first parameter to the middle of the stimulus % range and the second to 1 puts things into a reasonable ballpark here. paramsValues0 = [mean(comparisonStimuli') 1/((max(comparisonStimuli')-min(comparisonStimuli'))/4) 0 0]; % This puts limits on the range of the lapse rate. And we pass an option % to the fit function that forces the guess and lapse rates to be equal, % which is reasonable for this case. lapseLimits = [0 0.05]; % Set up standard options for Palamedes search options = PAL_minimize('options'); % Fit with Palemedes Toolbox. The parameter constraints match the psignifit parameters above. Some thinking is % required to initialize the parameters sensibly. We know that the mean of the cumulative normal should be % roughly within the range of the comparison stimuli, so we initialize this to the mean. The standard deviation % should be some moderate fraction of the range of the stimuli, so again this is used as the initializer. [paramsValues] = PAL_PFML_Fit(... comparisonStimuli',nYes',nSimulate*ones(size(nYes')), ... paramsValues0,paramsFree,PF,'searchOptions',options, ... 'lapseLimits',lapseLimits,'gammaEQlambda',true); probYesFitPal = PF(paramsValues,comparisonStimuliFit'); psePal = PF(paramsValues,0.5,'inverse'); threshPal = PF(paramsValues,0.75,'inverse')-psePal; % Plot of Y/N simulation. When the red and green overlap (which they do in all my tests), it % means that psignfit and Palamedes agree. figure; clf; hold on plot(comparisonStimuli,nYes/nSimulate,'ko','MarkerSize',6,'MarkerFaceColor','k'); plot([testStimulus testStimulus],[0 1],'b'); plot(comparisonStimuliFit,probYesFitPal,'g','LineWidth',1); plot([psePal psePal],[0 1],'g','LineWidth',1); plot([psePal psePal+threshPal],[0.75 0.75],'g','LineWidth',1); xlabel('Comparison','FontSize',16); ylabel('Prob "Yes"','FontSize',16); title(sprintf('Y/N psychometric function'),'FontSize',16); xlim([comparisonStimuli(1) comparisonStimuli(end)]) ylim([0 1]); if (exist('FigureSave','file')) FigureSave('PsychoYN',gcf,'pdf'); else saveas('gcf','PsychoYN','pdf'); end % Printout of interesting parameters. fprintf('Y/N simulated data\n'); fprintf('Palamedes pse: %g, thresh: %g\n',psePal,threshPal); fprintf('\n'); end %% Subfunctions for simulating observer function nYes = SimulateProbYes(responseTest,responseComparison,testSd,comparisonSd,nSimulate,adaptingBias) % probYes = SimulateProbYes(responseTest,responseComparison,testSd,comparisonSd,nSimulate,adaptingBias) % % Simulate out the number of times that the comparison is judged as larger on the response variable % than the test. I'm sure there is an analytic solution, but it's a little tricky because we % allow different standard deviations for the test and comparison noise. % % Assume experiment is based on comparison of noisy draws from underlying comparison and test % distributions. You can also think of responseTest as a criterion. Passing testSd = 0 makes % the criterion noise free, and other testSd may be thought of as criterial noise. % % The parameter adaptingBias is expressed in the same units as the internal response, and is subtracted % from the comparison response before the decision. It simulates an adaptive effect. Typically passed % as zero. It could also be regarded as a criterion that is shifted from the standard, if you are % thinking in TSD terms. % % 4/25/09 dhb Wrote it. diffNoise = normrnd(0,comparisonSd,nSimulate,1)-normrnd(0,testSd,nSimulate,1); nYes = length(find(responseComparison-adaptingBias-responseTest+diffNoise > 0)); end
github
BrainardLab/TeachingCode-master
psychofitTutorialTAFCStaircase.m
.m
TeachingCode-master/MatlabTutorials/psychofitTutorial/psychofitTutorialTAFCStaircase.m
8,302
utf_8
493bbea8ee0a6593d8f99f7e9e661094
function psychofitTutorialTAFCStaircase % psychofitTutorialTAFCStaircase % % Show a staircase procedure and illustrate how to aggregate data and fit. % % You need the Palamedes toolboxe (1.8.2) and BrainardLabToolbox for this to work. % 10/30/17 dhb Separated out and updated. %% Clear clear; close all; %% Specify precision as noise of a Gaussian variable % % Simulation parameters noiseSd = 0.06; testStimulus = 100; nComparisonFit = 100; nComparison = 10; nSimulate = 40; nComparisonSds = 4; thresholdCriterionCorrect = 0.75; baseStepSize = 0.10; %% Set up stimulus range comparisonStimuli = linspace(testStimulus,testStimulus+nComparisonSds*noiseSd,nComparison); comparisonStimuliFit = linspace(testStimulus,testStimulus+nComparisonSds*noiseSd,nComparisonFit); %% Staircase type. You can specify either 'quest' or 'standard'. staircaseType = 'standard'; %% Do a staircase for a TAFC experiment. Uses our Staircase class. % The code below runs either 1 or 3 interleaved staircases. % The use of 1 or 3 is hard-coded, with parameters for each % set in the switch statement below nInterleavedStaircases = 3; maxDelta = max(comparisonStimuli)-testStimulus; minDelta = 0.01; % Initialize staircases. Initialization is slightly different for 'standard' % and 'quest' versions. All parameters other than 'MaxValue' and 'MinValue' % are required, and this is enforced by the class constructor function. % % The logic for TAFC staircases is similar to Y/N, but we want to set % ups/downs or criterionCorr to aim above 50%, whereas in Y/N we typically % aim at 50%. for k = 1:nInterleavedStaircases % Set starting value for the staircase at a random level between % min and max. initialDelta = (maxDelta-minDelta)*3*rand(1)+minDelta; switch(staircaseType) case 'standard' stepSizes = [2*baseStepSize baseStepSize baseStepSize/4]; switch (nInterleavedStaircases) case 1 % Parameters for just one staircase numTrialsPerStaircase = 50; nUps = [2]; nDowns = [1]; case 3 % Parameters for three interleaved % Can also make the up/down rule vary % across the staircases, to spread trials % a little more. numTrialsPerStaircase = 30; nUps = [2 2 2]; nDowns = [1 1 1]; otherwise error('Don''t know how to deal with specified number of staircases'); end st{k} = Staircase(staircaseType,initialDelta, ... 'StepSizes', stepSizes, 'NUp', nUps(k), 'NDown', nDowns(k), ... 'MaxValue', maxDelta, 'MinValue', minDelta); otherwise error('Unknown staircase type specified'); end end % Simulate interleaved staircases for i = 1:numTrialsPerStaircase order = Shuffle(1:nInterleavedStaircases); for k = 1:nInterleavedStaircases comparisonDelta = getCurrentValue(st{order(k)}); response = SimulateTAFC(testStimulus,testStimulus+comparisonDelta,noiseSd,noiseSd,1); st{order(k)} = updateForTrial(st{order(k)},comparisonDelta,response); end end % Analyze staircase data valuesStair = []; responsesStair = []; for k = 1:nInterleavedStaircases threshStair(k) = getThresholdEstimate(st{k}); [valuesSingleStair{k},responsesSingleStair{k}] = getTrials(st{k}); valuesStair = [valuesStair valuesSingleStair{k}]; responsesStair = [responsesStair responsesSingleStair{k}]; end [meanValues,nCorrectStair,nTrialsStair] = GetAggregatedStairTrials(valuesStair,responsesStair,10); % Palamedes fit % % Fit with Palemedes Toolbox. The parameter constraints match the psignifit parameters above. Again, some % thought is required to initialize reasonably. The threshold parameter is reasonably taken to be in the % range of the comparison stimuli, where here 0 means that the comparison is the same as the test. The % second parameter should be on the order of 1/2, so we just hard code that. As with Y/N, really want to % plot the fit against the data to make sure it is reasonable in practice. % Define what psychometric functional form to fit. % % Alternatives: PAL_Gumbel, PAL_Weibull, PAL_CumulativeNormal, PAL_HyperbolicSecant PF = @PAL_Weibull; % The first two parameters of the Weibull define its shape. % % The third is the guess rate, which determines the value the function % takes on at x = 0. For TAFC, this should be locked at 0.5. % % The fourth parameter is the lapse rate - the asymptotic performance at % high values of x. For a perfect subject, this would be 0, but sometimes % subjects have a "lapse" and get the answer wrong even when the stimulus % is easy to see. We can search over this, but shouldn't allow it to take % on unreasonable values. 0.05 as an upper limit isn't crazy. % % paramsFree is a boolean vector that determins what parameters get % searched over. 1: free parameter, 0: fixed parameter paramsFree = [1 1 0 1]; % Initial guess. Setting the first parameter to the middle of the stimulus % range and the second to 1 puts things into a reasonable ballpark here. paramsValues0 = [mean(comparisonStimuli'-testStimulus) 1 0.5 0.01]; % This puts limits on the range of the lapse rate lapseLimits = [0 0.05]; % Set up standard options for Palamedes search options = PAL_minimize('options'); % Do the search to get the parameters [paramsValues] = PAL_PFML_Fit(... valuesStair',responsesStair',ones(size(responsesStair')), ... paramsValues0,paramsFree,PF,'searchOptions',options,'lapseLimits',lapseLimits); probCorrFitStair = PF(paramsValues,comparisonStimuliFit'-testStimulus); threshPalStair = PF(paramsValues,thresholdCriterionCorrect,'inverse'); % Figure stairFig = figure; clf; colors = ['r' 'g' 'b' 'k' 'y' 'c']; subplot(1,2,1); hold on for k = 1:nInterleavedStaircases xvalues = 1:numTrialsPerStaircase; index = find(responsesSingleStair{k} == 0); plot(xvalues,valuesSingleStair{k},[colors(k) '-']); plot(xvalues,valuesSingleStair{k},[colors(k) 'o'],'MarkerFaceColor',colors(k),'MarkerSize',6); if (~isempty(index)) plot(xvalues(index),valuesSingleStair{k}(index),[colors(k) 'o'],'MarkerFaceColor','w','MarkerSize',6); end plot(xvalues,threshStair(k)*ones(1,numTrialsPerStaircase),colors(k)); end xlabel('Trial Number','FontSize',16); ylabel('Level','FontSize',16); title(sprintf('TAFC staircase plot'),'FontSize',16); subplot(1,2,2); hold on plot(meanValues,nCorrectStair./nTrialsStair,'ko','MarkerSize',6,'MarkerFaceColor','k'); plot(comparisonStimuliFit-testStimulus,probCorrFitStair,'r','LineWidth',2); plot([threshPalStair threshPalStair],[0 thresholdCriterionCorrect],'r','LineWidth',2); xlabel('Delta Stimulus','FontSize',16); ylabel('Prob Correct','FontSize',16); title(sprintf('TAFC staircase psychometric function'),'FontSize',16); xlim([comparisonStimuli(1)-testStimulus comparisonStimuli(end)-testStimulus]) ylim([0 1]); if (exist('FigureSave','file')) FigureSave('StaircaseFC',gcf','pdf'); else saveas(gcf','StaircaseFC','pdf'); end fprintf('Staircase simulated data\n'); for k = 1:nInterleavedStaircases fprintf('\tTAFC staircase %d threshold estimate: %g\n',k,threshStair(k)); end fprintf('Palamedes''s threshold estimate from staircase data: %g\n',threshPalStair); end %% Subfunctions for simulating observer function nCorrect = SimulateTAFC(responseTest,responseComparison,testSd,comparisonSd,nSimulate) % nCorrect = SimulateTAFC(responseTest,responseComparison,testSd,comparisonSd,nSimulate) % % Simulate out the number of times that a TAFC task is done correctly, with judgment greater % corresponding to greater noisy response. % % 4/25/09 dhb Wrote it. nCorrect = 0; for i = 1:nSimulate responseTestNoise = responseTest+normrnd(0,testSd,1,1); responseComparisonNoise = responseComparison+normrnd(0,comparisonSd,1,1); if (responseComparison > responseTest & responseComparisonNoise > responseTestNoise) nCorrect = nCorrect+1; elseif (responseComparison <= responseTest & responseComparisonNoise <= responseTestNoise) nCorrect = nCorrect+1; end end end
github
BrainardLab/TeachingCode-master
psychofitTutorial2014.m
.m
TeachingCode-master/MatlabTutorials/psychofitTutorial/psychofitTutorial2014.m
22,190
utf_8
0385fcfe145686c5be6fb0f57f0c1129
function psychofitTutorial % psychofitTutorial2014 % % Show basic use of psignifit and Palamedes toolboxes to simulate and % fit psychophysical data. Has cases for Y/N and TAFC, and shows % both method of constant stimuli and staircase procedures. % % This is set up for our local version of psignifit, where the function psi has been % renamed psigpsi to avoid a name conflict with MATLAB's own psi function. % % You need both the psignifit and Palamedes toolboxes on your path, as well % as the Brainard lab staircase class and the Psychtoolbox. % % * [NOTE: DHB - This is a somewhat outdated version, as both psignifit and % Palamedes have changed since this was written. And, it does not use % mQUESTPlus. Starting to update parts in a new version today, % 4/30/09 dhb Wrote it. % 10/18/09 dhb Add some fits with Palamedes, just for grins % 10/19/09 dhb Added TAFC example as well as Y/N. Cleaned up and added comments. % 10/19/09 dhb Use staircase class for a TAFC staircase example. % 5/6/11 dhb Fix initial guess of slope for Palamedes. This was inverted, but worked by luck previously. % 10/31/12 dhb Fix what is printed out for Y/N staircase threshold. % dhb Y/N thresh defined as 75% point minus 50% point. % dhb Save figures, and a few more lines on the figs. % dhb Add option to simulate adapting bias. % 11/14/13 dhb Tune up a bunch of little things. % 10/21/14 dhb Added better comments for staircasing stuff. %% Clear clear; close all; clear classes; %% Specify precision as noise of a Gaussian variable % % Simulated Y/N experiment is for test bigger or less than % comparison. noiseSd = 0.06; testStimulus = 100; nComparisonFit = 100; adaptingBias = 0; nComparison = 10; nSimulate = 40; %% Staircase type. You can specify either 'quest' or 'standard'. staircaseType = 'standard'; %% Simulate Y/N psychometric function and fit. The cumulative normal is a pretty natural choice % for y/n psychometric data, and that's what's shown here. % % There are lots of variants to the fitting that could be used, in the sense that we could % allow for lapse rates, etc. But this form should work pretty well for most purposes. It's % always a good idea to plot the fit against the actual data and make sure it is reasonable. % For staircase data, this requires some binning (not demonstrated here.) comparisonStimuli = linspace(testStimulus-4*noiseSd,testStimulus+4*noiseSd,nComparison); comparisonStimuliFit = linspace(testStimulus-4*noiseSd,testStimulus+4*noiseSd,nComparisonFit); for i = 1:nComparison nYes(i) = SimulateProbYes(testStimulus,comparisonStimuli(i),0,noiseSd,nSimulate,adaptingBias); %#ok<AGROW> end % PSIGNIFIT % Fit simulated data, psignifit. These parameters do a one interval (y/n) fit. Both lambda (lapse rate) and % gamma (value for -Inf input) are locked at 0. fittype = 'c'; pfitdata = [comparisonStimuli', nYes', nSimulate*ones(size(nYes'))]; pfitstruct = pfit(pfitdata,'no plot','matrix_format','xrn', ... 'shape', fittype, 'n_intervals', 1, 'runs', 0, 'sens', 0, ... 'compute_stats', 0, 'cuts', [0.5], 'verbose', 0, 'fix_lambda',0,'fix_gamma',0); probYesFitPsig = psigpsi(fittype, pfitstruct.params.est, comparisonStimuliFit'); psePsig = findthreshold(fittype,pfitstruct.params.est,0.5,'performance'); threshPsig = findthreshold(fittype,pfitstruct.params.est,0.75,'performance') - ... findthreshold(fittype,pfitstruct.params.est,0.5,'performance'); % PALAMEDES % Fit with Palemedes Toolbox. The parameter constraints match the psignifit parameters above. Some thinking is % required to initialize the parameters sensibly. We know that the mean of the cumulative normal should be % roughly within the range of the comparison stimuli, so we initialize this to the mean. The standard deviation % should be some moderate fraction of the range of the stimuli, so again this is used as the initializer. PF = @PAL_CumulativeNormal; % Alternatives: PAL_Gumbel, PAL_Weibull, PAL_CumulativeNormal, PAL_HyperbolicSecant PFI = @PAL_inverseCumulativeNormal; paramsFree = [1 1 0 0]; % 1: free parameter, 0: fixed parameter paramsValues0 = [mean(comparisonStimuli') 1/((max(comparisonStimuli')-min(comparisonStimuli'))/4) 0 0]; options = optimset('fminsearch'); % Type help optimset options.TolFun = 1e-09; % Increase required precision on LL options.Display = 'off'; % Suppress fminsearch messages lapseLimits = [0 1]; % Limit range for lambda [paramsValues] = PAL_PFML_Fit(... comparisonStimuli',nYes',nSimulate*ones(size(nYes')), ... paramsValues0,paramsFree,PF,'searchOptions',options, ... 'lapseLimits',lapseLimits); probYesFitPal = PF(paramsValues,comparisonStimuliFit'); psePal = PFI(paramsValues,0.5); threshPal = PFI(paramsValues,0.75)-PFI(paramsValues,0.5); % Plot of Y/N simulation. When the red and green overlap (which they do in all my tests), it % means that psignfit and Palamedes agree. figure; clf; hold on plot(comparisonStimuli,nYes/nSimulate,'ko','MarkerSize',6,'MarkerFaceColor','k'); plot([testStimulus testStimulus],[0 1],'b'); plot(comparisonStimuliFit,probYesFitPsig,'r','LineWidth',2); plot(comparisonStimuliFit,probYesFitPal,'g','LineWidth',1); plot([psePsig psePsig],[0 1],'r','LineWidth',2); plot([psePal psePal],[0 1],'g','LineWidth',1); plot([psePsig psePsig+threshPsig],[0.75 0.75],'r','LineWidth',2); plot([psePal psePal+threshPal],[0.75 0.75],'g','LineWidth',1); xlabel('Comparison','FontSize',16); ylabel('Prob "Yes"','FontSize',16); title(sprintf('Y/N psychometric function'),'FontSize',16); xlim([comparisonStimuli(1) comparisonStimuli(end)]) ylim([0 1]); if (exist('FigureSave','file')) FigureSave('PsychoYN',gcf,'pdf'); else saveas('gcf','PsychoYN','pdf'); end % Printout of interesting parameters. fprintf('Y/N simulated data\n'); fprintf('Psignifit pse: %g, thresh: %g\n',psePsig,threshPsig); fprintf('Palamedes pse: %g, thresh: %g\n',psePal,threshPal); fprintf('\n'); %% Do a staircase for a Y/N experiment. Uses our Staircase class. % The code below runs three interleaved staircases. % For 'quest', three different criterion percent correct values are used. % For 'standard', three different up/down rules are used. % The use of 3 is hard-coded, in the sense that the vector lengths of the % criterion/up-down vectors must match this number. % % The variables maxDelta and minDelta below represent the range of trial values % that the staircase will range between. numTrialsPerStaircase = 50; maxDelta = max(comparisonStimuli)-testStimulus; minDelta = -maxDelta; % Initialize staircases. Initialization is slightly different for 'standard' % and 'quest' versions. All parameters other than 'MaxValue' and 'MinValue' % are required, and this is enforced by the class constructor function. nInterleavedStaircases = 3; for k = 1:nInterleavedStaircases % Set starting value for the staircase at a random level between % min and max. initialDelta = (maxDelta-minDelta)*rand(1)+minDelta; switch(staircaseType) case 'standard' % The staircase starts at the largest step size and decreases with % each reversal. When it gets to the minimum value in the list, it % stays there. stepSizes = [maxDelta/2 maxDelta/4 maxDelta/8]; % Set the up/dow rule for each staircase. N-Up, M-Down means (counterintuitively) % that it requires N positive responses to decrease the level and M negative responses % to decrease it. The choices shown here tend to spread the values around the 50-50 % response point. nUps = [1 1 2]; nDowns = [2 1 1]; st{k} = Staircase(staircaseType,initialDelta, ... 'StepSizes', stepSizes, 'NUp', nUps(k), 'NDown', nDowns(k), ... 'MaxValue', maxDelta, 'MinValue', minDelta); case 'quest' criterionCorrs = [.4 .5 .6]; st{k} = Staircase(staircaseType,initialDelta, ... 'Beta', 2, 'Delta', 0.01, 'PriorSD',1000, ... 'TargetThreshold', criterionCorrs(k), 'Gamma', 0, ... 'MaxValue', maxDelta, 'MinValue', minDelta); end end % Simulate interleaved staircases for i = 1:numTrialsPerStaircase order = Shuffle(1:nInterleavedStaircases); for k = 1:nInterleavedStaircases comparisonDelta = getCurrentValue(st{order(k)}); response = SimulateProbYes(testStimulus,testStimulus+comparisonDelta,0,noiseSd,1,adaptingBias); st{order(k)} = updateForTrial(st{order(k)},comparisonDelta,response); end end % Analyze staircase data valuesStair = []; responsesStair = []; for k = 1:nInterleavedStaircases pseStair(k) = getThresholdEstimate(st{k}); [valuesSingleStair{k},responsesSingleStair{k}] = getTrials(st{k}); valuesStair = [valuesStair valuesSingleStair{k}]; responsesStair = [responsesStair responsesSingleStair{k}]; end [meanValues,nCorrectStair,nTrialsStair] = GetAggregatedStairTrials(valuesStair,responsesStair,10); % Fit staircase data using Palamedes paramsValues0(1) = 0; paramsValues0(2) = 1/((max(valuesStair) - min(valuesStair))/4); [paramsValuesStair] = PAL_PFML_Fit(... valuesStair',responsesStair',ones(size(responsesStair')), ... paramsValues0,paramsFree,PF,'searchOptions',options, ... 'lapseLimits',lapseLimits); probYesFitStair = PF(paramsValuesStair,comparisonStimuliFit'-testStimulus); psePalStair = PFI(paramsValuesStair,0.5); threshPalStair = PFI(paramsValuesStair,0.75)-PFI(paramsValuesStair,0.5); % Figure stairFig = figure; clf; colors = ['r' 'g' 'b' 'k' 'y' 'c']; subplot(1,2,1); hold on for k = 1:nInterleavedStaircases xvalues = 1:numTrialsPerStaircase; index = find(responsesSingleStair{k} == 0); plot(xvalues,valuesSingleStair{k},[colors(k) '-']); plot(xvalues,valuesSingleStair{k},[colors(k) 'o'],'MarkerFaceColor',colors(k),'MarkerSize',6); if (~isempty(index)) plot(xvalues(index),valuesSingleStair{k}(index),[colors(k) 'o'],'MarkerFaceColor','w','MarkerSize',6); end plot(xvalues,pseStair(k)*ones(1,numTrialsPerStaircase),colors(k)); end xlabel('Trial Number','FontSize',16); ylabel('Level','FontSize',16); title(sprintf('Y/N staircase plot'),'FontSize',16); subplot(1,2,2); hold on plot(meanValues,nCorrectStair./nTrialsStair,'ko','MarkerSize',6,'MarkerFaceColor','k'); plot(comparisonStimuliFit-testStimulus,probYesFitStair,'r','LineWidth',2); plot([psePalStair psePalStair],[0 0.5],'r','LineWidth',2); plot([psePalStair psePalStair+threshPalStair],[0.75 0.75],'g','LineWidth',2); xlabel('Delta Stimulus','FontSize',16); ylabel('Prob Yes','FontSize',16); title(sprintf('Y/N staircase psychometric function'),'FontSize',16); xlim([comparisonStimuli(1)-testStimulus comparisonStimuli(end)-testStimulus]) ylim([0 1]); if (exist('FigureSave','file')) FigureSave('StaircaseYN',gcf','pdf'); else saveas(gcf,'StaircaseYN','pdf'); end fprintf('Staircase simulated data\n'); for k = 1:nInterleavedStaircases fprintf('\tY/N staircase %d threshold estimate: %g\n',k,pseStair(k)); end fprintf('Palamedes''s threshold estimate from staircase data: %g\n',threshPalStair); fprintf('\n'); %% Simulate TAFC psychometric function and fit. Here the Weibull is a more natural functional % form, and we show its use for both toolboxes. % % Unlike Y/N, the most natural x axis for TAFC is the increment of the comparison relative to % the test, so that a 0 comparison corresponds to chance performance. % % As with Y/N simulation above, we don't allow for a lapse rate in this demo. comparisonStimuli = linspace(testStimulus,testStimulus+6*noiseSd,nComparison); comparisonStimuliFit = linspace(testStimulus,testStimulus+6*noiseSd,nComparisonFit); for i = 1:nComparison nCorrect(i) = SimulateTAFC(testStimulus,comparisonStimuli(i),noiseSd,noiseSd,nSimulate,adaptingBias); %#ok<AGROW> end % PSIGNIFIT % Fit simulated data, psignifit. These parameters do a one interval (y/n) fit. Both lambda (lapse rate) and % gamma (value for -Inf input) are locked at 0. criterionCorr = 0.82; fittype = 'w'; pfitdata = [comparisonStimuli'-testStimulus, nCorrect', nSimulate*ones(size(nCorrect'))]; pfitstruct = pfit(pfitdata,'no plot','matrix_format','xrn', ... 'shape', fittype, 'n_intervals', 2, 'runs', 0, 'sens', 0, ... 'compute_stats', 0, 'cuts', [0.5], 'verbose', 0, 'fix_lambda',0,'fix_gamma',0.5); probCorrFitPsig = psigpsi(fittype, pfitstruct.params.est, comparisonStimuliFit'-testStimulus); threshPsig = findthreshold(fittype,pfitstruct.params.est,criterionCorr,'performance'); % PALAMEDES % Fit with Palemedes Toolbox. The parameter constraints match the psignifit parameters above. Again, some % thought is required to initialize reasonably. The threshold parameter is reasonably taken to be in the % range of the comparison stimuli, where here 0 means that the comparison is the same as the test. The % second parameter should be on the order of 1/2, so we just hard code that. As with Y/N, really want to % plot the fit against the data to make sure it is reasonable in practice. PF = @PAL_Weibull; % Alternatives: PAL_Gumbel, PAL_Weibull, PAL_CumulativeNormal, PAL_HyperbolicSecant PFI = @PAL_inverseWeibull; paramsFree = [1 1 0 0]; % 1: free parameter, 0: fixed parameter paramsValues0 = [mean(comparisonStimuli'-testStimulus) 1/2 0.5 0]; options = optimset('fminsearch'); % Type help optimset options.TolFun = 1e-09; % Increase required precision on LL options.Display = 'off'; % Suppress fminsearch messages lapseLimits = [0 1]; % Limit range for lambda [paramsValues] = PAL_PFML_Fit(... comparisonStimuli'-testStimulus,nCorrect',nSimulate*ones(size(nYes')), ... paramsValues0,paramsFree,PF,'searchOptions',options, ... 'lapseLimits',lapseLimits); probCorrFitPal = PF(paramsValues,comparisonStimuliFit'-testStimulus); threshPal = PFI(paramsValues,criterionCorr); % Plot of TAFC simulation. When the red and green overlap (which they do in all my tests), it % means that psignfit and Palamedes agree. figure; clf; hold on plot(comparisonStimuli'-testStimulus,nCorrect/nSimulate,'ko','MarkerSize',6,'MarkerFaceColor','k'); plot(comparisonStimuliFit-testStimulus,probCorrFitPsig,'r','LineWidth',2); plot(comparisonStimuliFit-testStimulus,probCorrFitPal,'g','LineWidth',1); plot([threshPsig threshPsig],[0 criterionCorr],'r','LineWidth',2); plot([threshPal threshPal],[0 criterionCorr],'g','LineWidth',1); xlabel('Delta Stimulus','FontSize',16); ylabel('Prob Correct','FontSize',16); title(sprintf('TAFC psychometric function'),'FontSize',16); xlim([comparisonStimuli(1)-testStimulus comparisonStimuli(end)-testStimulus]) ylim([0 1]); if (exist('FigureSave','file')) FigureSave('PsychoFC',gcf,'pdf'); else saveas(gcf,'PsychFC','pdf'); end % Printout fprintf('TAFC simulated data\n'); fprintf('Psignifit thresh: %g\n',threshPsig); fprintf('Palamedes thresh: %g\n',threshPal); fprintf('\n'); %% Do a staircase for a TAFC experiment. Uses our Staircase class. % The code below runs three interleaved staircases. % For 'quest', three different criterion percent correct values are used. % For 'standard', three different up/down rules are used. % The use of 3 is hard-coded, in the sense that the vector lengths of the % criterion/up-down vectors must match this number. numTrialsPerStaircase = 30; maxDelta = max(comparisonStimuli)-testStimulus; minDelta = 0.01; % Initialize staircases. Initialization is slightly different for 'standard' % and 'quest' versions. All parameters other than 'MaxValue' and 'MinValue' % are required, and this is enforced by the class constructor function. % % The logic for TAFC staircases is similar to Y/N, but we want to set % ups/downs or criterionCorr to aim above 50%, whereas in Y/N we typically % aim at 50%. nInterleavedStaircases = 3; for k = 1:nInterleavedStaircases % Set starting value for the staircase at a random level between % min and max. initialDelta = (maxDelta-minDelta)*rand(1)+minDelta; switch(staircaseType) case 'standard' stepSizes = [2*threshPal threshPal threshPal/4]; nUps = [3 2 3]; nDowns = [1 1 2]; st{k} = Staircase(staircaseType,initialDelta, ... 'StepSizes', stepSizes, 'NUp', nUps(k), 'NDown', nDowns(k), ... 'MaxValue', maxDelta, 'MinValue', minDelta); case 'quest' criterionCorrs = [criterionCorr-0.08 criterionCorr criterionCorr+0.08]; st{k} = Staircase(staircaseType,initialDelta, ... 'Beta', 2, 'Delta', 0.01, 'PriorSD',1000, ... 'TargetThreshold', criterionCorrs(k),'Gamma', 0.5, ... 'MaxValue', maxDelta, 'MinValue', minDelta); end end % Simulate interleaved staircases for i = 1:numTrialsPerStaircase order = Shuffle(1:nInterleavedStaircases); for k = 1:nInterleavedStaircases comparisonDelta = getCurrentValue(st{order(k)}); response = SimulateTAFC(testStimulus,testStimulus+comparisonDelta,noiseSd,noiseSd,1,adaptingBias); st{order(k)} = updateForTrial(st{order(k)},comparisonDelta,response); end end % Analyze staircase data valuesStair = []; responsesStair = []; for k = 1:nInterleavedStaircases threshStair(k) = getThresholdEstimate(st{k}); [valuesSingleStair{k},responsesSingleStair{k}] = getTrials(st{k}); valuesStair = [valuesStair valuesSingleStair{k}]; responsesStair = [responsesStair responsesSingleStair{k}]; end [meanValues,nCorrectStair,nTrialsStair] = GetAggregatedStairTrials(valuesStair,responsesStair,10); % Fit staircase data using Palamedes [paramsValuesStair] = PAL_PFML_Fit(... valuesStair',responsesStair',ones(size(responsesStair')), ... paramsValues0,paramsFree,PF,'searchOptions',options, ... 'lapseLimits',lapseLimits); probCorrFitStair = PF(paramsValuesStair,comparisonStimuliFit'-testStimulus); threshPalStair = PFI(paramsValuesStair,criterionCorr); % Figure stairFig = figure; clf; colors = ['r' 'g' 'b' 'k' 'y' 'c']; subplot(1,2,1); hold on for k = 1:nInterleavedStaircases xvalues = 1:numTrialsPerStaircase; index = find(responsesSingleStair{k} == 0); plot(xvalues,valuesSingleStair{k},[colors(k) '-']); plot(xvalues,valuesSingleStair{k},[colors(k) 'o'],'MarkerFaceColor',colors(k),'MarkerSize',6); if (~isempty(index)) plot(xvalues(index),valuesSingleStair{k}(index),[colors(k) 'o'],'MarkerFaceColor','w','MarkerSize',6); end plot(xvalues,threshStair(k)*ones(1,numTrialsPerStaircase),colors(k)); end xlabel('Trial Number','FontSize',16); ylabel('Level','FontSize',16); title(sprintf('TAFC staircase plot'),'FontSize',16); subplot(1,2,2); hold on plot(meanValues,nCorrectStair./nTrialsStair,'ko','MarkerSize',6,'MarkerFaceColor','k'); plot(comparisonStimuliFit-testStimulus,probCorrFitStair,'r','LineWidth',2); plot([threshPalStair threshPalStair],[0 criterionCorr],'r','LineWidth',2); xlabel('Delta Stimulus','FontSize',16); ylabel('Prob Correct','FontSize',16); title(sprintf('TAFC staircase psychometric function'),'FontSize',16); xlim([comparisonStimuli(1)-testStimulus comparisonStimuli(end)-testStimulus]) ylim([0 1]); if (exist('FigureSave','file')) FigureSave('StaircaseFC',gcf','pdf'); else saveas(gcf','StaircaseFC','pdf'); end fprintf('Staircase simulated data\n'); for k = 1:nInterleavedStaircases fprintf('\tTAFC staircase %d threshold estimate: %g\n',k,threshStair(k)); end fprintf('Palamedes''s threshold estimate from staircase data: %g\n',threshPalStair); end %% Subfunctions for simulating observer function nYes = SimulateProbYes(responseTest,responseComparison,testSd,comparisonSd,nSimulate,adaptingBias) % probYes = SimulateProbYes(responseTest,responseComparison,testSd,comparisonSd,nSimulate,adaptingBias) % % Simulate out the number of times that the comparison is judged as larger on the response variable % than the test. I'm sure there is an analytic solution, but it's a little tricky because we % allow different standard deviations for the test and comparison noise. % % Assume experiment is based on comparison of noisy draws from underlying comparison and test % distributions. You can also think of responseTest as a criterion. Passing testSd = 0 makes % the criterion noise free, and other testSd may be thought of as criterial noise. % % The parameter adaptingBias is expressed in the same units as the internal response, and is subtracted % from the comparison response before the decision. It simulates an adaptive effect. Typically passed % as zero. It could also be regarded as a criterion that is shifted from the standard, if you are % thinking in TSD terms. % % 4/25/09 dhb Wrote it. diffNoise = normrnd(0,comparisonSd,nSimulate,1)-normrnd(0,testSd,nSimulate,1); nYes = length(find(responseComparison-adaptingBias-responseTest+diffNoise > 0)); end function nCorrect = SimulateTAFC(responseTest,responseComparison,testSd,comparisonSd,nSimulate,adaptingBias) % probYes = SimulateProbYes(responseTest,responseComparison,testSd, comparisonSd,nSimulate,adaptingBias) % % Simulate out the number of times that a TAFC task is done correctly, with judgment greater % corresponding to greater noisy response. % % The parameter adaptingBias is expressed in the same units as the internal response, and is subtracted % from the comparison response before the decision. It simulates an adaptive effect. Typically passed % as zero. This can be a bit weird because the decision rule is coded on the assumption that the % comparison is always bigger than the test. % % 4/25/09 dhb Wrote it. nCorrect = 0; for i = 1:nSimulate responseTestNoise = responseTest+normrnd(0,testSd,1,1); responseComparisonNoise = responseComparison+normrnd(0,comparisonSd,1,1)-adaptingBias; if (responseComparison > responseTest & responseComparisonNoise > responseTestNoise) nCorrect = nCorrect+1; elseif (responseComparison <= responseTest & responseComparisonNoise <= responseTestNoise) nCorrect = nCorrect+1; end end end
github
BrainardLab/TeachingCode-master
psychofitTutorialTAFC.m
.m
TeachingCode-master/MatlabTutorials/psychofitTutorial/psychofitTutorialTAFC.m
5,173
utf_8
fa2b815076ca613d136e8e4c261f32ef
function psychofitTutorialTAFC % psychofitTutorialTAFC % % Show basic use of Palamedes toolboxes to simulate and % fit psychophysical data, TAFC, for method of constant stimuli. % % You need the Palamedes toolboxe (1.8.2) for this to work. % 04/30/09 dhb Broke out from 2014 version and updated. %% Clear clear; close all; %% Specify precision as noise of a Gaussian variable % % Simulation parameters noiseSd = 0.06; testStimulus = 100; nComparisonFit = 100; nComparison = 10; nSimulate = 40; nComparisonSds = 4; thresholdCriterionCorrect = 0.75; %% Simulate TAFC psychometric function and fit. Here the Weibull is a more natural functional % form, and we show its use for both toolboxes. % % The most natural x axis for TAFC is the increment of the comparison relative to % the test, so that a 0 comparison corresponds to chance performance. comparisonStimuli = linspace(testStimulus,testStimulus+nComparisonSds*noiseSd,nComparison); comparisonStimuliFit = linspace(testStimulus,testStimulus+nComparisonSds*noiseSd,nComparisonFit); for i = 1:nComparison nCorrect(i) = SimulateTAFC(testStimulus,comparisonStimuli(i),noiseSd,noiseSd,nSimulate); %#ok<AGROW> end % Palamedes fit % % Fit with Palemedes Toolbox. The parameter constraints match the psignifit parameters above. Again, some % thought is required to initialize reasonably. The threshold parameter is reasonably taken to be in the % range of the comparison stimuli, where here 0 means that the comparison is the same as the test. The % second parameter should be on the order of 1/2, so we just hard code that. As with Y/N, really want to % plot the fit against the data to make sure it is reasonable in practice. % Define what psychometric functional form to fit. % % Alternatives: PAL_Gumbel, PAL_Weibull, PAL_CumulativeNormal, PAL_HyperbolicSecant PF = @PAL_Weibull; % The first two parameters of the Weibull define its shape. % % The third is the guess rate, which determines the value the function % takes on at x = 0. For TAFC, this should be locked at 0.5. % % The fourth parameter is the lapse rate - the asymptotic performance at % high values of x. For a perfect subject, this would be 0, but sometimes % subjects have a "lapse" and get the answer wrong even when the stimulus % is easy to see. We can search over this, but shouldn't allow it to take % on unreasonable values. 0.05 as an upper limit isn't crazy. % % paramsFree is a boolean vector that determins what parameters get % searched over. 1: free parameter, 0: fixed parameter paramsFree = [1 1 0 1]; % Initial guess. Setting the first parameter to the middle of the stimulus % range and the second to 1 puts things into a reasonable ballpark here. paramsValues0 = [mean(comparisonStimuli'-testStimulus) 1 0.5 0.01]; % This puts limits on the range of the lapse rate lapseLimits = [0 0.05]; % Set up standard options for Palamedes search options = PAL_minimize('options'); % Do the search to get the parameters [paramsValues] = PAL_PFML_Fit(... comparisonStimuli'-testStimulus,nCorrect',nSimulate*ones(size(nCorrect')), ... paramsValues0,paramsFree,PF,'searchOptions',options,'lapseLimits',lapseLimits); %% Make a smooth curve with the parameters probCorrFitPal = PF(paramsValues,comparisonStimuliFit'-testStimulus); %% Invert psychometric function to find threshold threshPal = PF(paramsValues,thresholdCriterionCorrect,'inverse'); %% Plot of TAFC simulation % % The plot shows the simulated data, the fit, and the threshold from the % fit. figure; clf; hold on plot(comparisonStimuli'-testStimulus,nCorrect/nSimulate,'ko','MarkerSize',6,'MarkerFaceColor','k'); plot(comparisonStimuliFit-testStimulus,probCorrFitPal,'g','LineWidth',1); plot([threshPal threshPal],[0 thresholdCriterionCorrect],'g','LineWidth',1); xlabel('Delta Stimulus','FontSize',16); ylabel('Prob Correct','FontSize',16); title(sprintf('TAFC psychometric function'),'FontSize',16); xlim([comparisonStimuli(1)-testStimulus comparisonStimuli(end)-testStimulus]) ylim([0 1.01]); if (exist('FigureSave','file')) FigureSave('PsychoTAFC',gcf,'pdf'); else saveas(gcf,'PsychTAFC','pdf'); end % Printout fprintf('TAFC simulated data\n'); fprintf('Palamedes thresh: %g\n',threshPal); fprintf('Parameters: %0.2g %0.2g %0.2g %0.2g\n',paramsValues(1),paramsValues(2),paramsValues(3),paramsValues(4)); fprintf('\n'); end function nCorrect = SimulateTAFC(responseTest,responseComparison,testSd,comparisonSd,nSimulate) % nCorrect = SimulateTAFC(responseTest,responseComparison,testSd,comparisonSd,nSimulate) % % Simulate out the number of times that a TAFC task is done correctly, with judgment greater % corresponding to greater noisy response. % % 4/25/09 dhb Wrote it. nCorrect = 0; for i = 1:nSimulate responseTestNoise = responseTest+normrnd(0,testSd,1,1); responseComparisonNoise = responseComparison+normrnd(0,comparisonSd,1,1); if (responseComparison > responseTest & responseComparisonNoise > responseTestNoise) nCorrect = nCorrect+1; elseif (responseComparison <= responseTest & responseComparisonNoise <= responseTestNoise) nCorrect = nCorrect+1; end end end
github
BrainardLab/TeachingCode-master
poissonSetup.m
.m
TeachingCode-master/MatlabTutorials/filteringAndNoise (Phil Nelson)/poissonSetup.m
716
utf_8
26ec6970be1e3b049bf000cac6dbd324
%% pcn 9/07 poissonSetup.m % this function sets up the vector distrBins, which can then be used % to generate random integers in a Poisson distribution: % a. this function poissonSetup(Q) prepares the vector distrBins % b. to use it in your main routine, initialize with: % dist=poissonSetup(2) % (The argument selects the desired mean.) Then say: % [n,k]=histc(rand,dist) % which returns % k = a sample from the distribution, plus 1 % (and n = array with zeros except for bin #k) % %% function distrBins=poissonSetup(r); topBin=max([10 round(10*r)]); tmpBins(1)=0; running=exp(-r); tmpBins(2)=running; for m=1:(topBin-2); running=running*r/m; tmpBins(m+2)=running; end; distrBins=cumsum(tmpBins); return;
github
BrainardLab/TeachingCode-master
MGL_MOGL_VertexArray.m
.m
TeachingCode-master/MGLExamples/MGL_MOGL_VertexArray.m
8,758
utf_8
626bad60ec16d7eb3318b734aeb9e5e2
function MGL_MOGL_VertexArray % MGL_MOGL_VertexArray % % Description: % Shows how to create a simple shape with vertex arrays. % This setups up some OpenGL constants in the Matlab environment. % Essentially, anything in C OpenGL that starts with GL_ becomes GL.., e.g. % GL_RECT becomes GL.RECT. All GL_ are stored globally in the GL struct. global GL; InitializeMatlabOpenGL; % Setup some parameters we'll use. screenDims = [50 30]; % Width, height in centimeters of the display. backgroundRGB = [0 0 0]; % RGB of the background. All values are in the [0,1] range. screenDist = 50; % The distance from the observer to the display. cubeSize = 10; % Size of one side of the cube. % This the half the distance between the observers 2 pupils. This value is % key in setting up the stereo perspective for the left and right eyes. % For a single screen setup, we'll use a value of 0 since we're not % actually in stereo. ioOffset = 0; % Define the vertices of our cube. v = zeros(8, 3); v(1,:) = [-1 -1 1]; v(2,:) = [1 -1 1]; v(3,:) = [1 1 1]; v(4,:) = [-1 1 1]; v(5,:) = [-1 -1 -1]; v(6,:) = [1 -1 -1]; v(7,:) = [1 1 -1]; v(8,:) = [-1 1 -1]; % Now we define the vertex information for the vertex arrays we'll be % using. Essentially, we're defining the vertices for the OpenGL % primitives that will be used. cubeVerts = [v(1,:), v(2,:), v(3,:), v(4,:), ... % Front v(2,:), v(6,:), v(7,:), v(3,:), ... % Right v(6,:), v(5,:), v(8,:), v(7,:), ... % Back v(5,:), v(1,:), v(4,:), v(8,:), ... % Left v(4,:), v(3,:), v(7,:), v(8,:), ... % Top v(2,:), v(1,:), v(5,:), v(6,:)]; % Bottom % Define the surface normals for the each vertex for every primitive. It % is possible to use shared vertices to reduce the number of specified % values, but it makes it trickier to define vertex normals. These need to % match the vertices defined above. n.front = [0 0 1]; n.back = [0 0 -1]; n.right = [1 0 0]; n.left = [-1 0 0]; n.up = [0 1 0]; n.down = [0 -1 0]; cubeNormals = [repmat(n.front, 1, 4), repmat(n.right, 1, 4), ... repmat(n.back, 1, 4), repmat(n.left, 1, 4), ... repmat(n.up, 1, 4), repmat(n.down, 1, 4)]; % Define the vertex colors. cubeColors = repmat([1 0 0], 1, 24); % Now we define the indices of the vertices that we'll use to define the % cube. These are indices into the 'cubeVerts' array specified above. % Note that OpenGL uses 0 based indices unlike Matlab. cubeIndices = [0 1 2 3, ... % Front 4 5 6 7, ... % Right 8 9 10 11, ... % Back 12 13 14 15, ... % Left 16 17 18 19, ... % Top 20 21 22 23]; % Bottom % Convert the indices to unsigned bytes for storage optimization. cubeIndices = uint8(cubeIndices); try mglOpen; % We need to calculate a frustum to define our perspective matrix. % Using this data in combination with the glFrustum command, we can now % have a 3D rendering space instead of orthographic (2D). frustum = calculateFrustum(screenDist, screenDims, ioOffset); % Setup what our background color will be. We only need to do this % once unless we want to change our background color in the middle of % the program. glClearColor(backgroundRGB(1), backgroundRGB(2), backgroundRGB(3), ... 0); % This 4th value is the alpha value. We rarely care about it % for the background color. % Make sure we're testing for depth. Important if more than 1 thing is % on the screen and you don't want to deal with render order effects. glEnable(GL.DEPTH_TEST); % These help things rendered look nicer. glEnable(GL.BLEND); glEnable(GL.POLYGON_SMOOTH); glEnable(GL.LINE_SMOOTH); glEnable(GL.POINT_SMOOTH); % Turn on lighting. glLightfv(GL.LIGHT0, GL.AMBIENT, [0.5 0.5 0.5 1]); glLightfv(GL.LIGHT0, GL.DIFFUSE, [0.6 0.6 0.6 1]); glLightfv(GL.LIGHT0, GL.SPECULAR, [0.5 0.5 0.5 1]); glLightfv(GL.LIGHT0, GL.POSITION, [0 0 0 1]); glEnable(GL.LIGHTING); glEnable(GL.COLOR_MATERIAL); glEnable(GL.LIGHT0); % Turn on character listening. This function causes keyboard % characters to be gobbled up so they don't appear in any Matlab % window. mglEatKeys(1:50); % Clear the keyboard buffer. mglGetKeyEvent; keepDrawing = true; while keepDrawing % Look for a keyboard press. key = mglGetKeyEvent; % If the nothing was pressed keeping drawing. if ~isempty(key) % We can react differently to each key press. switch key.charCode % All other keys go here. otherwise fprintf('Exiting...\n'); % Quit our drawing loop. keepDrawing = false; end end % Setup the projection matrix. The projection matrix defines how % the OpenGL coordinate system maps onto the physical screen. glMatrixMode(GL.PROJECTION); % This gives us a clean slate to work with. glLoadIdentity; % Map our 3D rendering space to the display given a specific % distance from the screen to the subject and an interocular % offset. This is calculated at the beginning of the program. glFrustum(frustum.left, frustum.right, frustum.bottom, frustum.top, frustum.near, frustum.far); % Now we switch to the modelview mode, which is where we draw % stuff. glMatrixMode(GL.MODELVIEW); glLoadIdentity; % In 3D mode, we need to specify where the camera (the subject) is % in relation to the display. Essentially, for proper stereo, the % camera will be placed at the screen distance facing straight % ahead not at (0,0). gluLookAt(ioOffset, 0, screenDist, ... % Eye position ioOffset, 0, 0, ... % Fixation center 0, 1, 0); % Vector defining which way is up. % Clear our rendering space. If you don't do this rendered in the % buffer before will still be there. The scene is filled with the % background color specified above. glClear(mor(GL.COLOR_BUFFER_BIT, GL.DEPTH_BUFFER_BIT, GL.STENCIL_BUFFER_BIT, GL.ACCUM_BUFFER_BIT)); glRotated(20, 1, 1, 1); % Set the size of the cube. glScaled(cubeSize/2, cubeSize/2, cubeSize/2); % Render the cube. glEnableClientState(GL.VERTEX_ARRAY); glEnableClientState(GL.NORMAL_ARRAY); glEnableClientState(GL.COLOR_ARRAY); glNormalPointer(GL.DOUBLE, 0, cubeNormals); glColorPointer(3, GL.DOUBLE, 0, cubeColors); glVertexPointer(3, GL.DOUBLE, 0, cubeVerts); glColorMaterial(GL.FRONT_AND_BACK, GL.AMBIENT_AND_DIFFUSE); glDrawElements(GL.QUADS, length(cubeIndices), GL.UNSIGNED_BYTE, cubeIndices); glDisableClientState(GL.VERTEX_ARRAY); glDisableClientState(GL.NORMAL_ARRAY); glDisableClientState(GL.COLOR_ARRAY); % This command sticks everything we just did onto the screen. It % syncs to the refresh rate of the display. mglFlush; end % Close the MGL window. mglClose; % Disable character listening. mglEatKeys([]); catch e % Close the MGL window. mglClose; % Disable character listening. mglEatKeys([]); % Send the error to the Matlab command window. rethrow(e); end function frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % % Description: % Takes some basic screen information and calculates the frustum parameters % required to setup a 3D projection matrix. % % Input: % screenDistance (scalar) - Distance from the screen to the observer. % screenDims (1x2) - Dimensions of the screen. (width, height) % horizontal offset (scalar) - Horizontal shift of the observer from the % center of the display. Should be 0 for regular displays and half the % interocular distance for stereo setups. % % Output: % frust (struct) - Struct containing all calculated frustum parameters. % Contains the following fields. % 1. left - Left edge of the near clipping plane. % 2. right - Right edge of the near clipping plane. % 3. top - Top edge of the near clipping plane. % 4. bottom - Bottom edge of the near clipping plane. % 5. near - Distance from the observer to the near clipping plane. % 6. far - Distance from the observer to the far clipping plane. if nargin ~= 3 error('Usage: frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset)'); end % I chose these constants as reasonable values for the distances from the % camera for the type of experiments the Brainard lab does. frustum.near = 1; frustum.far = 100; % Use similar triangles to figure out the boundaries of the near clipping % plane based on the information about the screen size and its distance % from the camera. frustum.right = (screenDims(1)/2 - horizontalOffset) * frustum.near / screenDistance; frustum.left = -(screenDims(1)/2 + horizontalOffset) * frustum.near / screenDistance; frustum.top = screenDims(2)/2 * frustum.near / screenDistance; frustum.bottom = -frustum.top;
github
BrainardLab/TeachingCode-master
MGL_MOGL_NURBS.m
.m
TeachingCode-master/MGLExamples/MGL_MOGL_NURBS.m
7,889
utf_8
6070c511717e4aeb6321fc2724c40d49
function MGL_MOGL_NURBS % MGL_MOGL_NURBS % % Description: % Opens a full screen MGL window with a black background, and renders a % NURBS surface. % % Keyboard Control: % 'q' - Exits the program. % 't', 'r' - Rotate the surface about the x-axis. % This setups up some OpenGL constants in the Matlab environment. % Essentially, anything in C OpenGL that starts with GL_ becomes GL.., e.g. % GL_RECT becomes GL.RECT. All GL. are stored globally in the GL struct. global GL; InitializeMatlabOpenGL; % Setup some parameters we'll use. screenDims = [50 30]; % Width, height in centimeters of the display. screenDist = 50; % The distance from the observer to the display. backgroundRGB = [0 0 0]; % RGB of the background. All values are in the [0,1] range. rotationAmount = -80; % Degrees of rotation about the x-axis. % This the half the distance between the observers 2 pupils. This value is % key in setting up the stereo perspective for the left and right eyes. % For a single screen setup, we'll use a value of 0 since we're not % actually in stereo. ioOffset = 0; % Define the NURBS surface. ctlPoints = zeros(4,4,3); cPoints = zeros(1, 4*4*3); cIndex = 1; for u = 1:4 for v = 1:4 ctlPoints(u,v,1) = 2.0*(u - 1.5); ctlPoints(u,v,2) = 2.0*(v - 1.5); if ( (u == 2 || u == 3) && (v == 2 || v == 3)) ctlPoints(u,v,3) = 3.0; else ctlPoints(u,v,3) = -3.0; end % Re-pack the control points data into an array that the glNurbs % functions below understand. cPoints(cIndex:(cIndex+2)) = ctlPoints(u,v,:); cIndex = cIndex + 3; end end knots = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]; try mglOpen; % We need to calculate a frustum to define our perspective matrix. % Using this data in combination with the glFrustum command, we can now % have a 3D rendering space instead of orthographic (2D). frustum = calculateFrustum(screenDist, screenDims, ioOffset); % Setup what our background color will be. We only need to do this % once unless we want to change our background color in the middle of % the program. glClearColor(backgroundRGB(1), backgroundRGB(2), backgroundRGB(3), ... 0); % This 4th value is the alpha value. We rarely care about it % for the background color. % Make sure we're testing for depth. Important if more than 1 thing is % on the screen and you don't want to deal with render order effects. glEnable(GL.DEPTH_TEST); % These help things rendered look nicer. glEnable(GL.BLEND); glEnable(GL.POLYGON_SMOOTH); glEnable(GL.LINE_SMOOTH); glEnable(GL.POINT_SMOOTH); % Setup some lighting and material properties for the surface. glEnable(GL.LIGHTING); glEnable(GL.LIGHT0); matDiffuse = [0.7, 0.7, 0.7, 1.0]; matSpecular = [1.0, 1.0, 1.0, 1.0]; matShininess = 100; glMaterialfv(GL.FRONT, GL.DIFFUSE, matDiffuse); glMaterialfv(GL.FRONT, GL.SPECULAR, matSpecular); glMaterialfv(GL.FRONT, GL.SHININESS, matShininess); % Have OpenGL do polygon normalization for us to make the surface look % smoother. glEnable(GL.AUTO_NORMAL); glEnable(GL.NORMALIZE); % Create the NURBS renderer. theNurb = gluNewNurbsRenderer; % Turn on character listening. This function causes keyboard % characters to be gobbled up so they don't appear in any Matlab % window. mglEatKeys(1:50); keepDrawing = true; while keepDrawing % Look for a keyboard press. key = mglGetKeyEvent; % If the nothing was pressed keeping drawing. if ~isempty(key) % We can react differently to each key press. switch key.charCode case 'r' rotationAmount = rotationAmount + 10; case 't' rotationAmount = rotationAmount - 10; % All other keys go here. case 'q' fprintf('Exiting...\n'); % Quit our drawing loop. keepDrawing = false; end end % Setup the projection matrix. The projection matrix defines how % the OpenGL coordinate system maps onto the physical screen. glMatrixMode(GL.PROJECTION); % This gives us a clean slate to work with. glLoadIdentity; % Map our 3D rendering space to the display given a specific % distance from the screen to the subject and an interocular % offset. This is calculated at the beginning of the program. glFrustum(frustum.left, frustum.right, frustum.bottom, frustum.top, frustum.near, frustum.far); % Now we switch to the modelview mode, which is where we draw % stuff. glMatrixMode(GL.MODELVIEW); glLoadIdentity; % In 3D mode, we need to specify where the camera (the subject) is % in relation to the display. Essentially, for proper stereo, the % camera will be placed at the screen distance facing straight % ahead not at (0,0). gluLookAt(ioOffset, 0, screenDist, ... % Eye position ioOffset, 0, 0, ... % Fixation center 0, 1, 0); % Vector defining which way is up. % Clear our rendering space. If you don't do this rendered in the % buffer before will still be there. The scene is filled with the % background color specified above. glClear(mor(GL.COLOR_BUFFER_BIT, GL.DEPTH_BUFFER_BIT, GL.STENCIL_BUFFER_BIT, GL.ACCUM_BUFFER_BIT)); % Rotate the surface. glRotated(rotationAmount, 1, 0, 0); % Move the surface to the center of the screen. glTranslated(-2, -2, 0); % Render the NURBS surface. gluBeginSurface(theNurb); gluNurbsSurface(theNurb, ... 8, knots, 8, knots, ... 4 * 3, 3, cPoints, ... 4, 4, GL.MAP2_VERTEX_3); gluEndSurface(theNurb); % Show the control points. glPointSize(5.0); glDisable(GL.LIGHTING); glColor3f(1.0, 1.0, 0.0); glBegin(GL.POINTS); for i = 1:4 for j = 1:4 glVertex3fv(ctlPoints(i,j,:)); end end glEnd; glEnable(GL.LIGHTING); % This command sticks everything we just did onto the screen. It % syncs to the refresh rate of the display. mglFlush; end % Close the MGL window. mglClose; % Disable character listening. mglEatKeys([]); catch e % Close the MGL window. mglClose; % Disable character listening. mglEatKeys([]); % Send the error to the Matlab command window. rethrow(e); end function frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % % Description: % Takes some basic screen information and calculates the frustum parameters % required to setup a 3D projection matrix. % % Input: % screenDistance (scalar) - Distance from the screen to the observer. % screenDims (1x2) - Dimensions of the screen. (width, height) % horizontal offset (scalar) - Horizontal shift of the observer from the % center of the display. Should be 0 for regular displays and half the % interocular distance for stereo setups. % % Output: % frust (struct) - Struct containing all calculated frustum parameters. % Contains the following fields. % 1. left - Left edge of the near clipping plane. % 2. right - Right edge of the near clipping plane. % 3. top - Top edge of the near clipping plane. % 4. bottom - Bottom edge of the near clipping plane. % 5. near - Distance from the observer to the near clipping plane. % 6. far - Distance from the observer to the far clipping plane. if nargin ~= 3 error('Usage: frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset)'); end % I chose these constants as reasonable values for the distances from the % camera for the type of experiments the Brainard lab does. frustum.near = 1; frustum.far = 100; % Use similar triangles to figure out the boundaries of the near clipping % plane based on the information about the screen size and its distance % from the camera. frustum.right = (screenDims(1)/2 - horizontalOffset) * frustum.near / screenDistance; frustum.left = -(screenDims(1)/2 + horizontalOffset) * frustum.near / screenDistance; frustum.top = screenDims(2)/2 * frustum.near / screenDistance; frustum.bottom = -frustum.top;
github
BrainardLab/TeachingCode-master
MGL_MOGL_StereoWarping.m
.m
TeachingCode-master/MGLExamples/MGL_MOGL_StereoWarping.m
9,614
utf_8
294340811667d6f6047cc2f76b701f14
function MGL_MOGL_StereoWarping % This setups up some OpenGL constants in the Matlab environment. % Essentially, anything in C OpenGL that starts with GL_ becomes GL.., e.g. % GL_RECT becomes GL.RECT. All GL_ are stored globally in the GL struct. global GL; InitializeMatlabOpenGL; % Setup some parameters we'll use. screenDist = 76.4; % The distance from the observer to the display. backgroundRGB = [0 0 0]; % RGB of the background. All values are in the [0,1] range. rectDims = [2.54 2.54]*2; % Rectangle dimensions in centimeters. rectRGB = [1 0 0]; % Color of the rectangle in RGB. rectPos = [0 0 0]; % (x,y,z) position of the rectangle. rectInc = 1; % How much we'll move the rectangle for a given step. % The 2 screens we'll use have different IDs associated with them. We'll % set up some variables that make it easy to reference them. These IDs are % determined by the operating system, these are not arbitrary. Under screenID.left = 3; screenID.right = 2; % This the half the distance (cm) between the observers 2 pupils. This value is % key in setting up the stereo perspective for the left and right eyes. ioOffset.left = -3; ioOffset.right = 3; % Turn on character listening. This function causes keyboard % characters to be gobbled up so they don't appear in any Matlab % window. mglEatKeys(1:50); % Clear the keyboard buffer. mglGetKeyEvent; try % Open both displays. We setup some of the OpenGL parameters for both % displays because OpenGL commands are only effective for the % currently active display as specified by mglSwitchDisplay. for whichScreen = {'left', 'right'} % Pull out the string that's contained in the cell. i = whichScreen{1}; mglSwitchDisplay(screenID.(i)); mglOpen(screenID.(i)); % Setup what our background color will be. We only need to do this % once unless we want to change our background color in the middle of % the program. glClearColor(backgroundRGB(1), backgroundRGB(2), backgroundRGB(3), ... 0); % This 4th value is the alpha value. We rarely care about it % for the background color. % Make sure we're testing for depth. Important if more than 1 thing is % on the screen and you don't want to deal with render order effects. glEnable(GL.DEPTH_TEST); % These help things rendered look nicer. glEnable(GL.BLEND); glEnable(GL.POLYGON_SMOOTH); glEnable(GL.LINE_SMOOTH); glEnable(GL.POINT_SMOOTH); % Load in the calibration file for the display. We use this to % extract information needed for the framebuffer objet which % handles the warping, and some of the screen info. calFileName = sprintf('StereoWarp-NoRadiance-%s', i); cal = LoadCalFile(calFileName); % Extract the screen dimensions. screenDims.(i) = cal.warpParams.screenDims; % Create the framebuffer object. fbWidth = cal.warpParams.fbObject.width; fbHeight = cal.warpParams.fbObject.height; fbo.(i) = mglCreateFrameBufferObject(fbWidth, fbHeight); % Create the OpenGL display list we'll use to warp the vertices of % the framebuffer object onto the screen. warpList.(i) = mglCreateWarpList(cal.warpParams.actualGrid, [fbWidth fbHeight]); % Get the scene dimensions of the framebuffer object. fbSceneDims.(i) = cal.warpParams.fbSceneDims; % We need to calculate a frustum to define our perspective matrix. % Using this data in combination with the glFrustum command, we can now % have a 3D rendering space instead of orthographic (2D). The left and % right screen will have different frustums because the eye offset is % in different horizontal directions. frustum.(i) = calculateFrustum(screenDist, fbSceneDims.(i), ioOffset.(i)); end keepDrawing = true; while keepDrawing % Look for a keyboard press. key = mglGetKeyEvent; % If the nothing was pressed keeping drawing. if ~isempty(key) % We can react differently to each key press. switch key.charCode case 'r' rectRGB = rand(1,3); % Move the rectangle closer to the subject. case 'j' rectPos(3) = rectPos(3) + rectInc; % Move the rectangle further from the subject. case 'k' rectPos(3) = rectPos(3) - rectInc; % Move the rectangle left. case 'a' rectPos(1) = rectPos(1) - rectInc; % Move the rectangle right. case 'd' rectPos(1) = rectPos(1) + rectInc; % Move the rectangle up. case 'w' rectPos(2) = rectPos(2) + rectInc; % Move the rectangle down. case 's' rectPos(2) = rectPos(2) - rectInc; % All other keys go here. otherwise fprintf('Exiting...\n'); % Quit our drawing loop. keepDrawing = false; end end % We need to do the rendering for both displays. for whichScreen = {'left', 'right'} i = whichScreen{1}; % Direct all OpenGL commands to the appropriate screen. mglSwitchDisplay(screenID.(i)); % Setup the framebuffer object so that we can render into it. mglBindFrameBufferObject(fbo.(i)); % Setup the projection matrix. The projection matrix defines how % the OpenGL coordinate system maps onto the physical screen. glMatrixMode(GL.PROJECTION); % This gives us a clean slate to work with. glLoadIdentity; % Map our 3D rendering space to the display given a specific % distance from the screen to the subject and an interocular % offset. This is calculated at the beginning of the program. glFrustum(frustum.(i).left, frustum.(i).right, frustum.(i).bottom, ... frustum.(i).top, frustum.(i).near, frustum.(i).far); % Now we switch to the modelview mode, which is where we draw % stuff. glMatrixMode(GL.MODELVIEW); glLoadIdentity; % In 3D mode, we need to specify where the camera (the subject) is % in relation to the display. Essentially, for proper stereo, the % camera will be placed at the screen distance facing straight % ahead not at (0,0). gluLookAt(ioOffset.(i), 0, screenDist, ... % Eye position ioOffset.(i), 0, 0, ... % Fixation center 0, 1, 0); % Vector defining which way is up. % Clear our rendering space. If you don't do this rendered in the % buffer before will still be there. The scene is filled with the % background color specified above. glClear(mor(GL.COLOR_BUFFER_BIT, GL.DEPTH_BUFFER_BIT, GL.STENCIL_BUFFER_BIT, GL.ACCUM_BUFFER_BIT)); % Set the rectangle's color. glColor3dv(rectRGB); % This will center the rectangle on the screen. We call this prior % to specifying rectangle because all vertices are multiplied % against the current transformation matrix. In other words, the % order of operations happens in the opposite order they're written % in the code. glTranslated(-rectDims(1)/2 + rectPos(1), -rectDims(2)/2 + rectPos(2), rectPos(3)); % Draw the rectangle. glBegin(GL.QUADS); glVertex2d(0, 0); % Lower left corner glVertex2d(rectDims(1), 0); % Lower right corner glVertex2d(rectDims(1), rectDims(2)); % Upper right corner glVertex2d(0, rectDims(2)); % Upper left corner. glEnd; % Stop rendering to the framebuffer object. mglUnbindFrameBufferObject; % Draw the framebuffer object to the screen. mglRenderWarpedFrameBufferObject(fbo.(i).texture, warpList.(i), screenDims.(i)); % This command sticks everything we just did onto the screen. It % syncs to the refresh rate of the display. mglFlush; end end % Passing -1 to mglSwitchDisplay is a special option which closes any % MGL windows open on the screen. mglSwitchDisplay(-1); catch e % Close any open MGL windows. mglSwitchDisplay(-1); % Disable character listening. mglEatKeys([]); % Send the error to the Matlab command window. rethrow(e); end function frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % % Description: % Takes some basic screen information and calculates the frustum parameters % required to setup a 3D projection matrix. % % Input: % screenDistance (scalar) - Distance from the screen to the observer. % screenDims (1x2) - Dimensions of the screen. (width, height) % horizontal offset (scalar) - Horizontal shift of the observer from the % center of the display. Should be 0 for regular displays and half the % interocular distance for stereo setups. % % Output: % frust (struct) - Struct containing all calculated frustum parameters. % Contains the following fields. % 1. left - Left edge of the near clipping plane. % 2. right - Right edge of the near clipping plane. % 3. top - Top edge of the near clipping plane. % 4. bottom - Bottom edge of the near clipping plane. % 5. near - Distance from the observer to the near clipping plane. % 6. far - Distance from the observer to the far clipping plane. if nargin ~= 3 error('Usage: frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset)'); end % I chose these constants as reasonable values for the distances from the % camera for the type of experiments the Brainard lab does. frustum.near = 1; frustum.far = 100; % Use similar triangles to figure out the boundaries of the near clipping % plane based on the information about the screen size and its distance % from the camera. frustum.right = (screenDims(1)/2 - horizontalOffset) * frustum.near / screenDistance; frustum.left = -(screenDims(1)/2 + horizontalOffset) * frustum.near / screenDistance; frustum.top = screenDims(2)/2 * frustum.near / screenDistance; frustum.bottom = -frustum.top;
github
BrainardLab/TeachingCode-master
MGL_MOGL_Surface.m
.m
TeachingCode-master/MGLExamples/MGL_MOGL_Surface.m
9,259
utf_8
6d2177251935845d4826380586c28c74
function MGL_MOGL_Surface % MGL_MOGL_Surface % % Description: % Shows how to display an arbitrary surface/mesh. % This setups up some OpenGL constants in the Matlab environment. % Essentially, anything in C OpenGL that starts with GL_ becomes GL.., e.g. % GL_RECT becomes GL.RECT. All GL_ are stored globally in the GL struct. global GL; InitializeMatlabOpenGL; % Setup some parameters we'll use. screenDims = [50 30]; % Width, height in centimeters of the display. backgroundRGB = [0 0 0]; % RGB of the background. All values are in the [0,1] range. screenDist = 50; % The distance from the observer to the display. rotationAmount = -80; % Amount of rotation to apply to the surface. % This the half the distance between the observers 2 pupils. This value is % key in setting up the stereo perspective for the left and right eyes. % For a single screen setup, we'll use a value of 0 since we're not % actually in stereo. ioOffset = 0; % Create the (x,y,z) coordinates of a mesh. [meshData.x, meshData.y] = meshgrid(-8:0.1:8); r = sqrt(meshData.x .^ 2 + meshData.y .^ 2) + eps; meshData.z = 5*sin(r)./r; % Now create the surface normals. [meshData.nx meshData.ny meshData.nz] = surfnorm(meshData.x, meshData.y, meshData.z); try mglOpen; % We need to calculate a frustum to define our perspective matrix. % Using this data in combination with the glFrustum command, we can now % have a 3D rendering space instead of orthographic (2D). frustum = calculateFrustum(screenDist, screenDims, ioOffset); % Setup what our background color will be. We only need to do this % once unless we want to change our background color in the middle of % the program. glClearColor(backgroundRGB(1), backgroundRGB(2), backgroundRGB(3), ... 0); % This 4th value is the alpha value. We rarely care about it % for the background color. % Make sure we're testing for depth. Important if more than 1 thing is % on the screen and you don't want to deal with render order effects. glEnable(GL.DEPTH_TEST); % These help things rendered look nicer. glEnable(GL.BLEND); glEnable(GL.POLYGON_SMOOTH); glEnable(GL.LINE_SMOOTH); glEnable(GL.POINT_SMOOTH); glShadeModel(GL.SMOOTH); % Turn on lighting. glLightfv(GL.LIGHT0, GL.AMBIENT, [0.5 0.5 0.5 1]); glLightfv(GL.LIGHT0, GL.DIFFUSE, [0.6 0.6 0.6 1]); glLightfv(GL.LIGHT0, GL.SPECULAR, [0.5 0.5 0.5 1]); glLightfv(GL.LIGHT0, GL.POSITION, [20 10 0 0]); glEnable(GL.LIGHTING); glEnable(GL.COLOR_MATERIAL); glEnable(GL.LIGHT0); % Create our OpenGL display list. A display list is basically a group % of OpenGL commands that can be pre-computed and displayed later. % There is a reduction in overhead so the display lists improve % performance for complex renderings. displayList = createDisplayList(meshData); % Turn on character listening. This function causes keyboard % characters to be gobbled up so they don't appear in any Matlab % window. mglEatKeys(1:50); % Clear the keyboard buffer. mglGetKeyEvent; keepDrawing = true; while keepDrawing % Look for a keyboard press. key = mglGetKeyEvent; % If the nothing was pressed keeping drawing. if ~isempty(key) % We can react differently to each key press. switch key.charCode case 'r' rotationAmount = rotationAmount + 20; % All other keys go here. otherwise fprintf('Exiting...\n'); % Quit our drawing loop. keepDrawing = false; end end % Setup the projection matrix. The projection matrix defines how % the OpenGL coordinate system maps onto the physical screen. glMatrixMode(GL.PROJECTION); % This gives us a clean slate to work with. glLoadIdentity; % Map our 3D rendering space to the display given a specific % distance from the screen to the subject and an interocular % offset. This is calculated at the beginning of the program. glFrustum(frustum.left, frustum.right, frustum.bottom, frustum.top, frustum.near, frustum.far); % Now we switch to the modelview mode, which is where we draw % stuff. glMatrixMode(GL.MODELVIEW); glLoadIdentity; % In 3D mode, we need to specify where the camera (the subject) is % in relation to the display. Essentially, for proper stereo, the % camera will be placed at the screen distance facing straight % ahead not at (0,0). gluLookAt(ioOffset, 0, screenDist, ... % Eye position ioOffset, 0, 0, ... % Fixation center 0, 1, 0); % Vector defining which way is up. % Clear our rendering space. If you don't do this rendered in the % buffer before will still be there. The scene is filled with the % background color specified above. glClear(mor(GL.COLOR_BUFFER_BIT, GL.DEPTH_BUFFER_BIT, GL.STENCIL_BUFFER_BIT, GL.ACCUM_BUFFER_BIT)); glColorMaterial(GL.FRONT_AND_BACK, GL.AMBIENT_AND_DIFFUSE); % This rotates the mesh so we can see it better. glRotated(rotationAmount, 1, 1, 1); % Set our specular lighting component manually. glMaterialfv(GL.FRONT, GL.SPECULAR, [0.1 0 0 1]) % Use glColor to specify the ambient and diffuse material % properties of the surface. glColor3dv([1 0 0]); % Call the display list to render the mesh. We wrap the call to % the list with push and pop commands to save OpenGL state % information that might get modified by the display list. glPushMatrix; glPushAttrib(GL.ALL_ATTRIB_BITS); glCallList(displayList); glPopMatrix; glPopAttrib; % This command sticks everything we just did onto the screen. It % syncs to the refresh rate of the display. mglFlush; end % Close the MGL window. mglClose; % Disable character listening. mglEatKeys([]); catch e % Close the MGL window. mglClose; % Disable character listening. mglEatKeys([]); % Send the error to the Matlab command window. rethrow(e); end function displayList = createDisplayList(meshData) % displayList = createDisplayList(meshData) % % Description: % Generates a display list containing the specified mesh. % % Input: % meshData (struct) - Struct containing the vertex and surface normal data. % % Output: % displayList (scalar) - A pointer to the generated display list. global GL; % Create the empty display list. displayList = glGenLists(1); % We stick all the stuff we want in the display list between glNewList and % glEndList. glNewList(displayList, GL.COMPILE); glBegin(GL.QUADS); numRows = size(meshData.x, 1); numCols = size(meshData.x, 2); % Loop over all the vertices in the mesh to render all the rectangle % polygons. for row = 1:numRows - 1 for col = 1:numCols - 1 % Upper left corner. glNormal3d(meshData.nx(row, col), meshData.ny(row, col), meshData.nz(row, col)); glVertex3d(meshData.x(row, col), meshData.y(row, col), meshData.z(row, col)); % Lower left corner. glNormal3d(meshData.nx(row+1, col), meshData.ny(row+1, col), meshData.nz(row+1, col)); glVertex3d(meshData.x(row+1, col), meshData.y(row+1, col), meshData.z(row+1, col)); % Lower right corner. glNormal3d(meshData.nx(row+1, col+1), meshData.ny(row+1, col+1), meshData.nz(row+1, col+1)); glVertex3d(meshData.x(row+1, col+1), meshData.y(row+1, col+1), meshData.z(row+1, col+1)); % Upper right corner. glNormal3d(meshData.nx(row, col+1), meshData.ny(row, col+1), meshData.nz(row, col+1)); glVertex3d(meshData.x(row, col+1), meshData.y(row, col+1), meshData.z(row, col+1)); end end glEnd; glEndList; function frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % % Description: % Takes some basic screen information and calculates the frustum parameters % required to setup a 3D projection matrix. % % Input: % screenDistance (scalar) - Distance from the screen to the observer. % screenDims (1x2) - Dimensions of the screen. (width, height) % horizontal offset (scalar) - Horizontal shift of the observer from the % center of the display. Should be 0 for regular displays and half the % interocular distance for stereo setups. % % Output: % frust (struct) - Struct containing all calculated frustum parameters. % Contains the following fields. % 1. left - Left edge of the near clipping plane. % 2. right - Right edge of the near clipping plane. % 3. top - Top edge of the near clipping plane. % 4. bottom - Bottom edge of the near clipping plane. % 5. near - Distance from the observer to the near clipping plane. % 6. far - Distance from the observer to the far clipping plane. if nargin ~= 3 error('Usage: frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset)'); end % I chose these constants as reasonable values for the distances from the % camera for the type of experiments the Brainard lab does. frustum.near = 1; frustum.far = 100; % Use similar triangles to figure out the boundaries of the near clipping % plane based on the information about the screen size and its distance % from the camera. frustum.right = (screenDims(1)/2 - horizontalOffset) * frustum.near / screenDistance; frustum.left = -(screenDims(1)/2 + horizontalOffset) * frustum.near / screenDistance; frustum.top = screenDims(2)/2 * frustum.near / screenDistance; frustum.bottom = -frustum.top;
github
BrainardLab/TeachingCode-master
MGL_MOGL_Rect3D.m
.m
TeachingCode-master/MGLExamples/MGL_MOGL_Rect3D.m
7,826
utf_8
e7461951771b128e13418a47d363f41b
function MGL_MOGL_Rect3D % MGL_MOGL_Rect3D % % Description: % Opens a full screen MGL window with a black background, and renders a % rectangle in 3D space. % % Keyboard Control: % 'r' - Randomly change the rectangle color. % 'k' - Moves the rectangle further away. % 'j' - Moves the rectangle closer. % 'a' - Moves the rectangle left. % 'd' - Moves the rectangle right. % 'w' - Moves the rectangle up. % 's' - Moves the rectangle down. % This setups up some OpenGL constants in the Matlab environment. % Essentially, anything in C OpenGL that starts with GL_ becomes GL.., e.g. % GL_RECT becomes GL.RECT. All GL_ are stored globally in the GL struct. global GL; InitializeMatlabOpenGL; % Setup some parameters we'll use. screenDims = [50 30]; % Width, height in centimeters of the display. screenDist = 50; % The distance from the observer to the display. backgroundRGB = [0 0 0]; % RGB of the background. All values are in the [0,1] range. rectDims = [10 6]; % Rectangle dimensions in centimeters. rectRGB = [1 0 0]; % Color of the rectangle in RGB. rectPos = [0 0 0]; % (x,y,z) position of the rectangle. rectInc = 1; % How much we'll move the rectangle for a given step. % This the half the distance between the observers 2 pupils. This value is % key in setting up the stereo perspective for the left and right eyes. % For a single screen setup, we'll use a value of 0 since we're not % actually in stereo. ioOffset = 0; try mglOpen; % We need to calculate a frustum to define our perspective matrix. % Using this data in combination with the glFrustum command, we can now % have a 3D rendering space instead of orthographic (2D). frustum = calculateFrustum(screenDist, screenDims, ioOffset); % Setup what our background color will be. We only need to do this % once unless we want to change our background color in the middle of % the program. glClearColor(backgroundRGB(1), backgroundRGB(2), backgroundRGB(3), ... 0); % This 4th value is the alpha value. We rarely care about it % for the background color. % Make sure we're testing for depth. Important if more than 1 thing is % on the screen and you don't want to deal with render order effects. glEnable(GL.DEPTH_TEST); % These help things rendered look nicer. glEnable(GL.BLEND); glEnable(GL.POLYGON_SMOOTH); glEnable(GL.LINE_SMOOTH); glEnable(GL.POINT_SMOOTH); % Turn on character listening. This function causes keyboard % characters to be gobbled up so they don't appear in any Matlab % window. mglEatKeys(1:50); % Clear the keyboard buffer. mglGetKeyEvent; keepDrawing = true; while keepDrawing % Look for a keyboard press. key = mglGetKeyEvent; % If the nothing was pressed keeping drawing. if ~isempty(key) % We can react differently to each key press. switch key.charCode case 'r' rectRGB = rand(1,3); % Move the rectangle closer to the subject. case 'j' rectPos(3) = rectPos(3) + rectInc; % Move the rectangle further from the subject. case 'k' rectPos(3) = rectPos(3) - rectInc; % Move the rectangle left. case 'a' rectPos(1) = rectPos(1) - rectInc; % Move the rectangle right. case 'd' rectPos(1) = rectPos(1) + rectInc; % Move the rectangle up. case 'w' rectPos(2) = rectPos(2) + rectInc; % Move the rectangle down. case 's' rectPos(2) = rectPos(2) - rectInc; % All other keys go here. otherwise fprintf('Exiting...\n'); % Quit our drawing loop. keepDrawing = false; end end % Setup the projection matrix. The projection matrix defines how % the OpenGL coordinate system maps onto the physical screen. glMatrixMode(GL.PROJECTION); % This gives us a clean slate to work with. glLoadIdentity; % Map our 3D rendering space to the display given a specific % distance from the screen to the subject and an interocular % offset. This is calculated at the beginning of the program. glFrustum(frustum.left, frustum.right, frustum.bottom, frustum.top, frustum.near, frustum.far); % Now we switch to the modelview mode, which is where we draw % stuff. glMatrixMode(GL.MODELVIEW); glLoadIdentity; % In 3D mode, we need to specify where the camera (the subject) is % in relation to the display. Essentially, for proper stereo, the % camera will be placed at the screen distance facing straight % ahead not at (0,0). gluLookAt(ioOffset, 0, screenDist, ... % Eye position ioOffset, 0, 0, ... % Fixation center 0, 1, 0); % Vector defining which way is up. % Clear our rendering space. If you don't do this rendered in the % buffer before will still be there. The scene is filled with the % background color specified above. glClear(mor(GL.COLOR_BUFFER_BIT, GL.DEPTH_BUFFER_BIT, GL.STENCIL_BUFFER_BIT, GL.ACCUM_BUFFER_BIT)); % Set the rectangle's color. glColor3dv(rectRGB); % This will center the rectangle on the screen. We call this prior % to specifying rectangle because all vertices are multiplied % against the current transformation matrix. In other words, the % order of operations happens in the opposite order they're written % in the code. glTranslated(-rectDims(1)/2 + rectPos(1), -rectDims(2)/2 + rectPos(2), rectPos(3)); % Draw the rectangle. glBegin(GL.QUADS); glVertex2d(0, 0); % Lower left corner glVertex2d(rectDims(1), 0); % Lower right corner glVertex2d(rectDims(1), rectDims(2)); % Upper right corner glVertex2d(0, rectDims(2)); % Upper left corner. glEnd; % This command sticks everything we just did onto the screen. It % syncs to the refresh rate of the display. mglFlush; end % Close the MGL window. mglClose; % Disable character listening. mglEatKeys([]); catch e % Close the MGL window. mglClose; % Disable character listening. mglEatKeys([]); % Send the error to the Matlab command window. rethrow(e); end function frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset) % % Description: % Takes some basic screen information and calculates the frustum parameters % required to setup a 3D projection matrix. % % Input: % screenDistance (scalar) - Distance from the screen to the observer. % screenDims (1x2) - Dimensions of the screen. (width, height) % horizontal offset (scalar) - Horizontal shift of the observer from the % center of the display. Should be 0 for regular displays and half the % interocular distance for stereo setups. % % Output: % frust (struct) - Struct containing all calculated frustum parameters. % Contains the following fields. % 1. left - Left edge of the near clipping plane. % 2. right - Right edge of the near clipping plane. % 3. top - Top edge of the near clipping plane. % 4. bottom - Bottom edge of the near clipping plane. % 5. near - Distance from the observer to the near clipping plane. % 6. far - Distance from the observer to the far clipping plane. if nargin ~= 3 error('Usage: frustum = calculateFrustum(screenDistance, screenDims, horizontalOffset)'); end % I chose these constants as reasonable values for the distances from the % camera for the type of experiments the Brainard lab does. frustum.near = 1; frustum.far = 100; % Use similar triangles to figure out the boundaries of the near clipping % plane based on the information about the screen size and its distance % from the camera. frustum.right = (screenDims(1)/2 - horizontalOffset) * frustum.near / screenDistance; frustum.left = -(screenDims(1)/2 + horizontalOffset) * frustum.near / screenDistance; frustum.top = screenDims(2)/2 * frustum.near / screenDistance; frustum.bottom = -frustum.top;
github
quantizedmassivemimo/1bit_precoding_VLSI-master
precoder_sim.m
.m
1bit_precoding_VLSI-master/precoder_sim.m
17,150
iso_8859_13
38b9849df5b7637eb31e03b1c657cfa0
% ========================================================================= % -- Simulator for 1-bit Massive MU-MIMO Precoding in VLSI with CxPO % ------------------------------------------------------------------------- % -- (c) 2016 Christoph Studer, Oscar Castañeda, and Sven Jacobsson % -- e-mail: [email protected], [email protected], and % -- [email protected] (version 0.1; August 14, 2017) % ------------------------------------------------------------------------- % -- If you use this simulator or parts of it, then you must cite our % -- journal paper: % -- Oscar Castañeda, Sven Jacobsson, Giuseppe Durisi, Mikael Coldrey, % -- Tom Goldstein, and Christoph Studer, "1-bit Massive MU-MIMO % -- Precoding in VLSI," IEEE Journal on Emerging and Selected Topics in % -- Circuits and Systems (JETCAS), to appear in 2017 % -- and clearly mention this in your paper % ------------------------------------------------------------------------- % -- REMEMBER: C1PO + C2PO = C(1+2)PO = C3PO :) % ========================================================================= function precoder_sim(varargin) % -- set up default/custom parameters if isempty(varargin) disp('using default simulation settings and parameters...') % set default simulation parameters par.runId = 0; % simulation ID (used to reproduce results) par.L = 2; % number of DAC levels per I or Q dimension (must be 2!!!) par.U = 16; % number of single-antenna users par.B = 256; % number of base-station antennas (B>>U) par.mod = '16QAM'; % modulation type: 'BPSK','QPSK','16QAM','64QAM','8PSK' par.trials = 1e3; % number of Monte-Carlo trials (transmissions) par.NTPdB_list = ... % list of normalized transmit power [dB] values -10:2:20; % to be simulated par.precoder = ... % precoding scheme(s) to be evaluated {'ZF','MRT','ZFQ','MRTQ','SQUID','C1PO','C2PO'}; par.save = true; % save results (true,false) par.plot = true; % plot results (true,false) % *** SQUID specific % % note that the SQUID code includes two more algorithm parameters that % must be tuned for best performance (if you know what you are doing). par.SQUID.iterations = 200; % *** C1PO specific % % reasonable parameters for C1PO with different system configurations % please optimize manually for best performance (depends on # of iters) % % BxU | mod. | gamma | delta | rho % -------+-------+-------+-------+------ % 32x16 | BPSK | 2^5 | 6.4 | 1.25 % 64x16 | BPSK | 2^4 | 3.2 | 1.25 % 128x16 | BPSK | 2^2 | 0.8 | 1.25 % 256x16 | BPSK | 2^3 | 1.6 | 1.25 % -------+-------+-------+-------+------ % 32x16 | QPSK | 2^5 | 6.4 | 1.25 % 64x16 | QPSK | 2^4 | 3.2 | 1.25 % 128x16 | QPSK | 2^2 | 0.8 | 1.25 % 256x16 | QPSK | 2^3 | 1.6 | 1.25 % -------+-------+-------+-------+------- % 256x16 | 16QAM | 2^1 | 0.4 | 1.25 % -------+-------+-------+-------+------- % 256x16 | 64QAM | 14 | 2.8 | 1.25 par.C1PO.gamma = 2^1; % good for 256x16 with 16-QAM par.C1PO.rho = 1.25; % rho = gamma/(gamma-delta) [aka. pushfactor] par.C1PO.iterations = 25; % max number of iterations % *** C2PO specific % % reasonable parameters for C2PO with different system configurations % please optimize manually for best performance (depends on # of iters) % % BxU | mod. | tau | delta | rho % -------+-------+-------+-------+------ % 32x16 | BPSK | 2^-6 | 12.8 | 1.25 % 64x16 | BPSK | 2^-7 | 25.6 | 1.25 % 128x16 | BPSK | 2^-7 | 25.6 | 1.25 % 256x16 | BPSK | 2^-8 | 51.2 | 1.25 % -------+-------+-------+-------+------ % 32x16 | QPSK | 2^-6 | 12.8 | 1.25 % 64x16 | QPSK | 2^-7 | 25.6 | 1.25 % 128x16 | QPSK | 2^-7 | 25.6 | 1.25 % 256x16 | QPSK | 2^-8 | 51.2 | 1.25 % -------+-------+-------+-------+------- % 256x16 | 16QAM | 2^-8 | 51.2 | 1.25 % -------+-------+-------+-------+------- % 256x16 | 64QAM | 2^-8 | 51.2 | 1.25 par.C2PO.tau = 2^(-8); % good for 256x16 with 16-QAM par.C2PO.rho = 1.25; % rho = 1/(1-tau*delta) [aka. pushfactor] par.C2PO.iterations = 25; % max number of iterations else disp('use custom simulation settings and parameters...') par = varargin{1}; % only argument is par structure end % -- initialization % the methods have only been checked for 1-bit transmission % an extension to multi-bit needs more work :) if par.L~=2 error('This simulator is specifically designed for 1-bit scenarios') end % use runId random seed (enables reproducibility) rng(par.runId); % simulation name (used for saving results) par.simName = ['ERR_',num2str(par.U),'x',num2str(par.B), '_', ... par.mod, '_', num2str(par.trials),'Trials']; % set up Gray-mapped constellation alphabet (according to IEEE 802.11) switch (par.mod) case 'BPSK', par.symbols = [ -1 1 ]; case 'QPSK', par.symbols = [ -1-1i,-1+1i,+1-1i,+1+1i ]; case '16QAM', par.symbols = [ -3-3i,-3-1i,-3+3i,-3+1i, ... -1-3i,-1-1i,-1+3i,-1+1i, ... +3-3i,+3-1i,+3+3i,+3+1i, ... +1-3i,+1-1i,+1+3i,+1+1i ]; case '64QAM', par.symbols = [ -7-7i,-7-5i,-7-1i,-7-3i,-7+7i,-7+5i,-7+1i,-7+3i, ... -5-7i,-5-5i,-5-1i,-5-3i,-5+7i,-5+5i,-5+1i,-5+3i, ... -1-7i,-1-5i,-1-1i,-1-3i,-1+7i,-1+5i,-1+1i,-1+3i, ... -3-7i,-3-5i,-3-1i,-3-3i,-3+7i,-3+5i,-3+1i,-3+3i, ... +7-7i,+7-5i,+7-1i,+7-3i,+7+7i,+7+5i,+7+1i,+7+3i, ... +5-7i,+5-5i,+5-1i,+5-3i,+5+7i,+5+5i,+5+1i,+5+3i, ... +1-7i,+1-5i,+1-1i,+1-3i,+1+7i,+1+5i,+1+1i,+1+3i, ... +3-7i,+3-5i,+3-1i,+3-3i,+3+7i,+3+5i,+3+1i,+3+3i ]; case '8PSK', par.symbols = [ exp(1i*2*pi/8*0), exp(1i*2*pi/8*1), ... exp(1i*2*pi/8*7), exp(1i*2*pi/8*6), ... exp(1i*2*pi/8*3), exp(1i*2*pi/8*2), ... exp(1i*2*pi/8*4), exp(1i*2*pi/8*5) ]; end % compute symbol energy par.Es = mean(abs(par.symbols).^2); % - quantizer paremeters % optimal LSB for 2 < L < 16 quantization levels lsb_list = [ 1.59628628628629, ... 1.22515515515516, ... 0.994694694694695, ... 0.842052052052052, ... 0.734304304304304, ... 0.650500500500501, ... 0.584654654654655, ... 0.533773773773774, ... 0.491871871871872, ... 0.455955955955956, ... 0.423033033033033, ... 0.396096096096096, ... 0.375145145145145, ... 0.354194194194194, ... 0.336236236236236 ]; % resolution (number of bits) of the DACs par.Q = log2(par.L); % least significant bit par.lsb = lsb_list(par.L-1)/sqrt(2*par.B); % clip level par.clip = par.lsb*par.L/2; % quantizer labels and thresholds [~, ~, par.labels, par.thresholds, ~] = uniquantiz(1, par.lsb, par.L); % normalization constant par.alpha = sqrt( 1/(2*par.B) ... /sum(par.labels.^2.*( ... normcdf(par.thresholds(2:end)*sqrt(2*par.B)) ... -normcdf(par.thresholds(1:end-1)*sqrt(2*par.B))))); % scale quantization labels par.labels = par.alpha*par.labels; % quantizer alphabet par.alphabet = combvec(par.labels, par.labels); par.alphabet = par.alphabet(1,:) + 1i*par.alphabet(2,:); % quantizer-mapping function par.quantizer = @(x) par.alpha * uniquantiz(x, par.lsb, par.L); % equivalent (average) quantizer gain par.F = par.alpha*par.lsb*... sum(normpdf(par.thresholds(2:end-1),0,1/sqrt(2*par.B))); % precompute bit labels par.bps = log2(length(par.symbols)); % number of bits per symbol par.bits = de2bi(0:length(par.symbols)-1,par.bps,'left-msb'); % track simulation time time_elapsed = 0; % -- start simulation % - initialize result arrays (detector x normalized transmit power) % vector error rate res.VER = zeros(length(par.precoder),length(par.NTPdB_list)); % symbol error rate res.SER = zeros(length(par.precoder),length(par.NTPdB_list)); % bit error rate res.BER = zeros(length(par.precoder),length(par.NTPdB_list)); % error-vector magnitude res.EVM = zeros(length(par.precoder),length(par.NTPdB_list)); % SINDR res.SINDR = zeros(length(par.precoder),length(par.NTPdB_list)); % transmit power res.TxPower = zeros(length(par.precoder),length(par.NTPdB_list)); % receive power res.RxPower = zeros(length(par.precoder),length(par.NTPdB_list)); % simulation beamforming time res.TIME = zeros(length(par.precoder),length(par.NTPdB_list)); % compute noise variances to be considered N0_list = 10.^(-par.NTPdB_list/10); % generate random bit stream (antenna x bit x trial) bits = randi([0 1],par.U,par.bps,par.trials); % trials loop tic for t=1:par.trials % generate transmit symbol idx = bi2de(bits(:,:,t),'left-msb')+1; s = par.symbols(idx).'; % generate iid Gaussian channel matrix and noise vector n = sqrt(0.5)*(randn(par.U,1)+1i*randn(par.U,1)); H = sqrt(0.5)*(randn(par.U,par.B)+1i*randn(par.U,par.B)); % algorithm loop for d=1:length(par.precoder) % normalized transmit power loop for k=1:length(par.NTPdB_list) % set noise variance N0 = N0_list(k); % record time used by the beamformer starttime = toc; % beamformers switch (par.precoder{d}) % noise-independent case 'ZF', % ZF beamforming (infinite precision) [x, beta] = ZF(par, s, H); case 'ZFQ', % ZF beamforming (quantized) [x, beta] = ZF(par, s, H); x = par.quantizer(x); beta = beta/par.F; case 'MRT', % MRT beamforming (infinite precision) [x, beta] = MRT(par, s, H); case 'MRTQ', % MRT beamforming (quantized) [x, beta] = MRT(par, s, H); x = par.quantizer(x); beta = beta/par.F; case 'C1PO', % C1PO: biConvex 1-bit PrecOding [x, beta] = C1PO(par, s, H); case 'C2PO', % C2PO: C1PO with simpler preprocessing [x, beta] = C2PO(par, s, H); % noise-dependent case 'SQUID', % SQUID: Squared inifinity-norm relaxation with % Douglas-Rachford splitting [x, beta] = SQUID(par,s,H,N0); otherwise, error('par.precoder not specified') end % record beamforming simulation time res.TIME(d,k) = res.TIME(d,k) + (toc-starttime); % transmit data over noisy channel Hx = H*x; y = Hx + sqrt(N0)*n; % extract transmit and receive power res.TxPower(d,k) = res.TxPower(d,k) + mean(sum(abs(x).^2)); res.RxPower(d,k) = res.RxPower(d,k) + mean(sum(abs(Hx).^2))/par.U; % user terminals can estimate the beamforming factor beta shat = beta*y; % perform user-side detection [~,idxhat] = min(abs(shat*ones(1,length(par.symbols)) ... -ones(par.U,1)*par.symbols).^2,[],2); bithat = par.bits(idxhat,:); % -- compute error and complexity metrics err = (idx~=idxhat); res.VER(d,k) = res.VER(d,k) + any(err); res.SER(d,k) = res.SER(d,k) + sum(err)/par.U; res.BER(d,k) = res.BER(d,k) + ... sum(sum(bits(:,:,t)~=bithat))/(par.U*par.bps); res.EVM(d,k) = res.EVM(d,k) + 100*norm(shat - s)^2/norm(s)^2; res.SINDR(d,k) = res.SINDR(d,k) + norm(s)^2/norm(shat - s)^2; end % NTP loop end % algorithm loop % keep track of simulation time if toc>10 time=toc; time_elapsed = time_elapsed + time; fprintf('estimated remaining simulation time: %3.0f min.\n',... time_elapsed*(par.trials/t-1)/60); tic end end % trials loop % normalize results res.VER = res.VER/par.trials; res.SER = res.SER/par.trials; res.BER = res.BER/par.trials; res.EVM = res.EVM/par.trials; res.SINDR = res.SINDR/par.trials; res.TxPower = res.TxPower/par.trials; res.RxPower = res.RxPower/par.trials; res.TIME = res.TIME/par.trials; res.time_elapsed = time_elapsed; % -- save final results (par and res structures) if par.save save([ par.simName '_' num2str(par.runId) ],'par','res'); end % -- show results (generates fairly nice Matlab plots) if par.plot % - BER results marker_style = {'k-','b:','r--','y-.','g-.','bs--','mv--'}; figure(1) for d=1:length(par.precoder) semilogy(par.NTPdB_list,res.BER(d,:),marker_style{d},'LineWidth',2); if (d==1) hold on end end hold off grid on box on xlabel('normalized transmit power [dB]','FontSize',12) ylabel('uncoded bit error rate (BER)','FontSize',12); if length(par.NTPdB_list) > 1 axis([min(par.NTPdB_list) max(par.NTPdB_list) 1e-3 1]); end legend(par.precoder,'FontSize',12,'location','southwest') set(gca,'FontSize',12); end end %% Uniform quantizer function [v, q, vl, vt, c] = uniquantiz(y, lsb, L) % set clip level c = lsb*L/2; % clip signal if isreal(y) yc = max(min(y,c-lsb/1e5),-(c-lsb/1e5)); else yc = max(min(real(y),c-lsb/1e5),-(c-lsb/1e5)) ... + 1i*max(min(imag(y),c-lsb/1e5),-(c-lsb/1e5)); end % quantizer if mod(L,2) == 0 % midrise quantizer (without clipping) Q = @(x) lsb*floor(x/lsb) + lsb/2; else % midtread quantizer (without clipping) Q = @(x) lsb*floor(x/lsb + 1/2); end % quantize signal if isreal(y) v = Q(yc); else v = Q(real(yc)) + 1i*Q(imag(yc)); end % quantization error q = v - y; % uniform quantization labels vl = lsb *((0:L-1) - (L-1)/2); % uniform quantization thresholds vt = [-realmax*ones(length(lsb),1), ... bsxfun(@minus, vl(:,2:end), lsb/2), ... realmax*ones(length(lsb),1)]; end %% Zero-forcing beamforming (with infinite precision) function [x, beta] = ZF(par, s, H) % normalization constant (average gain) rho = sqrt((par.B-par.U)/(par.Es*par.U)); % transmitted signal x = rho*H'/(H*H')*s; % beamforming factor beta = 1/rho; end %% Maximum ratio transmission (MRT) beamforming (with infinite precision) function [x, beta, P] = MRT(par, s, H) % normalization constant gmrt = 1/sqrt(par.Es*par.U*par.B); % average gain % gmrt = 1/sqrt(par.Es*trace(H*H')); % instant gain % precoding matrix P = gmrt*H'; % transmitted signal x = P*s; % scaling factor beta = sqrt(par.U*par.Es/par.B); end %% C1PO: biConvex 1-bit PrecOding (Algorithm 1) function [x, beta] = C1PO(par,s,H) % initial guess x = H'*s; % preprocessing with exact inverse gammainv = 1/par.C1PO.gamma; Ainv = inv(eye(par.B) + gammainv*H'*(eye(par.U)-s*s'/norm(s,2)^2)*H); % main C1PO algorithm loop for i=2:par.C1PO.iterations x = par.C1PO.rho*(Ainv*x); x = min(max(real(x),-1),1) + 1i*min(max(imag(x),-1),1); end x = (sign(real(x))+1i*sign(imag(x)))/sqrt(2*par.B); % scaling factor beta = norm(s,2)^2/(s'*H*x); end %% C2PO: biConvex 1-bit PrecOding with simplified processing (Algorithm 2) function [x, beta] = C2PO(par,s,H) % initial guess x = H'*s; % preprocessing with approximate inverse tau = par.C2PO.tau; % step size Ainvapprox = eye(par.B) - tau*H'*(eye(par.U)-s*s'/norm(s,2)^2)*H ; % main C1PO algorithm loop for i=2:par.C2PO.iterations x = par.C2PO.rho*(Ainvapprox*x); x = min(max(real(x),-1),1) + 1i*min(max(imag(x),-1),1); end x = (sign(real(x))+1i*sign(imag(x)))/sqrt(2*par.B); % scaling factor beta = norm(s,2)^2/(s'*H*x); end %% Squared inifinity-norm relaxation with Douglas-Rachford splitting % (SQUID) (1-bit beamforming algorithm) function [x,beta] = SQUID(par,s,H,N0) % -- real-valued decomposition HR = [ real(H) -imag(H) ; imag(H) real(H) ]; sR = [ real(s) ; imag(s) ]; % -- initialization x = zeros(par.B*2,1); y = zeros(par.B*2,1); gain = 1; % ADMM algorithm parameter epsilon = 1e-5; % ADMM algorithm parameter Ainv = inv(HR'*HR + 0.5/gain*eye(par.B*2)); sREG = Ainv*(HR'*sR); % -- SQUID loop for t=1:par.SQUID.iterations u = sREG + 0.5/gain*(Ainv*(2*x-y)); xold = x; x = prox_infinityNorm2(y+u-x,2*2*par.U*par.B*N0); if norm(x-xold)/norm(x)<epsilon break; end y = y + u - x; end % -- extract binary solution xRest = sign(x); x = 1/sqrt(2*par.B)*(xRest(1:par.B,1)+1i*xRest(par.B+1:2*par.B,1)); % -- compute output gains beta = real(x'*H'*s)/(norm(H*x,2)^2+par.U*N0); if beta < 0 warning('SQUID: negative precoding factor!'); end end %% Infinity^2 proximal operator function [ xk ] = prox_infinityNorm2(w,lambda) N = length(w); wabs = abs(w); ws = (cumsum(sort(wabs,'descend')))./(lambda+(1:N)'); alphaopt = max(ws); if alphaopt>0 % -- truncation step xk = min(wabs,alphaopt).*sign(w); else xk = zeros(size(w)); end end
github
AnriKaede/IM-master
FMSearchTokenField.m
.m
IM-master/mac/TeamTalk/interface/mainWindow/FMSearchTokenField.m
4,519
utf_8
2a89df28133e0c91280b5daf58944c94
// // FMSearchTokenField.m // Duoduo // // Created by zuoye on 13-12-23. // Copyright (c) 2013年 zuoye. All rights reserved. // #import "FMSearchTokenField.h" #import "FMSearchTokenFieldCell.h" @implementation FMSearchTokenField @synthesize sendActionWhenEditing=_sendActionWhenEditing; @synthesize alwaysSendActionWhenPressEnter=_alwaysSendActionWhenPressEnter; +(void)initialize { [FMSearchTokenField setCellClass:[FMSearchTokenFieldCell class]]; } - (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) { self.sendActionWhenEditing = NO; self.alwaysSendActionWhenPressEnter = NO; self.m_tokenizingChar = 0x2c; /* var_32 = rdi; var_40 = *0x1002c3b58; rax = [[&var_32 super] initWithFrame:edx]; if (rax != 0x0) { rbx.sendActionWhenEditing = 0x0; rbx.alwaysSendActionWhenPressEnter = 0x0; rax = [NSMutableString alloc]; rax = [rax init]; rbx.m_untokenizedStringValue = rax; rbx.m_tokenizingChar = 0x2c; //44 } rax = rbx; return rax; */ } return self; } -(void)setTokenizingChars:(NSString *) chars{ self.m_tokenizingChar = [chars characterAtIndex:0]; [self setTokenizingCharacterSet:[NSCharacterSet characterSetWithCharactersInString:chars]]; } /* function methImpl_FMSearchTokenField_tokenCount { rbx = rdi; rax = [rdi tokenStyle]; rcx = rax; rax = 0x1; if (rcx == 0x1) goto loc_0x100111ce7; goto loc_100111c3f; loc_100111ce7: return rax; loc_100111c3f: rax = [rbx currentEditor]; if (rax == 0x0) goto loc_0x100111cf6; goto loc_100111c58; loc_100111cf6: rax = [rbx attributedStringValue]; rax = [rax length]; loc_100111c58: rax = [rax attributedString]; rax = [rax length]; r13 = 0x0; if (rax != 0x0) { rbx = 0x0; r13 = 0x0; do { rax = [r14 attribute:**NSAttachmentAttributeName atIndex:rbx effectiveRange:0x0]; r13 = r13 - 0xff + CARRY(CF); rax = [r14 length]; } while (rbx + 0x1 < rax); } rax = [r14 length]; rax = ((rax != r13 ? 0xff : 0x0) & 0xff) + r13; goto loc_100111ce7; } */ /* $rdi == arg0 (ObjC: self) $rsi == arg1 (ObjC: op, or _cmd) $rdx == arg2 (ObjC: first arg of method) $rcx == arg3 (ObjC: second arg of method) cell $r8 == arg4 第三个参数 $r9 == arg5 第四个 */ - (void)drawRect:(NSRect)dirtyRect{ if([[self subviews] count]>0){ NSView *view = [[self subviews] objectAtIndex:0]; if ([view isKindOfClass:[FMSearchTokenFieldCell class]]) { NSRect cellRect ; if ([self cell]) { cellRect = [[self cell] bounds]; } NSRect imageRect ; NSRect textRect; [(FMSearchTokenFieldCell *)view divideFrame:cellRect ToImageRect:&imageRect textRect:&textRect buttonRect:nil callFromView:YES]; [view setFrame:cellRect]; } } /* r12 = rdi; rax = [rdi subviews]; rax = [rax count]; if (rax != 0x0) { rax = [rbx objectAtIndex:0x0]; r14 = rax; rax = [*0x1002c29e8 class]; rax = [r14 isKindOfClass:rax]; if (rax != 0x0) { rax = [r12 cell]; r15 = rax; if (r12 != 0x0) { var_80 = [r12 bounds]; } else { } rbx = *objc_msgSend; rdx = 0x0; (*objc_msgSend)(r15, @selector(divideFrame:ToImageRect:textRect:buttonRect:callFromView:), rdx, &var_112, 0x0, 0x1); var_72 = var_136; var_64 = var_128; var_56 = var_120; var_48 = var_112; [r14 setFrame:rdx]; } } rax = &arg_0; var_32 = r12; var_40 = *0x1002c3b58; rax = [[&var_32 super] drawRect:edx]; return rax; */ [super drawRect:dirtyRect]; } /* function methImpl_FMSearchTokenField_dealloc { rbx = rdi; r14 = objc_msg_release; [rbx.m_buttonTrackingArea release]; [rbx.m_untokenizedStringValue release]; var_0 = rbx; var_8 = *0x1002c3b58; rax = [[&var_0 super] dealloc]; return rax; } */ -(void)mouseDown:(NSEvent *)theEvent{ } -(void)mouseUp:(NSEvent *)theEvent{ } -(void)mouseEntered:(NSEvent *)theEvent{ } -(void)mouseExited:(NSEvent *)theEvent{ } -(BOOL)isFlipped{ return NO; } @end
github
AnriKaede/IM-master
DDNinePartImage.m
.m
IM-master/mac/TeamTalk/interface/mainWindow/searchField/DDNinePartImage.m
6,722
utf_8
6dac0c29b80d07b31ccfd0b48ec932de
// // DDNinePartImage.m // Duoduo // // Created by zuoye on 14-1-20. // Copyright (c) 2014年 zuoye. All rights reserved. // #import "DDNinePartImage.h" @implementation DDNinePartImage -(id)initWithNSImage:(NSImage *)image leftPartWidth:(CGFloat)leftWidth rightPartWidth:(CGFloat)rightWidth topPartHeight:(CGFloat)topHeight bottomPartHeight:(CGFloat)bottomHeight{ return [self initWithNSImage:image leftPartWidth:leftWidth rightPartWidth:rightWidth topPartHeight:topHeight bottomPartHeight:bottomHeight flipped:NO]; } -(id)initWithNSImage:(NSImage *)image leftPartWidth:(CGFloat)leftWidth rightPartWidth:(CGFloat)rightWidth topPartHeight:(CGFloat)topHeight bottomPartHeight:(CGFloat)bottomHeight flipped:(BOOL)flipped{ self = [super init]; if (self) { //size 是指块图片的大小. // topLeftCornerImage = [DDNinePartImage getPartImage:image withSize:<#(NSSize)#> fromRect:<#(NSRect)#>] } return self; } /* function meth_TXNinePartImage_dealloc { edi = arg_0; [*(edi + 0x1c) release]; //topLeftCornerImage [*(edi + 0x20) release]; //topEdgeImage [*(edi + 0x24) release]; //topRightCornerImage [*(edi + 0x28) release]; //leftEdgeImage [*(edi + 0x2c) release]; //centerImage [*(edi + 0x30) release]; //rightEdgeImage [*(edi + 0x34) release]; //bottomLeftCornerImage [*(edi + 0x38) release]; //bottomEdgeImage [*(edi + 0x3c) release]; //bottomRightCornerImage var_8 = edi; var_12 = *0xca2ce4; eax = [[&var_8 super] dealloc]; return eax; } */ -(void)drawInRect:(NSRect)rect fromRect:(NSRect)fromRect operation:(NSCompositingOperation)op fraction:(CGFloat)delta{ [self drawInRect:rect compositingOperation:op alphaFraction:delta flipped:NO]; } -(void)drawInRect:(NSRect)rect compositingOperation:(NSCompositingOperation)op alphaFraction:(CGFloat)alphaFraction flipped:(BOOL)isFlipped{ NSGraphicsContext *context = [NSGraphicsContext currentContext]; [context saveGraphicsState]; [context setShouldAntialias:YES]; NSDrawNinePartImage(rect, topLeftCornerImage, topEdgeImage, topRightCornerImage, leftEdgeImage, centerImage, rightEdgeImage, bottomLeftCornerImage, bottomEdgeImage, bottomRightCornerImage, op, alphaFraction, isFlipped); [context restoreGraphicsState]; } +(NSImage *)getPartImage:(NSImage *)image withSize:(NSSize)size fromRect:(NSRect)rect{ NSImage *im = [[NSImage alloc] initWithSize:size]; [im lockFocus]; [image drawInRect:NSMakeRect(0, 0, size.width, size.height) fromRect:rect operation:NSCompositeCopy fraction:1]; [im unlockFocus]; return im; } /* $rdi == arg0 (ObjC: self) $rsi == arg1 (ObjC: op, or _cmd) $rdx == arg2 (ObjC: first arg of method) $rcx == arg3 (ObjC: second arg of method) cell $r8 == arg4 第三个参数 $r9 == arg5 第四个 */ /* function meth_TXNinePartImage_initWithNSImage_leftPartWidth_rightPartWidth_topPartHeight_bottomPartHeight_flipped_ { var_240 = arg_0; var_244 = *0xca2ce4; eax = [[&var_240 super] init]; if (eax != 0x0) { ecx = arg_8; edi = ecx; eax = [ecx size]; var_48 = eax; [edi size]; floorf(edx); asm{ fstp tword [ss:ebp-0x108+var_60] }; floorf(arg_14); asm{ fstp dword [ss:ebp-0x108+var_80] }; asm{ fld tword [ss:ebp-0x108+var_60] }; asm{ fstp dword [ss:ebp-0x108+var_92] }; floorf(arg_C); asm{ fstp dword [ss:ebp-0x108+var_72] }; xmm3 = var_80; var_52 = xmm3; xmm0 = var_92 - xmm3; var_60 = xmm0; var_224 = 0x0; var_228 = xmm0; xmm0 = var_72; var_56 = xmm0; var_232 = xmm0; var_236 = xmm3; eax = [TXNinePartImage getPartImage:edi withSize:xmm0 fromRect:xmm3]; eax = [eax retain]; *(esi + 0x1c) = eax; floorf(var_48); var_36 = esi; var_208 = var_56; asm{ fstp dword [ss:ebp-0x108+var_88] }; floorf(arg_10); asm{ fstp dword [ss:ebp-0x108+var_76] }; var_212 = var_60; xmm0 = var_88; var_48 = xmm0; xmm1 = var_76; var_44 = xmm1; xmm0 = xmm0 - var_56 - xmm1; var_40 = xmm0; var_216 = xmm0; xmm3 = var_52; var_220 = xmm3; esi = var_36; eax = [TXNinePartImage getPartImage:edi withSize:xmm0 fromRect:xmm3]; eax = [eax retain]; *(esi + 0x20) = eax; xmm0 = var_44; xmm1 = var_48 - xmm0; var_48 = xmm1; var_192 = xmm1; var_196 = var_60; var_200 = xmm0; xmm3 = var_52; var_204 = xmm3; eax = [TXNinePartImage getPartImage:edi withSize:xmm0 fromRect:xmm3]; eax = [eax retain]; *(esi + 0x24) = eax; floorf(arg_18); asm{ fstp dword [ss:ebp-0x108+var_84] }; var_176 = 0x0; xmm1 = var_84; var_52 = xmm1; var_180 = xmm1; xmm2 = var_56; var_184 = xmm2; xmm0 = var_60 - xmm1; var_60 = xmm0; var_188 = xmm0; eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm0]; eax = [eax retain]; *(esi + 0x28) = eax; var_160 = var_56; var_164 = var_52; xmm2 = var_40; var_168 = xmm2; xmm3 = var_60; var_172 = xmm3; eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm3]; eax = [eax retain]; *(esi + 0x2c) = eax; var_144 = var_48; var_148 = var_52; xmm2 = var_44; var_152 = xmm2; xmm3 = var_60; var_156 = xmm3; eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm3]; eax = [eax retain]; *(esi + 0x30) = eax; var_128 = 0x0; var_132 = 0x0; xmm2 = var_56; var_136 = xmm2; xmm3 = var_52; var_140 = xmm3; eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm3]; eax = [eax retain]; *(esi + 0x34) = eax; var_112 = var_56; var_116 = 0x0; xmm3 = var_40; var_120 = xmm3; xmm2 = var_52; var_124 = xmm2; eax = [TXNinePartImage getPartImage:edi withSize:xmm3 fromRect:xmm2]; eax = [eax retain]; *(esi + 0x38) = eax; var_96 = var_48; var_100 = 0x0; xmm2 = var_44; var_104 = xmm2; xmm3 = var_52; var_108 = xmm3; eax = [TXNinePartImage getPartImage:edi withSize:xmm2 fromRect:xmm3]; eax = [eax retain]; *(esi + 0x3c) = eax; *(int8_t *)(esi + 0x40) = arg_1C; } eax = esi; return eax; } */ @end
github
AnriKaede/IM-master
echo_diagnostic.m
.m
IM-master/win-client/3rdParty/src/libspeex/libspeex/echo_diagnostic.m
2,076
utf_8
8d5e7563976fbd9bd2eda26711f7d8dc
% Attempts to diagnose AEC problems from recorded samples % % out = echo_diagnostic(rec_file, play_file, out_file, tail_length) % % Computes the full matrix inversion to cancel echo from the % recording 'rec_file' using the far end signal 'play_file' using % a filter length of 'tail_length'. The output is saved to 'out_file'. function out = echo_diagnostic(rec_file, play_file, out_file, tail_length) F=fopen(rec_file,'rb'); rec=fread(F,Inf,'short'); fclose (F); F=fopen(play_file,'rb'); play=fread(F,Inf,'short'); fclose (F); rec = [rec; zeros(1024,1)]; play = [play; zeros(1024,1)]; N = length(rec); corr = real(ifft(fft(rec).*conj(fft(play)))); acorr = real(ifft(fft(play).*conj(fft(play)))); [a,b] = max(corr); if b > N/2 b = b-N; end printf ("Far end to near end delay is %d samples\n", b); if (b > .3*tail_length) printf ('This is too much delay, try delaying the far-end signal a bit\n'); else if (b < 0) printf ('You have a negative delay, the echo canceller has no chance to cancel anything!\n'); else printf ('Delay looks OK.\n'); end end end N2 = round(N/2); corr1 = real(ifft(fft(rec(1:N2)).*conj(fft(play(1:N2))))); corr2 = real(ifft(fft(rec(N2+1:end)).*conj(fft(play(N2+1:end))))); [a,b1] = max(corr1); if b1 > N2/2 b1 = b1-N2; end [a,b2] = max(corr2); if b2 > N2/2 b2 = b2-N2; end drift = (b1-b2)/N2; printf ('Drift estimate is %f%% (%d samples)\n', 100*drift, b1-b2); if abs(b1-b2) < 10 printf ('A drift of a few (+-10) samples is normal.\n'); else if abs(b1-b2) < 30 printf ('There may be (not sure) excessive clock drift. Is the capture and playback done on the same soundcard?\n'); else printf ('Your clock is drifting! No way the AEC will be able to do anything with that. Most likely, you''re doing capture and playback from two different cards.\n'); end end end acorr(1) = .001+1.00001*acorr(1); AtA = toeplitz(acorr(1:tail_length)); bb = corr(1:tail_length); h = AtA\bb; out = (rec - filter(h, 1, play)); F=fopen(out_file,'w'); fwrite(F,out,'short'); fclose (F);
github
AnriKaede/IM-master
echo_diagnostic.m
.m
IM-master/android/app/src/main/jni/libspeex/echo_diagnostic.m
2,076
utf_8
8d5e7563976fbd9bd2eda26711f7d8dc
% Attempts to diagnose AEC problems from recorded samples % % out = echo_diagnostic(rec_file, play_file, out_file, tail_length) % % Computes the full matrix inversion to cancel echo from the % recording 'rec_file' using the far end signal 'play_file' using % a filter length of 'tail_length'. The output is saved to 'out_file'. function out = echo_diagnostic(rec_file, play_file, out_file, tail_length) F=fopen(rec_file,'rb'); rec=fread(F,Inf,'short'); fclose (F); F=fopen(play_file,'rb'); play=fread(F,Inf,'short'); fclose (F); rec = [rec; zeros(1024,1)]; play = [play; zeros(1024,1)]; N = length(rec); corr = real(ifft(fft(rec).*conj(fft(play)))); acorr = real(ifft(fft(play).*conj(fft(play)))); [a,b] = max(corr); if b > N/2 b = b-N; end printf ("Far end to near end delay is %d samples\n", b); if (b > .3*tail_length) printf ('This is too much delay, try delaying the far-end signal a bit\n'); else if (b < 0) printf ('You have a negative delay, the echo canceller has no chance to cancel anything!\n'); else printf ('Delay looks OK.\n'); end end end N2 = round(N/2); corr1 = real(ifft(fft(rec(1:N2)).*conj(fft(play(1:N2))))); corr2 = real(ifft(fft(rec(N2+1:end)).*conj(fft(play(N2+1:end))))); [a,b1] = max(corr1); if b1 > N2/2 b1 = b1-N2; end [a,b2] = max(corr2); if b2 > N2/2 b2 = b2-N2; end drift = (b1-b2)/N2; printf ('Drift estimate is %f%% (%d samples)\n', 100*drift, b1-b2); if abs(b1-b2) < 10 printf ('A drift of a few (+-10) samples is normal.\n'); else if abs(b1-b2) < 30 printf ('There may be (not sure) excessive clock drift. Is the capture and playback done on the same soundcard?\n'); else printf ('Your clock is drifting! No way the AEC will be able to do anything with that. Most likely, you''re doing capture and playback from two different cards.\n'); end end end acorr(1) = .001+1.00001*acorr(1); AtA = toeplitz(acorr(1:tail_length)); bb = corr(1:tail_length); h = AtA\bb; out = (rec - filter(h, 1, play)); F=fopen(out_file,'w'); fwrite(F,out,'short'); fclose (F);
github
truongd8593/1D-Shallow-Water-equations-master
Fr.m
.m
1D-Shallow-Water-equations-master/Fr.m
207
utf_8
b7adb7763a8a9f44c45ad2ce3924eec0
%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Froude %%%%%%%%%%%%%%%%%%%%%%%%%%%% function [froude] = Fr(U) global g; if ( U(1) == 0 ) froude = 0.; else froude = U(2)/(U(1)*sqrt(g*U(1))); end end
github
posgraph/coupe.bilateral-texture-filtering-master
btf_2d_color_gpu.m
.m
coupe.bilateral-texture-filtering-master/bilateralTextureFiltering/btf_2d_color_gpu.m
3,053
utf_8
d6329d1d843ceb6c8424dd6bc33deca4
function r_img = btf_2d_color_gpu(I, fr, n_iter, fr_blf) % btf_2d_color_gpu - Bilateral Texture Filtering % % S = btf_2d_color_gpu(I, fr, n_iter, fr_blf) extracts structure S from % input I, with scale parameter fr, joint filtering scale fr_blf and % iteration number n_iter. % % Paras: % @I : Input image, both grayscale and color images are acceptable. % @fr : Parameter specifying the maximum size of texture elements. % @n_iter : Number of itearations, 5 by default. % @fr_blf : Parameter specifying kernel size of joint bilateral filtering. % % Example % ========== % I = imread('input.png'); % radius = 3; % iterations = 3; % radius_bf = radius * 2; % S = btf_2d_color_gpu(I, radius, iterations, radius_bf); % % ========== % The Code is created based on the following paper % [1] "Bilateral Texture Filtering", Hojin Cho, Hyunjoon Lee, Seungyong Lee, ACM Transactions on Graphics, % (SIGGRAPH 2014), 2014. % The code and the algorithm are for non-comercial use only. % global o_img if ~exist('fr_blf', 'var') || isempty(fr_blf), fr_blf = 2*fr; end if ~exist('n_iter', 'var') || isempty(n_iter), n_iter = 5; end sigma_avg = 0.05*sqrt(size(I, 3)); sigma_alpha = 5; tic; I = gpuArray(im2single(I)); o_img = I; for iter = 1:n_iter fprintf('iter = %d\n', iter); L = I; Gc = cell(fr, 1); %Lcpu = gather(L); for i = fr:fr B = imfilter(L, fspecial('average', 2*i+1), 'symmetric'); % MRTV Delta = comp_Delta_gpu(L, i); M = comp_MRTV_gpu(L, i); M = mean(M.*Delta, 3); % comp_S [S, M_min, ~] = comp_S(B, M, i); % alpha blending M_diff = M - M_min; alpha = sigmoid(M_diff, sigma_alpha); alpha = (alpha - 0.5) * 2; alpha = repmat(alpha, [1 1 size(S, 3)]); G = (alpha).*S + (1-alpha).*B; Gc{i} = G; end G = Gc{end}; r_img = blf_2d_gpu(I, G, fr_blf, sigma_avg); I = r_img; end r_img = gather(I); et = toc; disp(['elapsed time = ' num2str(et)]); end function b = sigmoid(a, p) b = 1 ./ (1 + exp(-p.*a)); end % comp_S function [S, M_min, min_idx] = comp_S(B, M, fr) [h, w, d] = size(B); p_M = padarray(M, [fr fr], 'replicate'); p_B = padarray(B, [fr fr], 'symmetric'); pu = fr+1; pb = pu+h-1; pl = fr+1; pr = pl+w-1; % minimum value S = B; %gpuArray(zeros(size(B), 'single')); M_min = M; %gpuArray(ones(h, w, 'single')*1000); % arbitrary large value oX = gpuArray(zeros(h, w, 'single')); oY = gpuArray(zeros(h, w, 'single')); min_idx = gpuArray(reshape(1:h*w, [h w])); p_min_idx = padarray(min_idx, [fr fr], 'symmetric'); for x = -fr:fr for y = -fr:fr n_M = p_M(pu+y:pb+y, pl+x:pr+x); n_B = p_B(pu+y:pb+y, pl+x:pr+x, :); n_min_idx = p_min_idx(pu+y:pb+y, pl+x:pr+x); idx = n_M < M_min; M_min = min(M_min, n_M); oX = oX.*(1-idx) + x.*idx; oY = oY.*(1-idx) + y.*idx; min_idx = n_min_idx.*idx + min_idx.*(1-idx); idx = repmat(idx, [1 1 d]); S = n_B.*idx + S.*(1-idx); end end end
github
latelee/caffe-master
classification_demo.m
.m
caffe-master/matlab/demo/classification_demo.m
5,466
utf_8
45745fb7cfe37ef723c307dfa06f1b97
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to the Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % and what versions are installed. % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab code for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to your Matlab search PATH in order to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
InverseTampere/TreeQSM-master
make_models_parallel.m
.m
TreeQSM-master/src/make_models_parallel.m
8,030
utf_8
11981cd204b15a2aced81d8c7a0a25ad
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function QSMs = make_models_parallel(dataname,savename,Nmodels,inputs) % --------------------------------------------------------------------- % MAKE_MODELS.M Makes QSMs of given point clouds. % % Version 1.1.2 % Latest update 9 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Makes QSMs of given point clouds specified by the "dataname" and by the % other inputs. The results are saved into file named "savename". % Notice, the code does not save indivual QSM runs into their own .mat or % .txt files but saves all models into one big .mat file. Same as % MAKE_MODELS but uses parfor command (requires Parallel Computing Toolbox) % which allows the utilization of multiple processors/cores to compute in % parallel number of QSMs with the same inputs. % % Inputs: % dataname String specifying the .mat-file containing the point % clouds that are used for the QSM reconstruction. % savename String, the name of the file where the QSMs are saved % Nmodels (Optional) Number of models generated for each input % (cloud and input parameters). Default value is 5. % inputs (Optional) The input parameters structure. Can be defined % below as part of this code. Can also be given as a % structure array where each tree gets its own, possibly % uniquely, defined parameters (e.g. optimal parameters) % but each tree has to have same number of parameter values. % % Output: % QSMs Structure array containing all the QSMs generated % --------------------------------------------------------------------- % Changes from version 1.1.1 to 1.1.2, 18 Aug 2020: % 1) Removed the inputs "lcyl" and "FilRad" from the inputs and the % calculations of number of input parameters % Changes from version 1.1.0 to 1.1.1, 13 Jan 2020: % 1) Changed "m = m+n;" to "m = m+n(j);" at the end of the function. % Changes from version 1.0.0 to 1.1.0, 03 Oct 2019: % 1) Added try-catch structure where "treeqsm" is called, so that if there % is an error during the reconstruction process of one tree, then the % larger process of making multiple QSMs from multiple tree is not % stopped. % 2) Changed the way the data is loaded. Previously all the data was % loaded into workspace, now only one point cloud is in the workspace. % 3) Corrected a bug where incomplete QSM was saved as complete QSM % 4) Changed where the input-structure for each tree reconstructed % 5) Changed the coding to separate more the results of the different % parallel processes (less warnings and errors) if nargin < 2 disp('Not enough inputs, no models generated!') QSMs = struct([]); return end if nargin == 2 Nmodels = 5; % Number of models per inputs, usually about 5 models is enough end %% Define the parameter values if nargin == 3 || nargin == 2 % The following parameters can be varied and should be optimised % (each can have multiple values): % Patch size of the first uniform-size cover: inputs.PatchDiam1 = [0.08 0.15]; % Minimum patch size of the cover sets in the second cover: inputs.PatchDiam2Min = [0.015 0.025]; % Maximum cover set size in the stem's base in the second cover: inputs.PatchDiam2Max = [0.06 0.08]; % The following parameters can be varied and but usually can be kept as % shown (i.e. as little bigger than PatchDiam parameters): % Ball radius used for the first uniform-size cover generation: inputs.BallRad1 = inputs.PatchDiam1+0.02; % Maximum ball radius used for the second cover generation: inputs.BallRad2 = inputs.PatchDiam2Max+0.01; % The following parameters can be usually kept fixed as shown: inputs.nmin1 = 3; % Minimum number of points in BallRad1-balls, good value is 3 inputs.nmin2 = 1; % Minimum number of points in BallRad2-balls, good value is 1 inputs.OnlyTree = 1; % If "1", then point cloud contains points only from the tree inputs.Tria = 0; % If "1", then triangulation produces inputs.Dist = 1; % If "1", then computes the point-model distances % Different cylinder radius correction options for modifying too large and % too small cylinders: % Traditional TreeQSM choices: % Minimum cylinder radius, used particularly in the taper corrections: inputs.MinCylRad = 0.0025; % Child branch cylinders radii are always smaller than the parent % branche's cylinder radii: inputs.ParentCor = 1; % Use partially linear (stem) and parabola (branches) taper corrections: inputs.TaperCor = 1; % Growth volume correction approach introduced by Jan Hackenberg, % allometry: GrowthVol = a*Radius^b+c % Use growth volume correction: inputs.GrowthVolCor = 0; % fac-parameter of the growth vol. approach, defines upper and lower % boundary: inputs.GrowthVolFac = 2.5; inputs.name = 'test'; inputs.tree = 0; inputs.plot = 0; inputs.savetxt = 0; inputs.savemat = 0; inputs.disp = 0; end % Compute the number of input parameter combinations in = inputs(1); ninputs = prod([length(in.PatchDiam1) length(in.PatchDiam2Min)... length(in.PatchDiam2Max)]); %% Load data matobj = matfile([dataname,'.mat']); names = fieldnames(matobj); i = 1; n = max(size(names)); while i <= n && ~strcmp(names{i,:},'Properties') i = i+1; end I = (1:1:n); I = setdiff(I,i); names = names(I,1); names = sort(names); nt = max(size(names)); % number of trees/point clouds %% make the models QSMs = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},... 'pmdistance',{},'triangulation',{}); % Generate Inputs struct that contains the input parameters for each tree if max(size(inputs)) == 1 for i = 1:nt Inputs(i) = inputs; Inputs(i).name = names{i}; Inputs(i).tree = i; Inputs(i).plot = 0; Inputs(i).savetxt = 0; Inputs(i).savemat = 0; Inputs(i).disp = 0; end else Inputs = inputs; end m = 1; for t = 1:nt % trees disp(['Modelling tree ',num2str(t),'/',num2str(nt),' (',Inputs(t).name,'):']) P = matobj.(Inputs(t).name); qsms = cell(Nmodels,1); % save here the accepted models qsm = cell(Nmodels,1); % cell-structure to keep different models separate n = ones(Nmodels,1); n0 = zeros(Nmodels,1); k = ones(Nmodels,1); parfor j = 1:Nmodels % generate N models per input inputs = Inputs(t); inputs.model = j; while k(j) <= 5 % try up to five times to generate non-empty models try qsm{j} = treeqsm(P,inputs); catch qsm{j} = struct('cylinder',{},'branch',{},'treedata',{},... 'rundata',{},'pmdistance',{},'triangulation',{}); qsm{j}(ninputs).treedata = 0; end n(j) = max(size(qsm{j})); Empty = false(n(j),1); for b = 1:n(j) if isempty(qsm{j}(b).branch) Empty(b) = true; end end if n(j) < ninputs || any(Empty) n(j) = nnz(~Empty); k(j) = k(j)+1; if n(j) > n0(j) qsms{j} = qsm{j}(~Empty); n0(j) = n(j); end else % Successful models generated qsms{j} = qsm{j}; k(j) = 10; end end if k(j) == 6 disp('Incomplete run!!') end end % Save the models for j = 1:Nmodels QSM = qsms{j}; a = max(size(QSM)); QSMs(m:m+a-1) = QSM; m = m+n(j); end str = ['results/',savename]; save(str,'QSMs') end
github
InverseTampere/TreeQSM-master
make_models.m
.m
TreeQSM-master/src/make_models.m
7,381
utf_8
4c4a04194131735e4fc02825bc11a987
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function QSMs = make_models(dataname,savename,Nmodels,inputs) % --------------------------------------------------------------------- % MAKE_MODELS.M Makes QSMs of given point clouds. % % Version 1.1.0 % Latest update 9 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Makes QSMs of given point clouds specified by the "dataname" and by the % other inputs. The results are saved into file named "savename". % Notice, the code does not save indivual QSM runs into their own .mat or % .txt files but saves all models into one big .mat file. % % Inputs: % dataname String specifying the .mat-file containing the point % clouds that are used for the QSM reconstruction. % savename String, the name of the file where the QSMs are saved % Nmodels (Optional) Number of models generated for each input % (cloud and input parameters). Default value is 5. % inputs (Optional) The input parameters structure. Can be defined % below as part of this code. Can also be given as a % structure array where each tree gets its own, possibly % uniquely, defined parameters (e.g. optimal parameters) % but each tree has to have same number of parameter values. % % Output: % QSMs Structure array containing all the QSMs generated % --------------------------------------------------------------------- % Changes from version 1.1.0 to 1.1.1, 18 Aug 2020: % 1) Removed the inputs "lcyl" and "FilRad" from the inputs and the % calculations of number of input parameters % Changes from version 1.0.0 to 1.1.0, 03 Oct 2019: % 1) Added try-catch structure where "treeqsm" is called, so that if there % is an error during the reconstruction process of one tree, then the % larger process of making multiple QSMs from multiple tree is not % stopped. % 2) Changed the way the data is loaded. Previously all the data was % loaded into workspace, now only one point cloud is in the workspace. % 3) Corrected a bug where incomplete QSM was saved as complete QSM % 4) Changed where the input-structure for each tree is reconstructed if nargin < 2 disp('Not enough inputs, no models generated!') QSMs = struct([]); return end if nargin == 2 Nmodels = 5; % Number of models per inputs, usually about 5 models is enough end %% Define the parameter values if nargin == 3 || nargin == 2 % The following parameters can be varied and should be optimised % (each can have multiple values): % Patch size of the first uniform-size cover: inputs.PatchDiam1 = [0.08 0.1]; % Minimum patch size of the cover sets in the second cover: inputs.PatchDiam2Min = [0.015 0.025]; % Maximum cover set size in the stem's base in the second cover: inputs.PatchDiam2Max = [0.06 0.08]; % The following parameters can be varied and but usually can be kept as % shown (i.e. as little bigger than PatchDiam parameters): % Ball radius used for the first uniform-size cover generation: inputs.BallRad1 = inputs.PatchDiam1+0.02; % Maximum ball radius used for the second cover generation: inputs.BallRad2 = inputs.PatchDiam2Max+0.01; % The following parameters can be usually kept fixed as shown: inputs.nmin1 = 3; % Minimum number of points in BallRad1-balls, good value is 3 inputs.nmin2 = 1; % Minimum number of points in BallRad2-balls, good value is 1 inputs.OnlyTree = 1; % If "1", then point cloud contains points only from the tree inputs.Tria = 0; % If "1", then triangulation produces inputs.Dist = 1; % If "1", then computes the point-model distances % Different cylinder radius correction options for modifying too large and % too small cylinders: % Traditional TreeQSM choices: % Minimum cylinder radius, used particularly in the taper corrections: inputs.MinCylRad = 0.0025; % Child branch cylinders radii are always smaller than the parent % branche's cylinder radii: inputs.ParentCor = 1; % Use partially linear (stem) and parabola (branches) taper corrections: inputs.TaperCor = 1; % Growth volume correction approach introduced by Jan Hackenberg, % allometry: GrowthVol = a*Radius^b+c % Use growth volume correction: inputs.GrowthVolCor = 0; % fac-parameter of the growth vol. approach, defines upper and lower % boundary: inputs.GrowthVolFac = 2.5; inputs.name = 'test'; inputs.tree = 0; inputs.plot = 0; inputs.savetxt = 0; inputs.savemat = 0; inputs.disp = 0; end % Compute the number of input parameter combinations in = inputs(1); ninputs = prod([length(in.PatchDiam1) length(in.PatchDiam2Min)... length(in.PatchDiam2Max)]); %% Load data matobj = matfile([dataname,'.mat']); names = fieldnames(matobj); i = 1; n = max(size(names)); while i <= n && ~strcmp(names{i,:},'Properties') i = i+1; end I = (1:1:n); I = setdiff(I,i); names = names(I,1); names = sort(names); nt = max(size(names)); % number of trees/point clouds %% make the models QSMs = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},... 'pmdistance',{},'triangulation',{}); % Generate Inputs struct that contains the input parameters for each tree if max(size(inputs)) == 1 for i = 1:nt Inputs(i) = inputs; Inputs(i).name = names{i}; Inputs(i).tree = i; Inputs(i).plot = 0; Inputs(i).savetxt = 0; Inputs(i).savemat = 0; Inputs(i).disp = 0; end else Inputs = inputs; end m = 1; for t = 1:nt % trees disp(['Modelling tree ',num2str(t),'/',num2str(nt),' (',Inputs(t).name,'):']) P = matobj.(Inputs(t).name); j = 1; % model number under generation, make "Nmodels" models per tree inputs = Inputs(t); while j <= Nmodels % generate N models per input k = 1; n0 = 0; inputs.model = j; while k <= 5 % try up to five times to generate non-empty models try QSM = treeqsm(P,inputs); catch QSM = struct('cylinder',{},'branch',{},'treedata',{},... 'rundata',{},'pmdistance',{},'triangulation',{}); QSM(ninputs).treedata = 0; end n = max(size(QSM)); Empty = false(n,1); for b = 1:n if isempty(QSM(b).branch) Empty(b) = true; end end if n < ninputs || any(Empty) n = nnz(~Empty); k = k+1; if n >= n0 qsm = QSM(~Empty); n0 = n; end else % Succesfull models generated QSMs(m:m+n-1) = QSM; m = m+n; k = 10; end end if k == 6 disp('Incomplete run!!') QSMs(m:m+n0-1) = qsm; m = m+n0; end j = j+1; end stri = ['results/',savename]; save(stri,'QSMs') end
github
InverseTampere/TreeQSM-master
select_optimum.m
.m
TreeQSM-master/src/select_optimum.m
41,288
utf_8
4810c22b2697e27fafb380cec479755f
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [TreeData,OptModels,OptInputs,OptQSM] = ... select_optimum(QSMs,Metric,savename) % --------------------------------------------------------------------- % SELECT_OPTIMUM.M Selects optimum models based on point-cylinder model % distances or standard deviations of attributes % % Version 1.4.0 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Works for single or multiple tree cases where the input QSMs contains % multiple models for the same tree with different inputs and multiple runs % with the same inputs. Allows the user to select from 34 different metrics % for the optimization. These include average point-model distances from % all, trunk, branch, 1st-order branch and 2nd-order branch cylinders plus % some combinations where e.g. "mean trunk and mean branch" or "mean trunk % and mean 1st-order branch" point-model distances are added together. % Similarly for the maximum point-model distances and the sums of mean and % the maximum distances. % The difference between "all" and "trunk and branch" is that "all" % is the average of all cylinder distances which usually emphasizes % branch cylinder as there usually much more those, whereas "trunk and branch" % gives equal weight for trunk and branch cylinders. % The other options for metric are based on minimizing the standard deviations % of volumes (total, trunk, branch, trunk+branch which have equal emphasis % between trunk and branches), lengths (trunk, branches) or total number of % branches. Here the idea is that if the variance (standard deviation) of % some attribute between models with the same inputs is small, then it % indicates some kind of robustness which might indicate that the inputs % are close to optimal. % The optimal single model out of the models with the optimal inputs is % selected based on the minimum mean point-model-distance. % % Inputs: % QSMs Contain all the QSMs, possibly from multiple trees % Metric Optional input, Metric to be minimized: % CYLINDER-DISTANCE METRICS: % 'all_mean_dis' = mean distances from (mdf) all cylinders, DEFAULT option % 'trunk_mean_dis' = mdf trunk cylinders, % 'branch_mean_dis' = mdf all branch cylinders, % '1branch_mean_dis' = mdf 1st-order branch cylinders, % '2branch_mean_dis' = mdf 2nd-order branch cylinders, % 'trunk+branch_mean_dis' = mdf trunk + mdf branch cylinders, % 'trunk+1branch_mean_dis' = mdf trunk + mdf 1st-ord branch cyls, % 'trunk+1branch+2branch_mean_dis' = above + mdf 2nd-ord branch cyls % '1branch+2branch_mean_dis' = mdf 1branch cyls + mdf 2branch cyls % 'all_max_dis' = maximum distances from (mdf) all cylinders % 'trunk_max_dis' = mdf trunk cylinders, % 'branch_max_dis' = mdf all branch cylinders, % '1branch_max_dis' = mdf 1st-order branch cylinders, % '2branch_max_dis' = mdf 2nd-order branch cylinders, % 'trunk+branch_max_dis' = mdf trunk + mdf branch cylinders, % 'trunk+1branch_max_dis' = mdf trunk + mdf 1st-ord branch cyls, % 'trunk+1branch+2branch_max_dis' = above + mdf 2nd-ord branch cyls. % '1branch+2branch_max_dis' = mdf 1branch cyls + mdf 2branch cyls % 'all_mean+max_dis' = mean + maximum distances from (m+mdf) all cylinders % 'trunk_mean+max_dis' = (m+mdf) trunk cylinders, % 'branch_mean+max_dis' = (m+mdf) all branch cylinders, % '1branch_mean+max_dis' = (m+mdf) 1st-order branch cylinders, % '2branch_mean+max_dis' = (m+mdf) 2nd-order branch cylinders, % 'trunk+branch_mean+max_dis' = (m+mdf) trunk + (m+mdf) branch cylinders, % 'trunk+1branch_mean+max_dis' = (m+mdf) trunk + (m+mdf) 1branch cyls, % 'trunk+1branch+2branch_mean+max_dis' = above + (m+mdf) 2branch cyls. % '1branch+2branch_mean+max_dis' = (m+mdf) 1branch cyls + (m+mdf) 2branch cyls % STANDARD DEVIATION METRICS: % 'tot_vol_std' = standard deviation of total volume % 'trunk_vol_std' = standard deviation of trunk volume % 'branch_vol_std' = standard deviation of branch volume % 'trunk+branch_vol_std' = standard deviation of trunk plus branch volume % 'tot_are_std' = standard deviation of total area % 'trunk_are_std' = standard deviation of trunk area % 'branch_are_std' = standard deviation of branch area % 'trunk+branch_are_std' = standard deviation of trunk plus branch area % 'trunk_len_std' = standard deviation of trunk length % 'branch_len_std' = standard deviation of branch length % 'branch_num_std' = standard deviation of number of branches % BRANCH-ORDER DISTRIBUTION METRICS: % 'branch_vol_ord3_mean' = mean difference in volume of 1-3 branch orders % 'branch_are_ord3_mean' = mean difference in area of 1-3 branch orders % 'branch_len_ord3_mean' = mean difference in length of 1-3 branch orders % 'branch_num_ord3_mean' = mean difference in number of 1-3 branch orders % 'branch_vol_ord3_max' = max difference in volume of 1-3 branch orders % 'branch_are_ord3_max' = max difference in area of 1-3 branch orders % 'branch_len_ord3_max' = max difference in length of 1-3 branch orders % 'branch_num_ord3_max' = max difference in number of 1-3 branch orders % 'branch_vol_ord6_mean' = mean difference in volume of 1-6 branch orders % 'branch_are_ord6_mean' = mean difference in area of 1-6 branch orders % 'branch_len_ord6_mean' = mean difference in length of 1-6 branch orders % 'branch_num_ord6_mean' = mean difference in number of 1-6 branch orders % 'branch_vol_ord6_max' = max difference in volume of 1-6 branch orders % 'branch_are_ord6_max' = max difference in area of 1-6 branch orders % 'branch_len_ord6_max' = max difference in length of 1-6 branch orders % 'branch_num_ord6_max' = max difference in number of 1-6 branch orders % CYLINDER DISTRIBUTION METRICS: % 'cyl_vol_dia10_mean') = mean diff. in volume of 1-10cm diam cyl classes % 'cyl_are_dia10_mean') = mean diff. in area of 1-10cm diam cyl classes % 'cyl_len_dia10_mean') = mean diff. in length of 1-10cm diam cyl classes % 'cyl_vol_dia10_max') = max diff. in volume of 1-10cm diam cyl classes % 'cyl_are_dia10_max') = max diff. in area of 1-10cm diam cyl classes % 'cyl_len_dia10_max') = max diff. in length of 1-10cm diam cyl classes % 'cyl_vol_dia20_mean') = mean diff. in volume of 1-20cm diam cyl classes % 'cyl_are_dia20_mean') = mean diff. in area of 1-20cm diam cyl classes % 'cyl_len_dia20_mean') = mean diff. in length of 1-20cm diam cyl classes % 'cyl_vol_dia20_max') = max diff. in volume of 1-20cm diam cyl classes % 'cyl_are_dia20_max') = max diff. in area of 1-20cm diam cyl classes % 'cyl_len_dia20_max') = max diff. in length of 1-20cm diam cyl classes % 'cyl_vol_zen_mean') = mean diff. in volume of cyl zenith distribution % 'cyl_are_zen_mean') = mean diff. in area of cyl zenith distribution % 'cyl_len_zen_mean') = mean diff. in length of cyl zenith distribution % 'cyl_vol_zen_max') = max diff. in volume of cyl zenith distribution % 'cyl_are_zen_max') = max diff. in area of cyl zenith distribution % 'cyl_len_zen_max') = max diff. in length of cyl zenith distribution % SURFACE COVERAGE METRICS: % metric to be minimized is 1-mean(surface_coverage) or 1-min(SC) % 'all_mean_surf' = mean surface coverage from (msc) all cylinders % 'trunk_mean_surf' = msc trunk cylinders, % 'branch_mean_surf' = msc all branch cylinders, % '1branch_mean_surf' = msc 1st-order branch cylinders, % '2branch_mean_surf' = msc 2nd-order branch cylinders, % 'trunk+branch_mean_surf' = msc trunk + msc branch cylinders, % 'trunk+1branch_mean_surf' = msc trunk + msc 1st-ord branch cyls, % 'trunk+1branch+2branch_mean_surf' = above + msc 2nd-ord branch cyls % '1branch+2branch_mean_surf' = msc 1branch cyls + msc 2branch cyls % 'all_min_surf' = minimum surface coverage from (msc) all cylinders % 'trunk_min_surf' = msc trunk cylinders, % 'branch_min_surf' = msc all branch cylinders, % '1branch_min_surf' = msc 1st-order branch cylinders, % '2branch_min_surf' = msc 2nd-order branch cylinders, % 'trunk+branch_min_surf' = msc trunk + msc branch cylinders, % 'trunk+1branch_min_surf' = msc trunk + msc 1st-ord branch cyls, % 'trunk+1branch+2branch_min_surf' = above + msc 2nd-ord branch cyls. % '1branch+2branch_min_surf' = msc 1branch cyls + msc 2branch cyls % savename Optional input, name string specifying the name of the saved file % containing the outputs % % Outputs: % TreeData Similar structure array as the "treedata" in QSMs but now each % attribute contains the mean and std computed from the models % with the optimal inputs. Also contains the sensitivities % for the inputs PatchDiam1, PatchDiam2Min, PatchDiam2Max. % Thus for single number attributes (e.g. TotalVolume) there % are five numbers [mean std sensi_PD1 sensi_PD2Min sensi_PD2Max] % OptModels Indexes of the models with the optimal inputs (column 1) and % the index of the optimal single model (column 2) in "QSMs" % for each tree % OptInputs The optimal input parameters for each tree % OptQSMs The single best QSM for each tree, OptQSMs = QSMs(OptModel); % --------------------------------------------------------------------- % Changes from version 1.3.1 to 1.4.0, 2 May 2022: % 1) Added estimation of (relative) sensitivity of the single number % attributes in TreeData for the inputs PatchDiam1, PatchDiam2Min, % PatchDiam2Max. Now TreeData contains also these values as the columns % 3 to 5. % 2) Corrected a small bug in the subfunction "collect_data" (assignment % of values for "CylSurfCov(i,:)"). The bug caused error for QSMs whose % maximum branch order is less than 2. % 3) Bug fix for 3 lines (caused error for some cases and for other cases % the optimal single model was wrongly selected): % [~,T] = min(dist(ind,best)); --> [~,T] = min(Data.CylDist(ind,best)); % Changes from version 1.2.0 to 1.3.0, 4 Aug 2020: % 1) Removed two inputs ("lcyl" and "FilRad") from the inputs to be % optimised. This corresponds to changes in the cylinder fitting. % 2) Added more choices for the optimisation criteria or cost % functions ("metric") that are minimised. There is now 91 metrics and % the new ones include surface coverage based metrics. % Changes from version 1.1.1 to 1.2.0, 4 Feb 2020: % 1) Major change in the structure: subfunctions % 2) Added more choices for the optimisation criteria or cost % functions ("metric") that are minimised. There is now 73 metrics and in % particular the new ones include some area related metrics and branch % and cylinder distribution based metrics. % Changes from version 1.1.0 to 1.1.1, 26 Nov 2019: % 1) Added the "name" of the point cloud from the inputs.name to the output % TreeData as a field. Also now displays the name together with the tree % number. % 2) TreeData contains now correctly fields ("location", "StemTaper", % "VolumeBranchOrder", etc) from the Optimal QSMs. % Changes from version 1.0.0 to 1.1.0, 08 Oct 2019: % 1) Added the posibility to select the optimisation criteria or cost % function ("metric") that is minimised from 34 different options. % Previously only one option was used. The used metric is also included % in "OptInputs" output as one of the fields. % 2) Added OptQSM as one of the outputs %% Select the metric based on the input if nargin > 1 [met,Metric] = select_metric(Metric); else met = 1; Metric = 'all_mean_dis'; end % The metric for selecting the optimal single model from the models with % the optimal inputs is the mean point-model-distance. best = 1; %% Collect data % Find the first non-empty model i = 1; while isempty(QSMs(i).cylinder) i = i+1; end % Determine how many single-number attributes there are in treedata names = fieldnames(QSMs(i).treedata); n = 1; while numel(QSMs(i).treedata.(names{n})) == 1 n = n+1; end n = n-1; Names = names(1:n); L = max(cellfun('length',Names))+1; for i = 1:n name = Names{i}; name(L) = ' '; Names{i} = name; end % Collect data: [treedata,inputs,TreeId,Data] = collect_data(QSMs,names,n); % Trees and their unique IDs TreeIds = unique(TreeId(:,1)); nt = length(TreeIds); % number of trees DataM = zeros(n,nt); DataS = zeros(n,nt); % Standard deviation of tree data for each tree DataM2 = DataM; DataM3 = DataM; DataS2 = DataS; DataS3 = DataS; OptIn = zeros(nt,9); % Optimal input values OptDist = zeros(nt,9); % Smallest metric values % average treedata and inputs for each tree-input-combination: TreeDataAll = zeros(nt,5*5*5,n); Inputs = zeros(nt,5*5*5,3); IndAll = (1:1:size(TreeId,1))'; % Indexes of the optimal single models in QSMs: OptModel = zeros(nt,3); % The indexes of models in QSMs with the optimal inputs (col 1) % and the indexes of the optimal single models (col 2): OptModels = cell(nt,2); NInputs = zeros(nt,1); %% Process each tree separately for tree = 1:nt % Select the models for the tree Models = TreeId(:,1) == TreeIds(tree); %% Determine the input parameter values InputParComb = unique(inputs(Models,:),'rows'); % Input parameter combinations IV = cell(3,1); N = zeros(3,1); for i = 1:3 I = unique(InputParComb(:,i)); IV{i} = I; N(i) = length(I); end %% Determine metric-value for each input % (average over number of models with the same inputs) input = cell(1,N(1)*N(2)*N(3)); distM = zeros(1,N(1)*N(2)*N(3)); % average distances or volume stds b = 0; for d = 1:N(1) % PatchDiam1 J = abs(inputs(:,1)-IV{1}(d)) < 0.0001; for a = 1:N(2) % PatchDiam2Min K = abs(inputs(:,2)-IV{2}(a)) < 0.0001; for i = 1:N(3) % PatchDiam2Max L = abs(inputs(:,3)-IV{3}(i)) < 0.0001; % Select models for the tree with the same inputs: T = Models & J & K & L; b = b+1; input{b} = [d a i]; % Compute the metric value; D = compute_metric_value(met,T,treedata,Data); distM(b) = D; % Collect the data and inputs TreeDataAll(tree,b,:) = mean(treedata(:,T),2); Inputs(tree,b,:) = [IV{1}(d) IV{2}(a) IV{3}(i)]; end end end %% Determine the optimal inputs and models ninputs = prod(N); NInputs(tree) = ninputs; [d,J] = sort(distM); O = input{J(1)}; OptIn(tree,1:3) = [IV{1}(O(1)) IV{2}(O(2)) IV{3}(O(3))]; OptDist(tree,1) = d(1); if ninputs > 1 O = input{J(2)}; OptIn(tree,4:6) = [IV{1}(O(1)) IV{2}(O(2)) IV{3}(O(3))]; OptDist(tree,2) = d(2); if ninputs > 2 O = input{J(3)}; OptIn(tree,7:9) = [IV{1}(O(1)) IV{2}(O(2)) IV{3}(O(3))]; OptDist(tree,3) = d(3); end end %% Mean of tree data for each tree computed from the optimal models: % Select the optimal models for each tree: In the case of multiple models % with same inputs, select the one model with the optimal inputs that % has the minimum metric value. J = abs(inputs(:,1)-OptIn(tree,1)) < 0.0001; K = abs(inputs(:,2)-OptIn(tree,2)) < 0.0001; L = abs(inputs(:,3)-OptIn(tree,3)) < 0.0001; T = Models & J & K & L; ind = IndAll(T); [~,T] = min(Data.CylDist(ind,best)); OptModel(tree,1) = ind(T); OptModels{tree,1} = ind; OptModels{tree,2} = ind(T); DataM(:,tree) = mean(treedata(:,ind),2); DataS(:,tree) = std(treedata(:,ind),[],2); if ninputs > 1 J = abs(inputs(:,1)-OptIn(tree,4)) < 0.0001; K = abs(inputs(:,2)-OptIn(tree,5)) < 0.0001; L = abs(inputs(:,3)-OptIn(tree,6)) < 0.0001; T = Models & J & K & L; ind = IndAll(T); [~,T] = min(Data.CylDist(ind,best)); OptModel(tree,2) = ind(T); DataM2(:,tree) = mean(treedata(:,ind),2); DataS2(:,tree) = std(treedata(:,ind),[],2); if ninputs > 2 J = abs(inputs(:,1)-OptIn(tree,7)) < 0.0001; K = abs(inputs(:,2)-OptIn(tree,8)) < 0.0001; L = abs(inputs(:,3)-OptIn(tree,9)) < 0.0001; T = Models & J & K & L; ind = IndAll(T); [~,T] = min(Data.CylDist(ind,best)); OptModel(tree,3) = ind(T); DataM3(:,tree) = mean(treedata(:,ind),2); DataS3(:,tree) = std(treedata(:,ind),[],2); end end % Decrease the number on non-zero decimals DataM(:,tree) = change_precision(DataM(:,tree)); DataS(:,tree) = change_precision(DataS(:,tree)); if ninputs > 1 DataM2(:,tree) = change_precision(DataM2(:,tree)); DataS2(:,tree) = change_precision(DataS2(:,tree)); if ninputs > 2 DataM3(:,tree) = change_precision(DataM3(:,tree)); DataS3(:,tree) = change_precision(DataS3(:,tree)); end end % Define the output "OptInputs" OptM = IndAll(OptModel(tree,1)); OptInputs(tree) = QSMs(OptM).rundata.inputs; if ninputs > 1 OptM2 = IndAll(OptModel(tree,2)); OI2(tree) = QSMs(OptM2).rundata.inputs; if ninputs > 2 OptM3 = IndAll(OptModel(tree,3)); OI3(tree) = QSMs(OptM3).rundata.inputs; end end end N = max(NInputs); TreeDataAll = TreeDataAll(:,1:N,:); Inputs = Inputs(:,1:N,:); % Compute Coefficient of variation for the data OptModel = IndAll(OptModel(:,1)); OptQSM = QSMs(OptModel); DataCV = DataS./DataM*100; % Coefficient of variation if ninputs > 1 DataCV2 = DataS2./DataM2*100; % Coefficient of variation if ninputs > 2 DataCV3 = DataS3./DataM3*100; % Coefficient of variation end end % Decrease the number on non-zero decimals for j = 1:nt DataCV(:,j) = change_precision(DataCV(:,j)); if ninputs > 1 DataCV2(:,j) = change_precision(DataCV2(:,j)); if ninputs > 2 DataCV3(:,j) = change_precision(DataCV3(:,j)); end end end %% Display some data about optimal models % Display optimal inputs, model and attributes for each tree for t = 1:nt disp('-------------------------------') disp([' Tree: ',num2str(OptInputs(t).tree),', ',OptInputs(t).name]) if NInputs(t) == 1 disp([' Metric: ',Metric]) disp([' Metric value: ',num2str(1000*OptDist(t,1))]) disp([' Optimal inputs: PatchDiam1 = ',... num2str(OptInputs(t).PatchDiam1)]) disp([' PatchDiam2Min = ',... num2str(OptInputs(t).PatchDiam2Min)]) disp([' PatchDiam2Max = ',... num2str(OptInputs(t).PatchDiam2Max)]) disp([' Optimal model: ',num2str(OptModel(t))]) sec = num2str(round(QSMs(OptModel(t)).rundata.time(end))); disp([' Reconstruction time for the optimal model: ',sec,' seconds']) disp(' Attributes (mean, std, CV(%)):') for i = 1:n str = ([' ',Names{i},': ',num2str([... DataM(i,t) DataS(i,t) DataCV(i,t)])]); disp(str) end elseif NInputs(t) == 2 disp(' The best two cases:') disp([' Metric: ',Metric]) disp([' Metric values: ',num2str(OptDist(t,1:2))]) disp([' inputs: PatchDiam1 = ',... num2str([OptInputs(t).PatchDiam1 OI2(t).PatchDiam1])]) disp([' PatchDiam2Min = ',... num2str([OptInputs(t).PatchDiam2Min OI2(t).PatchDiam2Min])]) disp([' PatchDiam2Max = ',... num2str([OptInputs(t).PatchDiam2Max OI2(t).PatchDiam2Max])]) disp([' Optimal model: ',num2str(OptModel(t))]) sec = num2str(round(QSMs(OptModel(t)).rundata.time(end))); disp([' Reconstruction time for the optimal model: ',sec,' seconds']) disp(' Attributes (mean, std, CV(%), second best mean):') for i = 1:n str = ([' ',Names{i},': ',num2str([DataM(i,t) ... DataS(i,t) DataCV(i,t) DataM2(i,t)])]); disp(str) end elseif NInputs(t) > 2 disp(' The best three cases:') disp([' Metric: ',Metric]) disp([' Metric values: ',num2str(OptDist(t,1:3))]) disp([' inputs: PatchDiam1 = ',num2str([... OptInputs(t).PatchDiam1 OI2(t).PatchDiam1 OI3(t).PatchDiam1])]) disp([' PatchDiam2Min = ',num2str([... OptInputs(t).PatchDiam2Min OI2(t).PatchDiam2Min OI3(t).PatchDiam2Min])]) disp([' PatchDiam2Max = ',num2str([... OptInputs(t).PatchDiam2Max OI2(t).PatchDiam2Max OI3(t).PatchDiam2Max])]) disp([' Optimal model: ',num2str(OptModel(t))]) sec = num2str(round(QSMs(OptModel(t)).rundata.time(end))); disp([' Reconstruction time for the optimal model: ',sec,' seconds']) str = [' Attributes (mean, std, CV(%),',... ' second best mean, third best mean, sensitivity):']; disp(str) for i = 1:n sensi = max(abs([DataM(i,t)-DataM2(i,t)... DataM(i,t)-DataM3(i,t)])/DataM(i,t)); sensi2 = 100*sensi; sensi = 100*sensi/DataCV(i,t); sensi2 = change_precision(sensi2); sensi = change_precision(sensi); str = ([' ',Names{i},': ',num2str([DataM(i,t) DataS(i,t) ... DataCV(i,t) DataM2(i,t) DataM3(i,t) sensi sensi2])]); disp(str) end end disp('------') end %% Compute the sensitivity of the tree attributes relative to PatchDiam-parameters Sensi = sensitivity_analysis(TreeDataAll,TreeId,Inputs,OptIn,NInputs); %% Generate TreeData sructure for optimal models clear TreeData TreeData = vertcat(OptQSM(:).treedata); for t = 1:nt for i = 1:n TreeData(t).(names{i}) = [DataM(i,t) DataS(i,t) squeeze(Sensi(t,i,:))']; end TreeData(t).name = OptInputs(t).name; end %% Add the metric for the "OptInputs" for i = 1:nt OptInputs(i).metric = Metric; end %% Save results if nargin == 3 str = ['results/OptimalQSMs_',savename]; save(str,'TreeData','OptModels','OptInputs','OptQSM') str = ['results/tree_data_',savename,'.txt']; fid = fopen(str, 'wt'); fprintf(fid, [repmat('%g\t', 1, size(DataM,2)-1) '%g\n'], DataM.'); fclose(fid); end % End of main function end function [treedata,inputs,TreeId,Data] = collect_data(... QSMs,names,Nattri) Nmod = max(size(QSMs)); % number of models treedata = zeros(Nattri,Nmod); % Collect all tree attributes from all models inputs = zeros(Nmod,3); % collect the inputs from all models % ([PatchDiam1 PatchDiam2Min PatchDiam2Max]) CylDist = zeros(Nmod,10); % collect the distances from all models CylSurfCov = zeros(Nmod,10); % collect the surface coverages from all models s = 6; % maximum branch order OrdDis = zeros(Nmod,4*s); % collect the distributions from all the models r = 20; % maximum cylinder diameter CylDiaDis = zeros(Nmod,3*r); CylZenDis = zeros(Nmod,54); TreeId = zeros(Nmod,2); % collectd the tree and model indexes from all models Keep = true(Nmod,1); % Non-empty models for i = 1:Nmod if ~isempty(QSMs(i).cylinder) % Collect input-parameter values and tree IDs: p = QSMs(i).rundata.inputs; inputs(i,:) = [p.PatchDiam1 p.PatchDiam2Min p.PatchDiam2Max]; TreeId(i,:) = [p.tree p.model]; % Collect cylinder-point distances: mean of all cylinders, % mean of trunk, branch, 1st- and 2nd-order branch cylinders. % And the maximum of the previous: D = QSMs(i).pmdistance; CylDist(i,:) = [D.mean D.TrunkMean D.BranchMean D.Branch1Mean ... D.Branch2Mean D.max D.TrunkMax D.BranchMax D.Branch1Max ... D.Branch2Max]; % Collect surface coverages: mean of all cylinders, % mean of trunk, branch, 1st- and 2nd-order branch cylinders. % And the minimum of the previous: D = QSMs(i).cylinder.SurfCov; T = QSMs(i).cylinder.branch == 1; B1 = QSMs(i).cylinder.BranchOrder == 1; B2 = QSMs(i).cylinder.BranchOrder == 2; if ~any(B1) CylSurfCov(i,:) = [mean(D) mean(D(T)) 0 0 0 ... min(D) min(D(T)) 0 0 0]; elseif ~any(B2) CylSurfCov(i,:) = [mean(D) mean(D(T)) mean(D(~T)) mean(D(B1)) ... 0 min(D) min(D(T)) min(D(~T)) min(D(B1)) 0]; else CylSurfCov(i,:) = [mean(D) mean(D(T)) mean(D(~T)) mean(D(B1)) ... mean(D(B2)) min(D) min(D(T)) min(D(~T)) min(D(B1)) min(D(B2))]; end % Collect branch-order distributions: d = QSMs(i).treedata.VolBranchOrd; nd = length(d); if nd > 0 a = min(nd,s); OrdDis(i,1:a) = d(1:a); OrdDis(i,s+1:s+a) = QSMs(i).treedata.AreBranchOrd(1:a); OrdDis(i,2*s+1:2*s+a) = QSMs(i).treedata.LenBranchOrd(1:a); OrdDis(i,3*s+1:3*s+a) = QSMs(i).treedata.NumBranchOrd(1:a); end % Collect cylinder diameter distributions: d = QSMs(i).treedata.VolCylDia; nd = length(d); if nd > 0 a = min(nd,r); CylDiaDis(i,1:a) = d(1:a); CylDiaDis(i,r+1:r+a) = QSMs(i).treedata.AreCylDia(1:a); CylDiaDis(i,2*r+1:2*r+a) = QSMs(i).treedata.LenCylDia(1:a); end % Collect cylinder zenith direction distributions: d = QSMs(i).treedata.VolCylZen; if ~isempty(d) CylZenDis(i,1:18) = d; CylZenDis(i,19:36) = QSMs(i).treedata.AreCylZen; CylZenDis(i,37:54) = QSMs(i).treedata.LenCylZen; end % Collect the treedata values from each model for j = 1:Nattri treedata(j,i) = QSMs(i).treedata.(names{j}); end else Keep(i) = false; end end treedata = treedata(:,Keep); inputs = inputs(Keep,:); TreeId = TreeId(Keep,:); clear Data Data.CylDist = CylDist(Keep,:); Data.CylSurfCov = CylSurfCov(Keep,:); Data.BranchOrdDis = OrdDis(Keep,:); Data.CylDiaDis = CylDiaDis(Keep,:); Data.CylZenDis = CylZenDis(Keep,:); % End of function end function [met,Metric] = select_metric(Metric) % Mean distance metrics: if strcmp(Metric,'all_mean_dis') met = 1; elseif strcmp(Metric,'trunk_mean_dis') met = 2; elseif strcmp(Metric,'branch_mean_dis') met = 3; elseif strcmp(Metric,'1branch_mean_dis') met = 4; elseif strcmp(Metric,'2branch_mean_dis') met = 5; elseif strcmp(Metric,'trunk+branch_mean_dis') met = 6; elseif strcmp(Metric,'trunk+1branch_mean_dis') met = 7; elseif strcmp(Metric,'trunk+1branch+2branch_mean_dis') met = 8; elseif strcmp(Metric,'1branch+2branch_mean_dis') met = 9; % Maximum distance metrics: elseif strcmp(Metric,'all_max_dis') met = 10; elseif strcmp(Metric,'trunk_max_dis') met = 11; elseif strcmp(Metric,'branch_max_dis') met = 12; elseif strcmp(Metric,'1branch_max_dis') met = 13; elseif strcmp(Metric,'2branch_max_dis') met = 14; elseif strcmp(Metric,'trunk+branch_max_dis') met = 15; elseif strcmp(Metric,'trunk+1branch_max_dis') met = 16; elseif strcmp(Metric,'trunk+1branch+2branch_max_dis') met = 17; elseif strcmp(Metric,'1branch+2branch_max_dis') met = 18; % Mean plus Maximum distance metrics: elseif strcmp(Metric,'all_mean+max_dis') met = 19; elseif strcmp(Metric,'trunk_mean+max_dis') met = 20; elseif strcmp(Metric,'branch_mean+max_dis') met = 21; elseif strcmp(Metric,'1branch_mean+max_dis') met = 22; elseif strcmp(Metric,'2branch_mean+max_dis') met = 23; elseif strcmp(Metric,'trunk+branch_mean+max_dis') met = 24; elseif strcmp(Metric,'trunk+1branch_mean+max_dis') met = 25; elseif strcmp(Metric,'trunk+1branch+2branch_mean+max_dis') met = 26; elseif strcmp(Metric,'1branch+2branch_mean+max_dis') met = 27; % Standard deviation metrics: elseif strcmp(Metric,'tot_vol_std') met = 28; elseif strcmp(Metric,'trunk_vol_std') met = 29; elseif strcmp(Metric,'branch_vol_std') met = 30; elseif strcmp(Metric,'trunk+branch_vol_std') met = 31; elseif strcmp(Metric,'tot_are_std') met = 32; elseif strcmp(Metric,'trunk_are_std') met = 33; elseif strcmp(Metric,'branch_are_std') met = 34; elseif strcmp(Metric,'trunk+branch_are_std') met = 35; elseif strcmp(Metric,'trunk_len_std') met = 36; elseif strcmp(Metric,'trunk+branch_len_std') met = 37; elseif strcmp(Metric,'branch_len_std') met = 38; elseif strcmp(Metric,'branch_num_std') met = 39; % Branch order distribution metrics: elseif strcmp(Metric,'branch_vol_ord3_mean') met = 40; elseif strcmp(Metric,'branch_are_ord3_mean') met = 41; elseif strcmp(Metric,'branch_len_ord3_mean') met = 42; elseif strcmp(Metric,'branch_num_ord3_mean') met = 43; elseif strcmp(Metric,'branch_vol_ord3_max') met = 44; elseif strcmp(Metric,'branch_are_ord3_max') met = 45; elseif strcmp(Metric,'branch_len_ord3_max') met = 46; elseif strcmp(Metric,'branch_num_ord3_max') met = 47; elseif strcmp(Metric,'branch_vol_ord6_mean') met = 48; elseif strcmp(Metric,'branch_are_ord6_mean') met = 49; elseif strcmp(Metric,'branch_len_ord6_mean') met = 50; elseif strcmp(Metric,'branch_num_ord6_mean') met = 51; elseif strcmp(Metric,'branch_vol_ord6_max') met = 52; elseif strcmp(Metric,'branch_are_ord6_max') met = 53; elseif strcmp(Metric,'branch_len_ord6_max') met = 54; elseif strcmp(Metric,'branch_num_ord6_max') met = 55; % Cylinder distribution metrics: elseif strcmp(Metric,'cyl_vol_dia10_mean') met = 56; elseif strcmp(Metric,'cyl_are_dia10_mean') met = 57; elseif strcmp(Metric,'cyl_len_dia10_mean') met = 58; elseif strcmp(Metric,'cyl_vol_dia10_max') met = 59; elseif strcmp(Metric,'cyl_are_dia10_max') met = 60; elseif strcmp(Metric,'cyl_len_dia10_max') met = 61; elseif strcmp(Metric,'cyl_vol_dia20_mean') met = 62; elseif strcmp(Metric,'cyl_are_dia20_mean') met = 63; elseif strcmp(Metric,'cyl_len_dia20_mean') met = 64; elseif strcmp(Metric,'cyl_vol_dia20_max') met = 65; elseif strcmp(Metric,'cyl_are_dia20_max') met = 66; elseif strcmp(Metric,'cyl_len_dia20_max') met = 67; elseif strcmp(Metric,'cyl_vol_zen_mean') met = 68; elseif strcmp(Metric,'cyl_are_zen_mean') met = 69; elseif strcmp(Metric,'cyl_len_zen_mean') met = 70; elseif strcmp(Metric,'cyl_vol_zen_max') met = 71; elseif strcmp(Metric,'cyl_are_zen_max') met = 72; elseif strcmp(Metric,'cyl_len_zen_max') met = 73; % Mean surface coverage metrics: elseif strcmp(Metric,'all_mean_surf') met = 74; elseif strcmp(Metric,'trunk_mean_surf') met = 75; elseif strcmp(Metric,'branch_mean_surf') met = 76; elseif strcmp(Metric,'1branch_mean_surf') met = 77; elseif strcmp(Metric,'2branch_mean_surf') met = 78; elseif strcmp(Metric,'trunk+branch_mean_surf') met = 79; elseif strcmp(Metric,'trunk+1branch_mean_surf') met = 80; elseif strcmp(Metric,'trunk+1branch+2branch_mean_surf') met = 81; elseif strcmp(Metric,'1branch+2branch_mean_surf') met = 82; % Minimum surface coverage metrics: elseif strcmp(Metric,'all_min_surf') met = 83; elseif strcmp(Metric,'trunk_min_surf') met = 84; elseif strcmp(Metric,'branch_min_surf') met = 85; elseif strcmp(Metric,'1branch_min_surf') met = 86; elseif strcmp(Metric,'2branch_min_surf') met = 87; elseif strcmp(Metric,'trunk+branch_min_surf') met = 88; elseif strcmp(Metric,'trunk+1branch_min_surf') met = 89; elseif strcmp(Metric,'trunk+1branch+2branch_min_surf') met = 90; elseif strcmp(Metric,'1branch+2branch_min_surf') met = 91; % Not given in right form, take the default option else met = 1; Metric = 'all_mean_dis'; end % End of function end function D = compute_metric_value(met,T,treedata,Data) if met <= 27 % cylinder distance metrics: D = mean(Data.CylDist(T,:),1); D(6:10) = 0.5*D(6:10); % Half the maximum values end if met < 10 % mean cylinder distance metrics: if met == 1 % all_mean_dis D = D(1); elseif met == 2 % trunk_mean_dis D = D(2); elseif met == 3 % branch_mean_dis D = D(3); elseif met == 4 % 1branch_mean_dis D = D(4); elseif met == 5 % 2branch_mean_dis D = D(5); elseif met == 6 % trunk+branch_mean_dis D = D(2)+D(3); elseif met == 7 % trunk+1branch_mean_dis D = D(2)+D(4); elseif met == 8 % trunk+1branch+2branch_mean_dis D = D(2)+D(4)+D(5); elseif met == 9 % 1branch+2branch_mean_dis D = D(4)+D(5); end elseif met < 19 % maximum cylinder distance metrics: if met == 10 % all_max_dis D = D(6); elseif met == 11 % trunk_max_dis D = D(7); elseif met == 12 % branch_max_dis D = D(8); elseif met == 13 % 1branch_max_dis D = D(9); elseif met == 14 % 2branch_max_dis D = D(10); elseif met == 15 % trunk+branch_max_dis D = D(7)+D(8); elseif met == 16 % trunk+1branch_max_dis D = D(7)+D(9); elseif met == 17 % trunk+1branch+2branch_max_dis D = D(7)+D(9)+D(10); elseif met == 18 % 1branch+2branch_max_dis D = D(9)+D(10); end elseif met < 28 % Mean plus maximum cylinder distance metrics: if met == 19 % all_mean+max_dis D = D(1)+D(6); elseif met == 20 % trunk_mean+max_dis D = D(2)+D(7); elseif met == 21 % branch_mean+max_dis D = D(3)+D(8); elseif met == 22 % 1branch_mean+max_dis D = D(4)+D(9); elseif met == 23 % 2branch_mean+max_dis D = D(5)+D(10); elseif met == 24 % trunk+branch_mean+max_dis D = D(2)+D(3)+D(7)+D(8); elseif met == 25 % trunk+1branch_mean+max_dis D = D(2)+D(4)+D(7)+D(9); elseif met == 26 % trunk+1branch+2branch_mean+max_dis D = D(2)+D(4)+D(5)+D(7)+D(9)+D(10); elseif met == 27 % 1branch+2branch_mean+max_dis D = D(4)+D(5)+D(9)+D(10); end elseif met < 39 % Standard deviation metrics: if met == 28 % tot_vol_std D = std(treedata(1,T)); elseif met == 29 % trunk_vol_std D = std(treedata(2,T)); elseif met == 30 % branch_vol_std D = std(treedata(3,T)); elseif met == 31 % trunk+branch_vol_std D = std(treedata(2,T))+std(treedata(3,T)); elseif met == 32 % tot_are_std D = std(treedata(12,T)); elseif met == 33 % trunk_are_std D = std(treedata(10,T)); elseif met == 34 % branch_are_std D = std(treedata(11,T)); elseif met == 35 % trunk+branch_are_std D = std(treedata(10,T))+std(treedata(11,T)); elseif met == 36 % trunk_len_std D = std(treedata(5,T)); elseif met == 37 % branch_len_std D = std(treedata(6,T)); elseif met == 38 % trunk+branch_len_std D = std(treedata(5,T))+std(treedata(6,T)); elseif met == 39 % branch_num_std D = std(treedata(8,T)); end elseif met < 56 % Branch order metrics: dis = max(Data.BranchOrdDis(T,:),[],1)-min(Data.BranchOrdDis(T,:),[],1); M = mean(Data.BranchOrdDis(T,:),1); I = M > 0; dis(I) = dis(I)./M(I); if met == 40 % branch_vol_ord3_mean D = mean(dis(1:3)); elseif met == 41 % branch_are_ord3_mean D = mean(dis(7:9)); elseif met == 42 % branch_len_ord3_mean D = mean(dis(13:15)); elseif met == 43 % branch_num_ord3_mean D = mean(dis(19:21)); elseif met == 44 % branch_vol_ord3_max D = max(dis(1:3)); elseif met == 45 % branch_are_ord3_max D = max(dis(7:9)); elseif met == 46 % branch_len_ord3_max D = max(dis(13:15)); elseif met == 47 % branch_vol_ord3_max D = max(dis(19:21)); elseif met == 48 % branch_vol_ord6_mean D = mean(dis(1:6)); elseif met == 49 % branch_are_ord6_mean D = mean(dis(7:12)); elseif met == 50 % branch_len_ord6_mean D = mean(dis(13:18)); elseif met == 51 % branch_num_ord6_mean D = mean(dis(19:24)); elseif met == 52 % branch_vol_ord6_max D = max(dis(1:6)); elseif met == 53 % branch_are_ord6_max D = max(dis(7:12)); elseif met == 54 % branch_len_ord6_max D = max(dis(13:18)); elseif met == 55 % branch_vol_ord6_max D = max(dis(19:24)); end elseif met < 68 % Cylinder diameter distribution metrics: dis = max(Data.CylDiaDis(T,:),[],1)-min(Data.CylDiaDis(T,:),[],1); M = mean(Data.CylDiaDis(T,:),1); I = M > 0; dis(I) = dis(I)./M(I); if met == 56 % cyl_vol_dia10_mean D = mean(dis(1:10)); elseif met == 57 % cyl_are_dia10_mean D = mean(dis(21:30)); elseif met == 58 % cyl_len_dia10_mean D = mean(dis(41:50)); elseif met == 59 % cyl_vol_dia10_max D = max(dis(1:10)); elseif met == 60 % cyl_are_dia10_max D = max(dis(21:30)); elseif met == 61 % cyl_len_dia10_max D = max(dis(41:50)); elseif met == 62 % cyl_vol_dia20_mean D = mean(dis(1:20)); elseif met == 63 % cyl_are_dia20_mean D = mean(dis(21:40)); elseif met == 64 % cyl_len_dia20_mean D = mean(dis(41:60)); elseif met == 65 % cyl_vol_dia20_max D = max(dis(1:20)); elseif met == 66 % cyl_are_dia20_max D = max(dis(21:40)); elseif met == 67 % cyl_len_dia20_max D = max(dis(41:60)); end elseif met < 74 % Cylinder zenith distribution metrics: dis = max(Data.CylZenDis(T,:),[],1)-min(Data.CylZenDis(T,:),[],1); M = mean(Data.CylZenDis(T,:),1); I = M > 0; dis(I) = dis(I)./M(I); if met == 68 % cyl_vol_zen_mean D = mean(dis(1:18)); elseif met == 69 % cyl_are_zen_mean D = mean(dis(19:36)); elseif met == 70 % cyl_len_zen_mean D = mean(dis(37:54)); elseif met == 71 % cyl_vol_zen_max D = max(dis(1:18)); elseif met == 72 % cyl_are_zen_max D = max(dis(19:36)); elseif met == 73 % cyl_len_zen_max D = max(dis(37:54)); end elseif met < 92 % Surface coverage metrics: D = 1-mean(Data.CylSurfCov(T,:),1); if met == 74 % all_mean_surf D = D(1); elseif met == 75 % trunk_mean_surf D = D(2); elseif met == 76 % branch_mean_surf D = D(3); elseif met == 77 % 1branch_mean_surf D = D(4); elseif met == 78 % 2branch_mean_surf D = D(5); elseif met == 79 % trunk+branch_mean_surf D = D(2)+D(3); elseif met == 80 % trunk+1branch_mean_surf D = D(2)+D(4); elseif met == 81 % trunk+1branch+2branch_mean_surf D = D(2)+D(4)+D(5); elseif met == 82 % 1branch+2branch_mean_surf D = D(4)+D(5); elseif met == 83 % all_min_surf D = D(6); elseif met == 84 % trunk_min_surf D = D(7); elseif met == 85 % branch_min_surf D = D(8); elseif met == 86 % 1branch_min_surf D = D(9); elseif met == 87 % 2branch_min_surf D = D(10); elseif met == 88 % trunk+branch_min_surf D = D(6)+D(7); elseif met == 89 % trunk+1branch_min_surf D = D(6)+D(8); elseif met == 90 % trunk+1branch+2branch_min_surf D = D(6)+D(9)+D(10); elseif met == 91 % 1branch+2branch_min_surf D = D(9)+D(10); end end % End of function end function Sensi = sensitivity_analysis(TreeDataAll,TreeId,Inputs,OptIn,NInputs) % Computes the sensitivity of tree attributes (e.g. total volume) to the % changes of input parameter, the PatchDiam parameters, values. The % sensitivity is normalized, i.e. the relative change of attribute value % (= max change in attribute value divided by the value with the optimal % inputs) is divided by the relative change of input parameter value. The % sensitivity is also expressed as percentage, i.e. multiplied by 100. The % sensitivity is computed relative PatchDiam1, PatchDiam2Min, and % PatchDiam2Max. The sensitivity is computed only from the attributes with % the input parameter values the closest to the optimal value. This way we % get the local sensitivity in the neighborhood of the optimal input. % % Output: % Sensi 3D-array (#trees,#attributes,#inputs) TreeIds = unique(TreeId(:,1)); % Unique tree IDs nt = length(TreeIds); % number of trees A = [2 3; 1 3; 1 2]; % Keep other two inputs constant and let one varie Sensi = zeros(nt,size(TreeDataAll,3),3); % initialization of the output for t = 1:nt % trees if NInputs(t) > 1 D = squeeze(TreeDataAll(t,1:NInputs(t),:))'; % Select the attributes for the tree In = squeeze(Inputs(t,1:NInputs(t),:)); % Select the inputs for the tree n = size(In,1); % number of different input-combinations I = all(In == OptIn(t,1:3),2); % Which data are with the optimal inputs ind = (1:1:n)'; I = ind(I); for i = 1:3 % inputs if length(unique(In(:,i))) > 1 dI = abs(max(In(:,i),[],2)-OptIn(t,i)); dImin = min(dI(dI > 0)); % the minimum nonzero absolute change in inputs dI = dImin/OptIn(t,i); % relative change in the attributes K1 = abs(max(In(:,i),[],2)-min(OptIn(t,i),[],2)) < dImin+0.0001; K = K1 & abs(max(In(:,i),[],2)-min(OptIn(t,i),[],2)) > 0.0001; K = ind(K); % the inputs the closest to the optimal input J = all(In(K,A(i,:)) == OptIn(t,A(i,:)),2); J = K(J); % input i the closest to the optimal and the other two equal the optimal dD = max(abs(D(:,J)-D(:,I)),[],2); dD = dD./D(:,I); % relative change in the input d = dD/dI*100; % relative sensitivity as a percentage Sensi(t,:,i) = round(100*d)/100; end end end end % End of function end
github
InverseTampere/TreeQSM-master
estimate_precision.m
.m
TreeQSM-master/src/estimate_precision.m
5,602
utf_8
7781426d9cbcdfb71f74a079141e9b6b
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [TreeData,OptQSMs,OptQSM] = ... estimate_precision(QSMs,NewQSMs,TreeData,OptModels,savename) % --------------------------------------------------------------------- % ESTIMATE_PRECISION.M Combines additional QSMs with optimal inputs % with previously generated QSMs to estimate the % precision (standard deviation) better. % % Version 1.1.0 % Latest update 10 May 2022 % % Copyright (C) 2016-2022 Pasi Raumonen % --------------------------------------------------------------------- % Uses models with the same inputs to estimate the precision (standard % deviation) of the results. Has two sets of models as its inputs: % 1) QSMs can contain models with many different input parameters for each tree % and OptModels contain the indexes of the models that are used here ("optimal % models"); 2) NewQSMs contains only models with the optimal inputs. % % Inputs: % QSMs Contain all the models, possibly from multiple trees % NewQSMs Contains the additional models with optimal inputs, for all trees % TreeData Similar structure array as the "treedata" in QSMs but now each % single-number attribute contains the mean and std computed % from the models with the optimal inputs, and the % sensitivities for PatchDiam-parameters % OptModels Indexes of the optimal models for each tree in "QSMs" % savename Optional input, name string specifying the name of the saved % file containing the outputs % Outputs: % TreeData Updated with new mean and std computed from all the QSMs % with the optimal inputs % OptQSMs Contains all the models with the optimal inputs, for all trees % OptQSM The best model (minimum point-model distance) among the models % with the optimal inputs, for all trees % --------------------------------------------------------------------- % Changes from version 1.0.2 to 1.1.0, 10 May 2022: % 1) Added "TreeData", the output of "select_optimum", as an input, and now % it is updated % Changes from version 1.0.1 to 1.0.2, 26 Nov 2019: % 1) Added the "name" of the point cloud from the inputs.name to the output % TreeData as a field. Also now displays the name together with the tree % number. % Changes from version 1.0.0 to 1.0.1, 08 Oct 2019: % 1) Small change for how the output "TreeData" is initialised %% Reconstruct the outputs OptQSMs = QSMs(vertcat(OptModels{:,1})); % Optimal models from the optimization process OptQSMs = [OptQSMs NewQSMs]; % Combine all the optimal QSMs m = max(size(OptQSMs)); % number of models IndAll = (1:1:m)'; % Find the first non-empty model i = 1; while isempty(OptQSMs(i).cylinder) i = i+1; end % Determine how many single-number attributes there are in treedata names = fieldnames(OptQSMs(i).treedata); n = 1; while numel(OptQSMs(i).treedata.(names{n})) == 1 n = n+1; end n = n-1; treedata = zeros(n,m); % Collect all single-number tree attributes from all models TreeId = zeros(m,1); % Collect tree and model indexes from all models Dist = zeros(m,1); % Collect the distances Keep = true(m,1); % Non-empty models for i = 1:m if ~isempty(OptQSMs(i).cylinder) for j = 1:n treedata(j,i) = OptQSMs(i).treedata.(names{j}); end TreeId(i) = OptQSMs(i).rundata.inputs.tree; Dist(i) = OptQSMs(i).pmdistance.mean; else Keep(i) = false; end end treedata = treedata(:,Keep); TreeId = TreeId(Keep,:); Dist = Dist(Keep); IndAll = IndAll(Keep); TreeIds = unique(TreeId); nt = length(TreeIds); % number of trees % Compute the means and standard deviations OptModel = zeros(nt,1); DataM = zeros(n,nt); DataS = zeros(n,nt); for t = 1:nt I = TreeId == TreeIds(t); ind = IndAll(I); dist = vertcat(Dist(ind)); [~,J] = min(dist); OptModel(t) = ind(J); DataM(:,t) = mean(treedata(:,ind),2); DataS(:,t) = std(treedata(:,ind),[],2); end OptQSM = OptQSMs(OptModel); DataCV = DataS./DataM*100; %% Display some data about optimal models % Decrease the number of non-zero decimals for j = 1:nt DataM(:,j) = change_precision(DataM(:,j)); DataS(:,j) = change_precision(DataS(:,j)); DataCV(:,j) = change_precision(DataCV(:,j)); end % Display optimal inputs, model and attributes for each tree for t = 1:nt disp([' Tree: ',num2str(t),', ',OptQSM(t).rundata.inputs.name]) disp(' Attributes (mean, std, CV(%)):') for i = 1:n str = ([' ',names{i},': ',num2str([DataM(i,t) DataS(i,t) DataCV(i,t)])]); disp(str) end disp('------') end %% Generate TreeData structure for optimal models %TreeData = vertcat(OptQSM(:).treedata); for t = 1:nt for i = 1:n TreeData(t).(names{i})(1:2) = [DataM(i,t) DataS(i,t)]; end TreeData(t).name = OptQSM(t).rundata.inputs.name; end %% Save results if nargin == 5 str = ['results/OptimalQSMs_',savename]; save(str,'TreeData','OptQSMs','OptQSM') end
github
InverseTampere/TreeQSM-master
treeqsm.m
.m
TreeQSM-master/src/treeqsm.m
19,257
utf_8
2fdd2b10f8257521a3ebf4f33ec31125
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function QSM = treeqsm(P,inputs) % --------------------------------------------------------------------- % TREEQSM.M Reconstructs quantitative structure tree models from point % clouds containing a tree. % % Version 2.4.1 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % INPUTS: % % P (Filtered) point cloud, (m_points x 3)-matrix, the rows % give the coordinates of the points. % % inputs Structure field defining reconstruction parameters. % Created with the "create_input.m" script. Contains % the following main fields: % PatchDiam1 Patch size of the first uniform-size cover % % PatchDiam2Min Minimum patch size of the cover sets in the second cover % % PatchDiam2Max Maximum cover set size in the stem's base in the % second cover % % BallRad1 Ball size used for the first cover generation % % BallRad2 Maximum ball radius used for the second cover generation % % nmin1 Minimum number of points in BallRad1-balls, % default value is 3. % % nmin2 Minimum number of points in BallRad2-balls, % default value is 1. % % OnlyTree If "1", the point cloud contains only points from the % tree and the trunk's base is defined as the lowest % part of the point cloud. Default value is "1". % % Tria If "1", tries to make triangulation for the stem up % to first main branch. Default value is "0". % % Dist If "1", compute the point-model distances. % Default value is "1". % % MinCylRad Minimum cylinder radius, used particularly in the % taper corrections % % ParentCor If "1", child branch cylinders radii are always % smaller than the parent branche's cylinder radii % % TaperCor If "1", use partially linear (stem) and parabola % (branches) taper corrections % % GrowthVolCor If "1", use growth volume correction introduced % by Jan Hackenberg % % GrowthVolFac fac-parameter of the growth volume approach, % defines upper and lower bound % % name Name string for saving output files and name for the % model in the output object % % tree Numerical id/index given to the tree % % model Model number of the tree, e.g. with the same inputs % % savemat If "1", saves the output struct QSM as a matlab-file % into \result folder % % savetxt If "1", saves the models in .txt-files into % \result folder % % plot Defines what is plotted during the reconstruction: % 2 = same as below plus distributions % 1 = plots the segmented point cloud and QSMs % 0 = plots nothing % % disp Defines what is displayed during the reconstruction: % 2 = same as below plus times and tree attributes; % 1 = display name, parameters and fit metrics; % 0 = display only the name % --------------------------------------------------------------------- % OUTPUT: % % QSM Structure array with the following fields: % cylinder Cylinder data % branch Branch data % treedata Tree attributes % rundata Information about the modelling run % pmdistances Point-to-model distance statistics % triangulation Triangulation of the stem (if inputs.Tria = 1) % --------------------------------------------------------------------- % cylinder (structure-array) contains the following fields: % radius % length % start xyz-coordinates of the starting point % axis xyz-component of the cylinder axis % parent index (in this file) of the parent cylinder % extension index (in this file) of the extension cylinder % added is cylinder added after normal cylinder fitting (= 1 if added) % UnmodRadius unmodified radius of the cylinder % branch branch (index in the branch structure array) of the cylinder % BranchOrder branch order of the branch the cylinder belongs % PositionInBranch running number of the cylinder in the branch it belongs % % branch (structure-array) contains the following fields: % order branch order (0 for trunk, 1 for branches originating from % the trunk, etc.) % parent index (in this file) of the parent branch % volume volume (L) of the branch (sum of the volumes of the cylinders % forming the branch) % length length (m) of the branch (sum of the lengths of the cylinders) % angle branching angle (deg) (angle between the branch and its parent % at the branching point) % height height (m) of the base of the branch % azimuth azimuth (deg) of the branch at the base % diameter diameter (m) of the branch at the base % % treedata (structure-array) contains the following fields: % TotalVolume % TrunkVolume % BranchVolume % TreeHeight % TrunkLength % BranchLength % NumberBranches Total number of branches % MaxBranchOrder % TotalArea % DBHqsm From the cylinder of the QSM at the right heigth % DBHcyl From the cylinder fitted to the section 1.1-1.5m % location (x,y,z)-coordinates of the base of the tree % StemTaper Stem taper function/curve from the QSM % VolumeCylDiam Distribution of the total volume in diameter classes % LengthCylDiam Distribution of the total length in diameter classes % VolumeBranchOrder Branch volume per branching order % LengthBranchOrder Branch length per branching order % NumberBranchOrder Number of branches per branching order % treedata from mixed model (cylinders and triangulation) contains also % the following fields: % DBHtri Computed from triangulation model % TriaTrunkVolume Triangulated trunk volume (up to first branch) % MixTrunkVolume Mixed trunk volume, bottom (triang.) + top (cylinders) % MixTotalVolume Mixed total volume, mixed trunk volume + branch volume % TriaTrunkLength Triangulated trunk length % % pmdistances (structure-array) contains the following fields (and others): % CylDists Average point-model distance for each cylinder % median median of CylDist for all, stem, 1branch, 2branch cylinder % mean mean of CylDist for all, stem, 1branch, 2branch cylinder % max max of CylDist for all, stem, 1branch, 2branch cylinder % std standard dev. of CylDist for all, stem, 1branch, 2branch cylinder % % rundata (structure-array) contains the following fields: % inputs The input parameters in a structure-array % time Computation times for each step % date Starting and stopping dates (year,month,day,hour,minute,second) % of the computation % % triangulation (structure-array) contains the following fields: % vert Vertices (xyz-coordinates) of the triangulation % facet Facet information % fvd Color information for plotting the model % volume Volume enclosed by the triangulation % bottom Z-coordinate of the bottom plane of the triangulation % top Z-coordinate of the top plane of the triangulation % triah Height of the triangles % triah Width of the triangles % cylind Cylinder index in the stem where the triangulation stops % --------------------------------------------------------------------- % Changes from version 2.4.0 to 2.4.1, 2 May 2022: % Minor update. New filtering options, new code ("define_input") for % selecting automatically PatchDiam and BallRad parameter values for % the optimization process, added sensitivity estimates of the results, % new smoother plotting of QSMs, corrected some bugs, rewrote some % functions (e.g. "branches"). % Particular changes in treeqsm.m file: % 1) Deleted the remove of the field "ChildCyls" and "CylsInSegment". % Changes from version 2.3.2 to 2.4.0, 17 Aug 2020: % First major update. Cylinder fitting process and the taper correction % has changed. The fitting is adaptive and no more “lcyl” and “FilRad” % parameters. Treedata has many new outputs: Branch and cylinder % distributions; surface areas; crown dimensions. More robust triangulation % of stem. Branch, cylinder and triangulation structures have new fields. % More optimisation metrics, more plots of the results and more plotting % functions. % Particular changes in treeqsm.m file: % 1) Removed the for-loops for lcyl and FilRad. % 2) Changes what is displayed about the quality of QSMs % (point-model-distances and surface coverage) during reconstruction % 3) Added version number to rundata % 4) Added remove of the field "ChildCyls" and "CylsInSegment" of "cylinder" % from "branches" to "treeqsm". % Changes from version 2.3.1 to 2.3.2, 2 Dec 2019: % Small changes in the subfunction to allow trees without branches % Changes from version 2.3.0 to 2.3.1, 8 Oct 2019: % 1) Some changes in the subfunctions, particularly in "cylinders" and % "tree_sets" % 2) Changed how "treeqsm" displays things during the running of the % function %% Code starts --> Time = zeros(11,1); % Save computation times for modelling steps Date = zeros(2,6); % Starting and stopping dates of the computation Date(1,:) = clock; % Names of the steps to display name = ['Cover sets '; 'Tree sets '; 'Initial segments'; 'Final segments '; 'Cylinders '; 'Branch & data '; 'Distances ']; if inputs.disp > 0 disp('---------------') disp([' ',inputs.name,', Tree = ',num2str(inputs.tree),... ', Model = ',num2str(inputs.model)]) end % Input parameters PatchDiam1 = inputs.PatchDiam1; PatchDiam2Min = inputs.PatchDiam2Min; PatchDiam2Max = inputs.PatchDiam2Max; BallRad1 = inputs.BallRad1; BallRad2 = inputs.BallRad2; nd = length(PatchDiam1); ni = length(PatchDiam2Min); na = length(PatchDiam2Max); if inputs.disp == 2 % Display parameter values disp([' PatchDiam1 = ',num2str(PatchDiam1)]) disp([' BallRad1 = ',num2str(BallRad1)]) disp([' PatchDiam2Min = ',num2str(PatchDiam2Min)]) disp([' PatchDiam2Max = ',num2str(PatchDiam2Max)]) disp([' BallRad2 = ',num2str(BallRad2)]) disp([' Tria = ',num2str(inputs.Tria),... ', OnlyTree = ',num2str(inputs.OnlyTree)]) disp('Progress:') end %% Make the point cloud into proper form % only 3-dimensional data if size(P,2) > 3 P = P(:,1:3); end % Only double precision data if ~isa(P,'double') P = double(P); end %% Initialize the output file QSM = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},... 'pmdistance',{},'triangulation',{}); %% Reconstruct QSMs nmodel = 0; for h = 1:nd tic Inputs = inputs; Inputs.PatchDiam1 = PatchDiam1(h); Inputs.BallRad1 = BallRad1(h); if nd > 1 && inputs.disp >= 1 disp(' -----------------') disp([' PatchDiam1 = ',num2str(PatchDiam1(h))]); disp(' -----------------') end %% Generate cover sets cover1 = cover_sets(P,Inputs); Time(1) = toc; if inputs.disp == 2 display_time(Time(1),Time(1),name(1,:),1) end %% Determine tree sets and update neighbors [cover1,Base,Forb] = tree_sets(P,cover1,Inputs); Time(2) = toc-Time(1); if inputs.disp == 2 display_time(Time(2),sum(Time(1:2)),name(2,:),1) end %% Determine initial segments segment1 = segments(cover1,Base,Forb); Time(3) = toc-sum(Time(1:2)); if inputs.disp == 2 display_time(Time(3),sum(Time(1:3)),name(3,:),1) end %% Correct segments % Don't remove small segments and add the modified base to the segment segment1 = correct_segments(P,cover1,segment1,Inputs,0,1,1); Time(4) = toc-sum(Time(1:3)); if inputs.disp == 2 display_time(Time(4),sum(Time(1:4)),name(4,:),1) end for i = 1:na % Modify inputs Inputs.PatchDiam2Max = PatchDiam2Max(i); Inputs.BallRad2 = BallRad2(i); if na > 1 && inputs.disp >= 1 disp(' -----------------') disp([' PatchDiam2Max = ',num2str(PatchDiam2Max(i))]); disp(' -----------------') end for j = 1:ni tic % Modify inputs Inputs.PatchDiam2Min = PatchDiam2Min(j); if ni > 1 && inputs.disp >= 1 disp(' -----------------') disp([' PatchDiam2Min = ',num2str(PatchDiam2Min(j))]); disp(' -----------------') end %% Generate new cover sets % Determine relative size of new cover sets and use only tree points RS = relative_size(P,cover1,segment1); % Generate new cover cover2 = cover_sets(P,Inputs,RS); Time(5) = toc; if inputs.disp == 2 display_time(Time(5),sum(Time(1:5)),name(1,:),1) end %% Determine tree sets and update neighbors [cover2,Base,Forb] = tree_sets(P,cover2,Inputs,segment1); Time(6) = toc-Time(5); if inputs.disp == 2 display_time(Time(6),sum(Time(1:6)),name(2,:),1) end %% Determine segments segment2 = segments(cover2,Base,Forb); Time(7) = toc-sum(Time(5:6)); if inputs.disp == 2 display_time(Time(7),sum(Time(1:7)),name(3,:),1) end %% Correct segments % Remove small segments and the extended bases. segment2 = correct_segments(P,cover2,segment2,Inputs,1,1,0); Time(8) = toc-sum(Time(5:7)); if inputs.disp == 2 display_time(Time(8),sum(Time(1:8)),name(4,:),1) end %% Define cylinders cylinder = cylinders(P,cover2,segment2,Inputs); Time(9) = toc; if inputs.disp == 2 display_time(Time(9),sum(Time(1:9)),name(5,:),1) end if ~isempty(cylinder.radius) %% Determine the branches branch = branches(cylinder); %% Compute (and display) model attributes T = segment2.segments{1}; T = vertcat(T{:}); T = vertcat(cover2.ball{T}); trunk = P(T,:); % point cloud of the trunk % Compute attributes and distibutions from the cylinder model % and possibly some from a triangulation [treedata,triangulation] = tree_data(cylinder,branch,trunk,inputs); Time(10) = toc-Time(9); if inputs.disp == 2 display_time(Time(10),sum(Time(1:10)),name(6,:),1) end %% Compute point model distances if inputs.Dist pmdis = point_model_distance(P,cylinder); % Display the mean point-model distances and surface coverages % for stem, branch, 1branc and 2branch cylinders if inputs.disp >= 1 D = [pmdis.TrunkMean pmdis.BranchMean ... pmdis.Branch1Mean pmdis.Branch2Mean]; D = round(10000*D)/10; T = cylinder.branch == 1; B1 = cylinder.BranchOrder == 1; B2 = cylinder.BranchOrder == 2; SC = 100*cylinder.SurfCov; S = [mean(SC(T)) mean(SC(~T)) mean(SC(B1)) mean(SC(B2))]; S = round(10*S)/10; disp(' ----------') str = [' PatchDiam1 = ',num2str(PatchDiam1(h)), ... ', PatchDiam2Max = ',num2str(PatchDiam2Max(i)), ... ', PatchDiam2Min = ',num2str(PatchDiam2Min(j))]; disp(str) str = [' Distances and surface coverages for ',... 'trunk, branch, 1branch, 2branch:']; disp(str) str = [' Average cylinder-point distance: '... num2str(D(1)),' ',num2str(D(2)),' ',... num2str(D(3)),' ',num2str(D(4)),' mm']; disp(str) str = [' Average surface coverage: '... num2str(S(1)),' ',num2str(S(2)),' ',... num2str(S(3)),' ',num2str(S(4)),' %']; disp(str) disp(' ----------') end Time(11) = toc-sum(Time(9:10)); if inputs.disp == 2 display_time(Time(11),sum(Time(1:11)),name(7,:),1) end end %% Reconstruct the output "QSM" Date(2,:) = clock; Time(12) = sum(Time(1:11)); clear qsm qsm = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},... 'pmdistance',{},'triangulation',{}); qsm(1).cylinder = cylinder; qsm(1).branch = branch; qsm(1).treedata = treedata; qsm(1).rundata.inputs = Inputs; qsm(1).rundata.time = single(Time); qsm(1).rundata.date = single(Date); qsm(1).rundata.version = '2.4.1'; if inputs.Dist qsm(1).pmdistance = pmdis; end if inputs.Tria qsm(1).triangulation = triangulation; end nmodel = nmodel+1; QSM(nmodel) = qsm; %% Save the output into results-folder % matlab-format (.mat) if inputs.savemat str = [inputs.name,'_t',num2str(inputs.tree),'_m',... num2str(inputs.model)]; save(['results/QSM_',str],'QSM') end % text-format (.txt) if inputs.savetxt if nd > 1 || na > 1 || ni > 1 str = [inputs.name,'_t',num2str(inputs.tree),'_m',... num2str(inputs.model)]; if nd > 1 str = [str,'_D',num2str(PatchDiam1(h))]; end if na > 1 str = [str,'_DA',num2str(PatchDiam2Max(i))]; end if ni > 1 str = [str,'_DI',num2str(PatchDiam2Min(j))]; end else str = [inputs.name,'_t',num2str(inputs.tree),'_m',... num2str(inputs.model)]; end save_model_text(qsm,str) end %% Plot models and segmentations if inputs.plot >= 1 if inputs.Tria plot_models_segmentations(P,cover2,segment2,cylinder,trunk,... triangulation) else plot_models_segmentations(P,cover2,segment2,cylinder) end if nd > 1 || na > 1 || ni > 1 pause end end end end end end
github
InverseTampere/TreeQSM-master
plot_models_segmentations.m
.m
TreeQSM-master/src/plotting/plot_models_segmentations.m
3,161
utf_8
5a2123902cb06456971999fd9aee3156
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function plot_models_segmentations(P,cover,segment,cylinder,trunk,triangulation) % --------------------------------------------------------------------- % PLOT_MODELS_SEGMENTATION.M Plots the segmented point clouds and % cylinder/triangulation models % % Version 1.1.0 % Latest update 13 July 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % Inputs: % P Point cloud % cover cover-structure array % segment segment-structure array % cylinder cylinder-structure array % trunk point cloud of the trunk % triangulation triangulation-structure array % Changes from version 1.0.0 to 1.1.0, 13 July 2020: % 1) plots now figure 1 and 2 with two subplots; in the first the colors % are based on branching order and in the second they are based on % branch %% figure 1: branch-segmented point cloud % colors denote the branching order and branches figure(1) subplot(1,2,1) plot_branch_segmentation(P,cover,segment,'order') subplot(1,2,2) plot_branch_segmentation(P,cover,segment,'branch') %% figure 2: cylinder model % colors denote the branching order and branches Sta = cylinder.start; P = P-Sta(1,:); if nargin > 5 trunk = trunk-Sta(1,:); Vert = double(triangulation.vert); Vert = Vert-Sta(1,:); end Sta = Sta-Sta(1,:); cylinder.start = Sta; figure(2) subplot(1,2,1) plot_cylinder_model(cylinder,'order',2,10) subplot(1,2,2) plot_cylinder_model(cylinder,'branch',2,10) %% figure 3, segmented point cloud and cylinder model plot_branch_segmentation(P,cover,segment,'order',3,1) hold on plot_cylinder_model(cylinder,'order',3,10,0.7) hold off if nargin > 4 %% figure 4, triangulation model (bottom) and cylinder model (top) % of the stem Facets = double(triangulation.facet); CylInd = triangulation.cylind; fvd = triangulation.fvd; if max(size(Vert)) > 5 Bran = cylinder.branch; nc = size(Bran,1); ind = (1:1:nc)'; C = ind(Bran == 1); n = size(trunk,1); I = logical(round(0.55*rand(n,1))); figure(4) point_cloud_plotting(trunk(I,:),4,3) patch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,... 'FaceColor','flat') alpha(1) hold on plot_cylinder_model(cylinder,'order',4,20,1,(CylInd:C(end))) axis equal hold off else disp('No triangulation model generated!') end end
github
InverseTampere/TreeQSM-master
cubical_partition.m
.m
TreeQSM-master/src/tools/cubical_partition.m
4,085
utf_8
5c56478a02bcbdc77d66b72d7288c317
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [Partition,CubeCoord,Info,Cubes] = cubical_partition(P,EL,NE) % --------------------------------------------------------------------- % CUBICAL_PARTITION.M Partitions the point cloud into cubes. % % Version 1.1.0 % Latest update 6 Oct 2021 % % Copyright (C) 2015-2021 Pasi Raumonen % --------------------------------------------------------------------- % Inputs: % P Point cloud, (n_points x 3)-matrix % EL Length of the cube edges % NE Number of empty edge layers % % Outputs: % Partition Point cloud partitioned into cubical cells, % (nx x ny x nz)-cell, where nx,ny,nz are the number % of cubes in x,y,z-directions, respectively. If "Cubes" % is outputed, then "Partition" is (n x 1)-cell, where each % cell corresponds to a nonempty cube. % % CC (n_points x 3)-matrix whose rows are the cube coordinates % of each point: x,y,z-coordinates % Info The minimum coordinate values and number of cubes in each % coordinate direction % Cubes (Optional) (nx x ny x nz)-matrix (array), each nonzero % element indicates that its cube is nonempty and the % number indicates which cell in "Partition" contains the % points of the cube. % --------------------------------------------------------------------- % Changes from version 1.0.0 to 1.1.0, 6 Oct 2021: % 1) Changed the determinationa EL and NE so that the while loop don't % continue endlessly in some cases if nargin == 2 NE = 3; end % The vertices of the big cube containing P Min = double(min(P)); Max = double(max(P)); % Number of cubes with edge length "EdgeLength" in the sides % of the big cube N = double(ceil((Max-Min)/EL)+2*NE+1); t = 0; while t < 10 && 8*N(1)*N(2)*N(3) > 4e9 t = t+1; EL = 1.1*EL; N = double(ceil((Max-Min)/EL)+2*NE+1); end if 8*N(1)*N(2)*N(3) > 4e9 NE = 3; N = double(ceil((Max-Min)/EL)+2*NE+1); end Info = [Min N EL NE]; % Calculates the cube-coordinates of the points CubeCoord = floor([P(:,1)-Min(1) P(:,2)-Min(2) P(:,3)-Min(3)]/EL)+NE+1; % Sorts the points according a lexicographical order LexOrd = [CubeCoord(:,1) CubeCoord(:,2)-1 CubeCoord(:,3)-1]*[1 N(1) N(1)*N(2)]'; CubeCoord = uint16(CubeCoord); [LexOrd,SortOrd] = sort(LexOrd); SortOrd = uint32(SortOrd); LexOrd = uint32(LexOrd); if nargout <= 3 % Define "Partition" Partition = cell(N(1),N(2),N(3)); np = size(P,1); % number of points p = 1; % The index of the point under comparison while p <= np t = 1; while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end q = SortOrd(p); Partition{CubeCoord(q,1),CubeCoord(q,2),CubeCoord(q,3)} = SortOrd(p:p+t-1); p = p+t; end else nc = size(unique(LexOrd),1); % Define "Partition" Cubes = zeros(N(1),N(2),N(3),'uint32'); Partition = cell(nc,1); np = size(P,1); % number of points p = 1; % The index of the point under comparison c = 0; while p <= np t = 1; while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end q = SortOrd(p); c = c+1; Partition{c,1} = SortOrd(p:p+t-1); Cubes(CubeCoord(q,1),CubeCoord(q,2),CubeCoord(q,3)) = c; p = p+t; end end
github
InverseTampere/TreeQSM-master
connected_components.m
.m
TreeQSM-master/src/tools/connected_components.m
5,720
utf_8
533338e9122eb5441ad9d27f943075fc
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [Components,CompSize] = connected_components(Nei,Sub,MinSize,Fal) % --------------------------------------------------------------------- % CONNECTED_COMPONENTS.M Determines the connected components of cover % sets using their neighbour-relation % % Version 1.1 % Latest update 16 Aug 2017 % % Copyright (C) 2013-2017 Pasi Raumonen % --------------------------------------------------------------------- % Determines connected components of the subset of cover sets defined % by "Sub" such that each component has at least "MinSize" % number of cover sets. % % Inputs: % Nei Neighboring cover sets of each cover set, (n_sets x 1)-cell % Sub Subset whose components are determined, % length(Sub) < 2 means no subset and thus the whole point cloud % "Sub" may be also a vector of cover set indexes in the subset % or a logical (n_sets)-vector, where n_sets is the number of % all cover sets % MinSize Minimum number of cover sets in an acceptable component % Fal Logical false vector for the cover sets % % Outputs: % Components Connected components, (n_comp x 1)-cell % CompSize Number of sets in the components, (n_comp x 1)-vector if length(Sub) <= 3 && ~islogical(Sub) && Sub(1) > 0 % Very small subset, i.e. at most 3 cover sets n = length(Sub); if n == 1 Components = cell(1,1); Components{1} = uint32(Sub); CompSize = 1; elseif n == 2 I = Nei{Sub(1)} == Sub(2); if any(I) Components = cell(1,1); Components{1} = uint32((Sub)); CompSize = 1; else Components = cell(2,1); Components{1} = uint32(Sub(1)); Components{2} = uint32(Sub(2)); CompSize = [1 1]; end elseif n == 3 I = Nei{Sub(1)} == Sub(2); J = Nei{Sub(1)} == Sub(3); K = Nei{Sub(2)} == Sub(3); if any(I)+any(J)+any(K) >= 2 Components = cell(1,1); Components{1} = uint32(Sub); CompSize = 1; elseif any(I) Components = cell(2,1); Components{1} = uint32(Sub(1:2)); Components{2} = uint32(Sub(3)); CompSize = [2 1]; elseif any(J) Components = cell(2,1); Components{1} = uint32(Sub([1 3])); Components{2} = uint32(Sub(2)); CompSize = [2 1]; elseif any(K) Components = cell(2,1); Components{1} = uint32(Sub(2:3)); Components{2} = uint32(Sub(1)); CompSize = [2 1]; else Components = cell(3,1); Components{1} = uint32(Sub(1)); Components{2} = uint32(Sub(2)); Components{3} = uint32(Sub(3)); CompSize = [1 1 1]; end end elseif any(Sub) || (length(Sub) == 1 && Sub(1) == 0) nb = size(Nei,1); if nargin == 3 Fal = false(nb,1); end if length(Sub) == 1 && Sub == 0 % All the cover sets ns = nb; if nargin == 3 Sub = true(nb,1); else Sub = ~Fal; end elseif ~islogical(Sub) % Subset of cover sets ns = length(Sub); if nargin == 3 sub = false(nb,1); else sub = Fal; end sub(Sub) = true; Sub = sub; else % Subset of cover sets ns = nnz(Sub); end Components = cell(ns,1); CompSize = zeros(ns,1,'uint32'); nc = 0; % number of components found m = 1; while ~Sub(m) m = m+1; end i = 0; Comp = zeros(ns,1,'uint32'); while i < ns Add = Nei{m}; I = Sub(Add); Add = Add(I); a = length(Add); Comp(1) = m; Sub(m) = false; t = 1; while a > 0 Comp(t+1:t+a) = Add; Sub(Add) = false; t = t+a; Add = vertcat(Nei{Add}); I = Sub(Add); Add = Add(I); % select the unique elements of Add: n = length(Add); if n > 2 I = true(n,1); for j = 1:n if ~Fal(Add(j)) Fal(Add(j)) = true; else I(j) = false; end end Fal(Add) = false; Add = Add(I); elseif n == 2 if Add(1) == Add(2) Add = Add(1); end end a = length(Add); end i = i+t; if t >= MinSize nc = nc+1; Components{nc} = uint32(Comp(1:t)); CompSize(nc) = t; end if i < ns while m <= nb && Sub(m) == false m = m+1; end end end Components = Components(1:nc); CompSize = CompSize(1:nc); else Components = cell(0,1); CompSize = 0; end
github
InverseTampere/TreeQSM-master
growth_volume_correction.m
.m
TreeQSM-master/src/tools/growth_volume_correction.m
5,308
utf_8
43642ad1b72156592dd2da09e8efa614
function cylinder = growth_volume_correction(cylinder,inputs) % --------------------------------------------------------------------- % GROWTH_VOLUME_CORRECTION.M Use growth volume allometry approach to % modify the radius of cylinders. % % Version 2.0.0 % Latest update 16 Sep 2021 % % Copyright (C) 2013-2021 Pasi Raumonen % --------------------------------------------------------------------- % % Use growth volume (= the total volume "supported by the cylinder") % allometry approach to modify the radius of too large and too small % cylinders. Uses the allometry: % % Radius = a * GrowthVolume^b + c % % If cylinder's radius is over fac-times or under 1/fac-times the radius % predicted from the growth volume allometry, then correct the radius to % match the allometry. However, the radius of the cylinders in the branch % tips are never incresed, only decreased by the correction. More details % can be from Jan Hackenberg's "SimpleTree" papers and documents. % --------------------------------------------------------------------- % Inputs: % cylinder Structure array that needs to contains the following fields: % radius (Rad) Radii of the cylinders, vector % length (Len) Lengths of the cylinders, vector % parent (CPar) Parents of the cylinders, vector % inputs.GrowthVolFac The factor "fac", defines the upper and lower % allowed radius from the predicted one: % 1/fac*predicted_rad <= rad <= fac*predicted_rad % --------------------------------------------------------------------- % Changes from version 1.0.0 to 2.0.0, 16 Sep 2021: % 1) Changed the roles of RADIUS and GROWTH_VOLUME in the allometry, i.e. % the radius is now predicted from the growth volume % 2) Do not increase the radius of the branch tip cylinders disp('----------') disp('Growth volume based correction of cylinder radii:') Rad = double(cylinder.radius); Rad0 = Rad; Len = double(cylinder.length); CPar = cylinder.parent; CExt = cylinder.extension; initial_volume = round(1000*pi*sum(Rad.^2.*Len)); disp([' Initial_volume (L): ',num2str(initial_volume)]) %% Define the child cylinders for each cylinder n = length(Rad); CChi = cell(n,1); ind = (1:1:n)'; for i = 1:n CChi{i} = ind(CPar == i); end %% Compute the growth volume GrowthVol = zeros(n,1); % growth volume S = cellfun('length',CChi); modify = S == 0; GrowthVol(modify) = pi*Rad(modify).^2.*Len(modify); parents = unique(CPar(modify)); if parents(1) == 0 parents = parents(2:end); end while ~isempty(parents) V = pi*Rad(parents).^2.*Len(parents); m = length(parents); for i = 1:m GrowthVol(parents(i)) = V(i)+sum(GrowthVol(CChi{parents(i)})); end parents = unique(CPar(parents)); if parents(1) == 0 parents = parents(2:end); end end %% Fit the allometry: Rad = a*GV^b; options = optimset('Display','off'); X = lsqcurvefit(@allometry,[0.5 0.5 0],GrowthVol,Rad,[],[],options); disp(' Allometry model parameters R = a*GV^b+c:') disp([' Multiplier a: ', num2str(X(1))]) disp([' Exponent b: ', num2str(X(2))]) if length(X) > 2 disp([' Intersect c: ', num2str(X(3))]) end %% Compute the predicted radius from the allometry PredRad = allometry(X,GrowthVol); %% Correct the radii based on the predictions % If cylinder's radius is over fac-times or under 1/fac-times the % predicted radius, then correct the radius to match the allometry fac = inputs.GrowthVolFac; modify = Rad < PredRad/fac | Rad > fac*PredRad; modify(Rad < PredRad/fac & CExt == 0) = 0; % Do not increase the radius at tips CorRad = PredRad(modify); % Plot allometry and radii modification gvm = max(GrowthVol); gv = (0:0.001:gvm); PRad = allometry(X,gv); figure(1) plot(GrowthVol,Rad,'.b','Markersize',2) hold on plot(gv,PRad,'-r','Linewidth',2) plot(gv,PRad/fac,'-g','Linewidth',2) plot(gv,fac*PRad,'-g','Linewidth',2) hold off grid on xlabel('Growth volume (m^3)') ylabel('Radius (m)') legend('radius','predicted radius','minimum radius','maximum radius','Location','NorthWest') figure(2) histogram(CorRad-Rad(modify)) xlabel('Change in radius') title('Number of cylinders per change in radius class') % Determine the maximum radius change R = Rad(modify); D = max(abs(R-CorRad)); % Maximum radius change J = abs(R-CorRad) == D; D = CorRad(J)-R(J); % modify the radius according to allometry Rad(modify) = CorRad; cylinder.radius = Rad; disp([' Modified ',num2str(nnz(modify)),' of the ',num2str(n),' cylinders']) disp([' Largest radius change (cm): ',num2str(round(1000*D)/10)]) corrected_volume = round(1000*pi*sum(Rad.^2.*Len)); disp([' Corrected volume (L): ', num2str(corrected_volume)]) disp([' Change in volume (L): ', num2str(corrected_volume-initial_volume)]) disp('----------') % % Plot cylinder models where the color indicates change (green = no change, % % red = decreased radius, cyan = increased radius) % cylinder.branch = ones(n,1); % cylinder.BranchOrder = ones(n,1); % I = Rad < Rad0; % cylinder.BranchOrder(I) = 2; % I = Rad > Rad0; % cylinder.BranchOrder(I) = 3; % plot_cylinder_model(cylinder,'order',3,20,1) % % cyl = cylinder; % cyl.radius = Rad0; % plot_cylinder_model(cyl,'order',4,20,1) end % End of main function function F = allometry(x,xdata) F = x(1)*xdata.^x(2)+x(3); end
github
InverseTampere/TreeQSM-master
simplify_qsm.m
.m
TreeQSM-master/src/tools/simplify_qsm.m
10,948
utf_8
56b1bb310e2e1ffb3db492223c4c62d8
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function QSM = simplify_qsm(QSM,MaxOrder,SmallRadii,ReplaceIterations,Plot,Disp) % --------------------------------------------------------------------- % SIMPLIFY_QSM.M Simplifies cylinder QSMs by restricting the maximum % branching order, by removing thin branches, and by % replacing two concecutive cylinders with a longer cylinder % % Version 2.0.0 % Latest update 4 May 2022 % % Copyright (C) 2015-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Inputs: % QSM QSM-structure, output of treeqsm.m, must contain only one model % MaxOrder Maximum branching order, higher order branches removed % SmallRadii Minimum acceptable radius for a branch at its base % ReplaceIterations Number of iterations for replacing two concecutive % cylinders inside one branch with one longer cylinder % Plot If true/1, then plots the cylinder models before and % after the simplification % Disp If Disp == 1, then display the simplication results % (the number of cylinders after each step). If % Disp == 2, then display also the treedata results for % the original and simplified QSMs. If Disp == 0, then % nothing is displayed. % % Output: % Modified QSM NOTICE: cylinder, branch and treedata are modified. % Changes from version 1.1.0 to 2.0.0, 4 May 2022: % 1) Added modification of branch and treedata structures based on the % modified cylinders % 2) Added input for plotting and displaying the results % 3) Corrected some bugs that could cause errors in some special cases if nargin <= 4 Plot = 0; Disp = 1; elseif nargin <= 5 Disp = 1; end if Disp == 2 inputs = QSM.rundata.inputs; display_treedata(QSM.treedata,inputs) end % Plot the cylinder model before the simplification if Plot plot_cylinder_model(QSM.cylinder,'branch',1,20,1) end %% Maximum branching order c = QSM.cylinder; nc = size(c.radius,1); if Disp >= 1 disp([' ',num2str(nc),' cylinders originally']) end % Cylinders with branching order up to MaxBranchOrder SmallOrder = c.BranchOrder <= MaxOrder; N = fieldnames(c); n = max(size(N)); for i = 1:n c.(N{i}) = c.(N{i})(SmallOrder,:); end % Modify topology information Ind = (1:1:nc)'; m = nnz(SmallOrder); Ind(SmallOrder) = (1:1:m)'; I = c.parent > 0; c.parent(I) = Ind(c.parent(I)); I = c.extension > 0; c.extension(I) = Ind(c.extension(I)); if Disp == 1 nc = nnz(SmallOrder); disp([' ',num2str(nc),' cylinders after branching order simplification']) end %% Small branches if nargin >= 3 && SmallRadii > 0 nc = size(c.radius,1); % Determine child branches BPar = QSM.branch.parent; nb = size(BPar,1); BChi = cell(nb,1); for i = 1:nb P = BPar(i); if P > 0 BChi{P} = [BChi{P}; i]; end end % Remove branches whose radii is too small compared to its parent Large = true(nc,1); Pass = true(nb,1); for i = 1:nb if Pass(i) if QSM.branch.diameter(i) < SmallRadii B = i; BC = BChi{B}; while ~isempty(BC) B = [B; BC]; BC = vertcat(BChi{BC}); end Pass(B) = false; m = length(B); for k = 1:m Large(c.branch == B(k)) = false; end end end end % Modify topology information Ind = (1:1:nc)'; m = nnz(Large); Ind(Large) = (1:1:m)'; I = c.parent > 0; c.parent(I) = Ind(c.parent(I)); I = c.extension > 0; c.extension(I) = Ind(c.extension(I)); % Update/reduce cylinders for i = 1:n c.(N{i}) = c.(N{i})(Large,:); end if Disp >= 1 nc = nnz(Large); disp([' ',num2str(nc),' cylinders after small branch simplification']) end end %% Cylinder replacing if nargin >= 4 && ReplaceIterations > 0 % Determine child cylinders nc = size(c.radius,1); CChi = cell(nc,1); for i = 1:nc P = c.parent(i); if P > 0 PE = c.extension(P); if PE ~= i CChi{P} = [CChi{P}; i]; end end end % Replace cylinders for j = 1:ReplaceIterations nc = size(c.radius,1); Ind = (1:1:nc)'; Keep = false(nc,1); i = 1; while i <= nc t = 1; while i+t <= nc && c.branch(i+t) == c.branch(i) t = t+1; end Cyls = (i:1:i+t-1)'; S = c.start(Cyls,:); A = c.axis(Cyls,:); L = c.length(Cyls); if t == 1 % one cylinder in the branch Keep(i) = true; elseif ceil(t/2) == floor(t/2) % even number of cylinders in the branch I = (1:2:t)'; % select 1., 3., 5., ... % Correct radii, axes and lengths E = S(end,:)+L(end)*A(end,:); S = S(I,:); m = length(I); if m > 1 A = [S(2:end,:); E]-S(1:end,:); else A = E-S(1,:); end L = sqrt(sum(A.*A,2)); A = [A(:,1)./L A(:,2)./L A(:,3)./L]; cyls = Cyls(I); Keep(cyls) = true; V = pi*c.radius(Cyls).^2.*c.length(Cyls); J = (2:2:t)'; V = V(I)+V(J); R = sqrt(V./L/pi); c.radius(cyls) = R; else % odd number of cylinders I = [1 2:2:t]'; % select 1., 2., 4., 6., ... % Correct radii, axes and lengths E = S(end,:)+L(end)*A(end,:); S = S(I,:); l = L(1); a = A(I,:); m = length(I); if m > 2 a(2:end,:) = [S(3:end,:); E]-S(2:end,:); else a(2,:) = E-S(2,:); end A = a; L = sqrt(sum(A.*A,2)); L(1) = l; A(2:end,:) = [A(2:end,1)./L(2:end) A(2:end,2)./L(2:end) A(2:end,3)./L(2:end)]; cyls = Cyls(I); Keep(cyls) = true; V = pi*c.radius(Cyls).^2.*c.length(Cyls); J = (3:2:t)'; V = V(I(2:end))+V(J); R = sqrt(V./L(2:end)/pi); c.radius(cyls(2:end)) = R; end if t > 1 % Modify cylinders c.length(cyls) = L; c.axis(cyls,:) = A; % Correct branching/topology information c.PositionInBranch(cyls) = (1:1:m)'; c.extension(cyls) = [cyls(2:end); 0]; c.parent(cyls(2:end)) = cyls(1:end-1); par = c.parent(cyls(1)); if par > 0 && ~Keep(par) par0 = c.parent(par); if Keep(par0) && c.extension(par0) == par c.parent(cyls(1)) = par0; end end % Correct child branches chi = vertcat(CChi{Cyls}); if ~isempty(chi) par = c.parent(chi); J = Keep(par); par = par(~J)-1; c.parent(chi(~J)) = par; par = c.parent(chi); rp = c.radius(par); sp = c.start(par,:); ap = c.axis(par,:); lc = c.length(chi); sc = c.start(chi,:); ac = c.axis(chi,:); ec = sc+[lc.*ac(:,1) lc.*ac(:,2) lc.*ac(:,3)]; m = length(chi); for k = 1:m [d,V,h,B] = distances_to_line(sc(k,:),ap(k,:),sp(k,:)); V = V/d; sc(k,:) = sp(k,:)+rp(k)*V+B; end ac = ec-sc; [ac,lc] = normalize(ac); c.length(chi) = lc; c.start(chi,:) = sc; c.axis(chi,:) = ac; end end i = i+t; end % Change topology (parent, extension) indexes m = nnz(Keep); Ind(Keep) = (1:1:m)'; I = c.parent > 0; c.parent(I) = Ind(c.parent(I)); I = c.extension > 0; c.extension(I) = Ind(c.extension(I)); % Update/reduce cylinders for i = 1:n c.(N{i}) = c.(N{i})(Keep,:); end if j < ReplaceIterations % Determine child cylinders nc = size(c.radius,1); CChi = cell(nc,1); for i = 1:nc P = c.parent(i); if P > 0 PE = c.extension(P); if PE ~= i CChi{P} = [CChi{P}; i]; end end end end end if Disp >= 1 nc = size(c.radius,1); disp([' ',num2str(nc),' cylinders after cylinder replacements']) end end if Disp >= 1 nc = size(c.radius,1); disp([' ',num2str(nc),' cylinders after all simplifications']) end %% Updata the QSM % Update the branch branch = branches(c); % Update the treedata inputs = QSM.rundata.inputs; inputs.plot = 0; % Display if Disp == 2 inputs.disp = 2; else inputs.disp = 0; end treedata = update_tree_data(QSM,c,branch,inputs); % Update the cylinder, branch, and treedata of the QSM QSM.cylinder = c; QSM.branch = branch; QSM.treedata = treedata; % Plot the cylinder model after the simplification if Plot plot_cylinder_model(QSM.cylinder,'branch',2,20,1) end end % End of main function function display_treedata(treedata,inputs) %% Generate units for displaying the treedata Names = fieldnames(treedata); n = size(Names,1); Units = zeros(n,3); m = 23; for i = 1:n if ~inputs.Tria && strcmp(Names{i},'CrownVolumeAlpha') m = i; elseif inputs.Tria && strcmp(Names{i},'TriaTrunkLength') m = i; end if strcmp(Names{i}(1:3),'DBH') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'ume') Units(i,:) = 'L '; elseif strcmp(Names{i}(end-2:end),'ght') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'gth') Units(i,:) = 'm '; elseif strcmp(Names{i}(1:3),'vol') Units(i,:) = 'L '; elseif strcmp(Names{i}(1:3),'len') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'rea') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(1:3),'loc') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-4:end),'aConv') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-5:end),'aAlpha') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-4:end),'eConv') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-5:end),'eAlpha') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-2:end),'Ave') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'Max') Units(i,:) = 'm '; end end %% Display treedata disp('------------') disp(' Tree attributes before simplification:') for i = 1:m v = change_precision(treedata.(Names{i})); if strcmp(Names{i},'DBHtri') disp(' -----') disp(' Tree attributes from triangulation:') end disp([' ',Names{i},' = ',num2str(v),' ',Units(i,:)]) end disp(' -----') end
github
InverseTampere/TreeQSM-master
save_model_text.m
.m
TreeQSM-master/src/tools/save_model_text.m
4,758
utf_8
b477a27d4b1f21363cdf3c28f6c7f863
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function save_model_text(QSM,savename) % --------------------------------------------------------------------- % SAVE_MODEL_TEXT.M Saves QSM (cylinder, branch, treedata) into text % files % % Version 1.1.0 % Latest update 17 Aug 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % Save the cylinder, branch, and treedata structures in text-formats (.txt) % into /result-folder with the input "savename" defining the file names: % 'cylinder_',savename,'.txt' % 'branch_',savename,'.txt' % 'treedata_',savename,'.txt' % !!! Notice that only part of the treedata, the single number tree % attributes are saved in the text-file. % Every user can change this code easily to define what is saved into % their text-files. % Changes from version 1.0.0 to 1.1.0, 17 Aug 2020: % 1) Added the new fields of cylinder, branch and treedata structures % 2) Added header names to the files % 3) Changed the names of the files to be saved % 4) Changed the name of second input from "string" to "savename" % 5) Changed the rounding of some parameters and attributes cylinder = QSM.cylinder; branch = QSM.branch; treedata = QSM.treedata; %% Form cylinder data, branch data and tree data % Use less decimals Rad = round(10000*cylinder.radius)/10000; % radius (m) Len = round(10000*cylinder.length)/10000; % length (m) Sta = round(10000*cylinder.start)/10000; % starting point (m) Axe = round(10000*cylinder.axis)/10000; % axis (m) CPar = single(cylinder.parent); % parent cylinder CExt = single(cylinder.extension); % extension cylinder Added = single(cylinder.added); % is cylinder added to fil a gap Rad0 = round(10000*cylinder.UnmodRadius)/10000; % unmodified radius (m) B = single(cylinder.branch); % branch index of the cylinder BO = single(cylinder.BranchOrder); % branch order of the branch PIB = single(cylinder.PositionInBranch); % position of the cyl. in the branch Mad = single(round(10000*cylinder.mad)/10000); % mean abso. distance (m) SC = single(round(10000*cylinder.SurfCov)/10000); % surface coverage CylData = [Rad Len Sta Axe CPar CExt B BO PIB Mad SC Added Rad0]; NamesC = ['radius (m)',"length (m)","start_point","axis_direction",... "parent","extension","branch","branch_order","position_in_branch",... "mad","SurfCov","added","UnmodRadius (m)"]; BOrd = single(branch.order); % branch order BPar = single(branch.parent); % parent branch BDia = round(10000*branch.diameter)/10000; % diameter (m) BVol = round(10000*branch.volume)/10000; % volume (L) BAre = round(10000*branch.area)/10000; % area (m^2) BLen = round(1000*branch.length)/1000; % length (m) BAng = round(10*branch.angle)/10; % angle (deg) BHei = round(1000*branch.height)/1000; % height (m) BAzi = round(10*branch.azimuth)/10; % azimuth (deg) BZen = round(10*branch.zenith)/10; % zenith (deg) BranchData = [BOrd BPar BDia BVol BAre BLen BHei BAng BAzi BZen]; NamesB = ["order","parent","diameter (m)","volume (L)","area (m^2)",... "length (m)","height (m)","angle (deg)","azimuth (deg)","zenith (deg)"]; % Extract the field names of treedata Names = fieldnames(treedata); n = 1; while ~strcmp(Names{n},'location') n = n+1; end n = n-1; Names = Names(1:n); TreeData = zeros(n,1); % TreeData contains TotalVolume, TrunkVolume, BranchVolume, etc for i = 1:n TreeData(i) = treedata.(Names{i,:}); end TreeData = change_precision(TreeData); % use less decimals NamesD = string(Names); %% Save the data as text-files str = ['results/cylinder_',savename,'.txt']; fid = fopen(str, 'wt'); fprintf(fid, [repmat('%s\t', 1, size(NamesC,2)-1) '%s\n'], NamesC.'); fprintf(fid, [repmat('%g\t', 1, size(CylData,2)-1) '%g\n'], CylData.'); fclose(fid); str = ['results/branch_',savename,'.txt']; fid = fopen(str, 'wt'); fprintf(fid, [repmat('%s\t', 1, size(NamesB,2)-1) '%s\n'], NamesB.'); fprintf(fid, [repmat('%g\t', 1, size(BranchData,2)-1) '%g\n'], BranchData.'); fclose(fid); str = ['results/treedata_',savename,'.txt']; fid = fopen(str, 'wt'); NamesD(:,2) = TreeData; fprintf(fid,'%s\t %g\n',NamesD.'); fclose(fid);
github
InverseTampere/TreeQSM-master
define_input.m
.m
TreeQSM-master/src/tools/define_input.m
4,812
utf_8
fc9070dc19351ba25dce1ec2036e2d6d
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function inputs = define_input(Clouds,nPD1,nPD2Min,nPD2Max) % --------------------------------------------------------------------- % DEFINE_INPUT.M Defines the required inputs (PatchDiam and BallRad % parameters) for TreeQSM based in estimated tree % radius. % % Version 1.0.0 % Latest update 4 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Takes in a single tree point clouds, that preferably contains only points % from the tree and not e.g. from groung. User defines the number of % PatchDiam1, PatchDiam2Min, PatchDiam2Max parameter values needed. Then % the code estimates automatically these parameter values based on the % tree stem radius and tree height. Thus this code can be used to generate % the inputs needed for QSM reconstruction with TreeQSM. % % Inputs: % P Point cloud of a tree OR string specifying the name of the .mat % file where multiple point clouds are saved % nPD1 Number of parameter values estimated for PatchDiam1 % nPD2Min Number of parameter values estimated for PatchDiam2Min % nPD2Max Number of parameter values estimated for PatchDiam2Max % % Output: % inputs Input structure with the estimated parameter values % --------------------------------------------------------------------- % Create inputs-structure create_input Inputs = inputs; % If given multiple clouds, extract the names if ischar(Clouds) || isstring(Clouds) matobj = matfile([Clouds,'.mat']); names = fieldnames(matobj); i = 1; n = max(size(names)); while i <= n && ~strcmp(names{i,:},'Properties') i = i+1; end I = (1:1:n); I = setdiff(I,i); names = names(I,1); names = sort(names); nt = max(size(names)); % number of trees/point clouds else P = Clouds; nt = 1; end inputs(nt).PatchDiam1 = 0; %% Estimate the PatchDiam and BallRad parameters for i = 1:nt if nt > 1 % Select point cloud P = matobj.(names{i}); inputs(i) = Inputs; inputs(i).name = names{i}; inputs(i).tree = i; inputs(i).plot = 0; inputs(i).savetxt = 0; inputs(i).savemat = 0; inputs(i).disp = 0; end %% Estimate the stem diameter close to bottom % Define height Hb = min(P(:,3)); Ht = max(P(:,3)); TreeHeight = double(Ht-Hb); Hei = P(:,3)-Hb; % Select a section (0.02-0.1*tree_height) from the bottom of the tree hSecTop = min(4,0.1*TreeHeight); hSecBot = 0.02*TreeHeight; hSec = hSecTop-hSecBot; Sec = Hei > hSecBot & Hei < hSecTop; StemBot = P(Sec,1:3); % Estimate stem axis (point and direction) AxisPoint = mean(StemBot); V = StemBot-AxisPoint; V = normalize(V); AxisDir = optimal_parallel_vector(V); % Estimate stem diameter d = distances_to_line(StemBot,AxisDir,AxisPoint); Rstem = double(median(d)); % Point resolution (distance between points) Res = sqrt((2*pi*Rstem*hSec)/size(StemBot,1)); %% Define the PatchDiam parameters % PatchDiam1 is around stem radius divided by 3. pd1 = Rstem/3;%*max(1,TreeHeight/20); if nPD1 == 1 inputs(i).PatchDiam1 = pd1; else n = nPD1; inputs(i).PatchDiam1 = linspace((0.90-(n-2)*0.1)*pd1,(1.10+(n-2)*0.1)*pd1,n); end % PatchDiam2Min is around stem radius divided by 6 and increased for % over 20 m heigh trees. pd2 = Rstem/6*min(1,20/TreeHeight); if nPD2Min == 1 inputs(i).PatchDiam2Min = pd2; else n = nPD2Min; inputs(i).PatchDiam2Min = linspace((0.90-(n-2)*0.1)*pd2,(1.10+(n-2)*0.1)*pd2,n); end % PatchDiam2Max is around stem radius divided by 2.5. pd3 = Rstem/2.5;%*max(1,TreeHeight/20); if nPD2Max == 1 inputs(i).PatchDiam2Max = pd3; else n = nPD2Max; inputs(i).PatchDiam2Max = linspace((0.90-(n-2)*0.1)*pd3,(1.10+(n-2)*0.1)*pd3,n); end % Define the BallRad parameters: inputs(i).BallRad1 = max([inputs(i).PatchDiam1+1.5*Res; min(1.25*inputs(i).PatchDiam1,inputs(i).PatchDiam1+0.025)]); inputs(i).BallRad2 = max([inputs(i).PatchDiam2Max+1.25*Res; min(1.2*inputs(i).PatchDiam2Max,inputs(i).PatchDiam2Max+0.025)]); %plot_point_cloud(P,1,1) end
github
InverseTampere/TreeQSM-master
update_tree_data.m
.m
TreeQSM-master/src/tools/update_tree_data.m
22,826
utf_8
e026d8880095f35cc2322e8a540a7ed4
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function treedata = update_tree_data(QSM,cylinder,branch,inputs) % --------------------------------------------------------------------- % UPDATE_TREE_DATA.M Updates the treedata structure, e.g. after % simplification of QSM % % Version 1.0.0 % Latest update 4 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Inputs: % treedata Treedata structure from "tree_data" % cylinder Cylinder structure from "cylinders" % branch Branch structure from "branches" % % Output: % treedata Tree data/attributes in a struct % --------------------------------------------------------------------- % Define some variables from cylinder: treedata = QSM.treedata; Rad = cylinder.radius; Len = cylinder.length; Sta = cylinder.start; Axe = cylinder.axis; nc = length(Rad); ind = (1:1:nc)'; Trunk = cylinder.branch == 1; % Trunk cylinders %% Tree attributes from cylinders % Volumes, areas, lengths, branches treedata.TotalVolume = 1000*pi*Rad.^2'*Len; treedata.TrunkVolume = 1000*pi*Rad(Trunk).^2'*Len(Trunk); treedata.BranchVolume = 1000*pi*Rad(~Trunk).^2'*Len(~Trunk); bottom = min(Sta(:,3)); [top,i] = max(Sta(:,3)); if Axe(i,3) > 0 top = top+Len(i)*Axe(i,3); end treedata.TreeHeight = top-bottom; treedata.TrunkLength = sum(Len(Trunk)); treedata.BranchLength = sum(Len(~Trunk)); treedata.TotalLength = treedata.TrunkLength+treedata.BranchLength; NB = length(branch.order)-1; % number of branches treedata.NumberBranches = NB; BO = max(branch.order); % maximum branch order treedata.MaxBranchOrder = BO; treedata.TrunkArea = 2*pi*sum(Rad(Trunk).*Len(Trunk)); treedata.BranchArea = 2*pi*sum(Rad(~Trunk).*Len(~Trunk)); treedata.TotalArea = 2*pi*sum(Rad.*Len); %% Crown measures,Vertical profile and spreads [treedata,spreads] = crown_measures(treedata,cylinder,branch); %% Update triangulation information if inputs.Tria treedata = update_triangulation(QSM,treedata,cylinder); end %% Tree Location treedata.location = Sta(1,:); %% Stem taper R = Rad(Trunk); n = length(R); Taper = zeros(n+1,2); Taper(1,2) = 2*R(1); Taper(2:end,1) = cumsum(Len(Trunk)); Taper(2:end,2) = [2*R(2:end); 2*R(n)]; treedata.StemTaper = Taper'; %% Vertical profile and spreads treedata.VerticalProfile = mean(spreads,2); treedata.spreads = spreads; %% CYLINDER DISTRIBUTIONS: %% Wood part diameter distributions % Volume, area and length of wood parts as functions of cylinder diameter % (in 1cm diameter classes) treedata = cylinder_distribution(treedata,Rad,Len,Axe,'Dia'); %% Wood part height distributions % Volume, area and length of cylinders as a function of height % (in 1 m height classes) treedata = cylinder_height_distribution(treedata,Rad,Len,Sta,Axe,ind); %% Wood part zenith direction distributions % Volume, area and length of wood parts as functions of cylinder zenith % direction (in 10 degree angle classes) treedata = cylinder_distribution(treedata,Rad,Len,Axe,'Zen'); %% Wood part azimuth direction distributions % Volume, area and length of wood parts as functions of cylinder zenith % direction (in 10 degree angle classes) treedata = cylinder_distribution(treedata,Rad,Len,Axe,'Azi'); %% BRANCH DISTRIBUTIONS: %% Branch order distributions % Volume, area, length and number of branches as a function of branch order treedata = branch_order_distribution(treedata,branch); %% Branch diameter distributions % Volume, area, length and number of branches as a function of branch diameter % (in 1cm diameter classes) treedata = branch_distribution(treedata,branch,'Dia'); %% Branch height distribution % Volume, area, length and number of branches as a function of branch height % (in 1 meter classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Hei'); %% Branch angle distribution % Volume, area, length and number of branches as a function of branch angle % (in 10 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Ang'); %% Branch azimuth distribution % Volume, area, length and number of branches as a function of branch azimuth % (in 22.5 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Azi'); %% Branch zenith distribution % Volume, area, length and number of branches as a function of branch zenith % (in 10 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Zen'); %% change into single-format Names = fieldnames(treedata); n = size(Names,1); for i = 1:n treedata.(Names{i}) = single(treedata.(Names{i})); end if inputs.disp == 2 %% Generate units for displaying the treedata Units = zeros(n,3); m = 23; for i = 1:n if ~inputs.Tria && strcmp(Names{i},'CrownVolumeAlpha') m = i; elseif inputs.Tria && strcmp(Names{i},'TriaTrunkLength') m = i; end if strcmp(Names{i}(1:3),'DBH') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'ume') Units(i,:) = 'L '; elseif strcmp(Names{i}(end-2:end),'ght') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'gth') Units(i,:) = 'm '; elseif strcmp(Names{i}(1:3),'vol') Units(i,:) = 'L '; elseif strcmp(Names{i}(1:3),'len') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'rea') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(1:3),'loc') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-4:end),'aConv') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-5:end),'aAlpha') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-4:end),'eConv') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-5:end),'eAlpha') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-2:end),'Ave') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'Max') Units(i,:) = 'm '; end end %% Display treedata disp('------------') disp(' Tree attributes:') for i = 1:m v = change_precision(treedata.(Names{i})); if strcmp(Names{i},'DBHtri') disp(' -----') disp(' Tree attributes from triangulation:') end disp([' ',Names{i},' = ',num2str(v),' ',Units(i,:)]) end disp(' -----') end if inputs.plot > 1 %% Plot distributions figure(6) subplot(2,4,1) plot(Taper(:,1),Taper(:,2),'-b') title('Stem taper') xlabel('Distance from base (m)') ylabel('Diameter (m)') axis tight grid on Q.treedata = treedata; subplot(2,4,2) plot_distribution(Q,6,0,0,'VolCylDia') subplot(2,4,3) plot_distribution(Q,6,0,0,'AreCylDia') subplot(2,4,4) plot_distribution(Q,6,0,0,'LenCylDia') subplot(2,4,5) plot_distribution(Q,6,0,0,'VolBranchOrd') subplot(2,4,6) plot_distribution(Q,6,0,0,'LenBranchOrd') subplot(2,4,7) plot_distribution(Q,6,0,0,'AreBranchOrd') subplot(2,4,8) plot_distribution(Q,6,0,0,'NumBranchOrd') figure(7) subplot(3,3,1) plot_distribution(Q,7,0,0,'VolCylHei') subplot(3,3,2) plot_distribution(Q,7,0,0,'AreCylHei') subplot(3,3,3) plot_distribution(Q,7,0,0,'LenCylHei') subplot(3,3,4) plot_distribution(Q,7,0,0,'VolCylZen') subplot(3,3,5) plot_distribution(Q,7,0,0,'AreCylZen') subplot(3,3,6) plot_distribution(Q,7,0,0,'LenCylZen') subplot(3,3,7) plot_distribution(Q,7,0,0,'VolCylAzi') subplot(3,3,8) plot_distribution(Q,7,0,0,'AreCylAzi') subplot(3,3,9) plot_distribution(Q,7,0,0,'LenCylAzi') figure(8) subplot(3,4,1) plot_distribution(Q,8,1,0,'VolBranchDia','VolBranch1Dia') subplot(3,4,2) plot_distribution(Q,8,1,0,'AreBranchDia','AreBranch1Dia') subplot(3,4,3) plot_distribution(Q,8,1,0,'LenBranchDia','LenBranch1Dia') subplot(3,4,4) plot_distribution(Q,8,1,0,'NumBranchDia','NumBranch1Dia') subplot(3,4,5) plot_distribution(Q,8,1,0,'VolBranchHei','VolBranch1Hei') subplot(3,4,6) plot_distribution(Q,8,1,0,'AreBranchHei','AreBranch1Hei') subplot(3,4,7) plot_distribution(Q,8,1,0,'LenBranchHei','LenBranch1Hei') subplot(3,4,8) plot_distribution(Q,8,1,0,'NumBranchHei','NumBranch1Hei') subplot(3,4,9) plot_distribution(Q,8,1,0,'VolBranchAng','VolBranch1Ang') subplot(3,4,10) plot_distribution(Q,8,1,0,'AreBranchAng','AreBranch1Ang') subplot(3,4,11) plot_distribution(Q,8,1,0,'LenBranchAng','LenBranch1Ang') subplot(3,4,12) plot_distribution(Q,8,1,0,'NumBranchAng','NumBranch1Ang') figure(9) subplot(2,4,1) plot_distribution(Q,9,1,0,'VolBranchZen','VolBranch1Zen') subplot(2,4,2) plot_distribution(Q,9,1,0,'AreBranchZen','AreBranch1Zen') subplot(2,4,3) plot_distribution(Q,9,1,0,'LenBranchZen','LenBranch1Zen') subplot(2,4,4) plot_distribution(Q,9,1,0,'NumBranchZen','NumBranch1Zen') subplot(2,4,5) plot_distribution(Q,9,1,0,'VolBranchAzi','VolBranch1Azi') subplot(2,4,6) plot_distribution(Q,9,1,0,'AreBranchAzi','AreBranch1Azi') subplot(2,4,7) plot_distribution(Q,9,1,0,'LenBranchAzi','LenBranch1Azi') subplot(2,4,8) plot_distribution(Q,9,1,0,'NumBranchAzi','NumBranch1Azi') end end % End of main function function [treedata,spreads] = crown_measures(treedata,cylinder,branch) %% Generate point clouds from the cylinder model Axe = cylinder.axis; Len = cylinder.length; Sta = cylinder.start; Tip = Sta+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; % tips of the cylinders nc = length(Len); P = zeros(5*nc,3); % four mid points on the cylinder surface t = 0; for i = 1:nc [U,V] = orthonormal_vectors(Axe(i,:)); U = cylinder.radius(i)*U; if cylinder.branch(i) == 1 % For stem cylinders generate more points for k = 1:4 M = Sta(i,:)+k*Len(i)/4*Axe(i,:); R = rotation_matrix(Axe(i,:),pi/12); for j = 1:12 if j > 1 U = R*U; end t = t+1; P(t,:) = M+U'; end end else M = Sta(i,:)+Len(i)/2*Axe(i,:); R = rotation_matrix(Axe(i,:),pi/4); for j = 1:4 if j > 1 U = R*U; end t = t+1; P(t,:) = M+U'; end end end P = P(1:t,:); P = double([P; Sta; Tip]); P = unique(P,'rows'); %% Vertical profiles (layer diameters/spreads), mean: bot = min(P(:,3)); top = max(P(:,3)); Hei = top-bot; if Hei > 10 m = 20; elseif Hei > 2 m = 10; else m = 5; end spreads = zeros(m,18); for j = 1:m I = P(:,3) >= bot+(j-1)*Hei/m & P(:,3) < bot+j*Hei/m; X = unique(P(I,:),'rows'); if size(X,1) > 5 [K,A] = convhull(X(:,1),X(:,2)); % compute center of gravity for the convex hull and use it as % center for computing average diameters n = length(K); x = X(K,1); y = X(K,2); CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; V = mat_vec_subtraction(X(:,1:2),[CX CY]); ang = atan2(V(:,2),V(:,1))+pi; [ang,I] = sort(ang); L = sqrt(sum(V.*V,2)); L = L(I); for i = 1:18 I = ang >= (i-1)*pi/18 & ang < i*pi/18; if any(I) L1 = max(L(I)); else L1 = 0; end J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi; if any(J) L2 = max(L(J)); else L2 = 0; end spreads(j,i) = L1+L2; end end end %% Crown diameters (spreads), mean and maximum: X = unique(P(:,1:2),'rows'); [K,A] = convhull(X(:,1),X(:,2)); % compute center of gravity for the convex hull and use it as center for % computing average diameters n = length(K); x = X(K,1); y = X(K,2); CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; V = mat_vec_subtraction(Tip(:,1:2),[CX CY]); ang = atan2(V(:,2),V(:,1))+pi; [ang,I] = sort(ang); L = sqrt(sum(V.*V,2)); L = L(I); S = zeros(18,1); for i = 1:18 I = ang >= (i-1)*pi/18 & ang < i*pi/18; if any(I) L1 = max(L(I)); else L1 = 0; end J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi; if any(J) L2 = max(L(J)); else L2 = 0; end S(i) = L1+L2; end treedata.CrownDiamAve = mean(S); MaxDiam = 0; for i = 1:n V = mat_vec_subtraction([x y],[x(i) y(i)]); L = max(sqrt(sum(V.*V,2))); if L > MaxDiam MaxDiam = L; end end treedata.CrownDiamMax = L; %% Crown areas from convex hull and alpha shape: treedata.CrownAreaConv = A; alp = max(0.5,treedata.CrownDiamAve/10); shp = alphaShape(X(:,1),X(:,2),alp); treedata.CrownAreaAlpha = shp.area; %% Crown base % Define first major branch as the branch whose diameter > min(0.05*dbh,5cm) % and whose horizontal relative reach is more than the median reach of 1st-ord. % branches (or at maximum 10). The reach is defined as the horizontal % distance from the base to the tip divided by the dbh. dbh = treedata.DBHcyl; nb = length(branch.order); HL = zeros(nb,1); % horizontal reach branches1 = (1:1:nb)'; branches1 = branches1(branch.order == 1); % 1st-order branches nb = length(branches1); nc = size(Sta,1); ind = (1:1:nc)'; for i = 1:nb C = ind(cylinder.branch == branches1(i)); if ~isempty(C) base = Sta(C(1),:); C = C(end); tip = Sta(C,:)+Len(C)*Axe(C); V = tip(1:2)-base(1:2); HL(branches1(i)) = sqrt(V*V')/dbh*2; end end M = min(10,median(HL)); % Sort the branches according to the their heights Hei = branch.height(branches1); [Hei,SortOrd] = sort(Hei); branches1 = branches1(SortOrd); % Search the first/lowest branch: d = min(0.05,0.05*dbh); b = 0; if nb > 1 i = 1; while i < nb i = i+1; if branch.diameter(branches1(i)) > d && HL(branches1(i)) > M b = branches1(i); i = nb+2; end end if i == nb+1 && nb > 1 b = branches1(1); end end if b > 0 % search all the children of the first major branch: nb = size(branch.parent,1); Ind = (1:1:nb)'; chi = Ind(branch.parent == b); B = b; while ~isempty(chi) B = [B; chi]; n = length(chi); C = cell(n,1); for i = 1:n C{i} = Ind(branch.parent == chi(i)); end chi = vertcat(C{:}); end % define crown base height from the ground: BaseHeight = max(Sta(:,3)); % Height of the crown base for i = 1:length(B) C = ind(cylinder.branch == B(i)); ht = min(Tip(C,3)); hb = min(Sta(C,3)); h = min(hb,ht); if h < BaseHeight BaseHeight = h; end end treedata.CrownBaseHeight = BaseHeight-Sta(1,3); %% Crown length and ratio treedata.CrownLength = treedata.TreeHeight-treedata.CrownBaseHeight; treedata.CrownRatio = treedata.CrownLength/treedata.TreeHeight; %% Crown volume from convex hull and alpha shape: I = P(:,3) >= BaseHeight; X = P(I,:); [K,V] = convhull(X(:,1),X(:,2),X(:,3)); treedata.CrownVolumeConv = V; alp = max(0.5,treedata.CrownDiamAve/5); shp = alphaShape(X(:,1),X(:,2),X(:,3),alp,'HoleThreshold',10000); treedata.CrownVolumeAlpha = shp.volume; else % No branches treedata.CrownBaseHeight = treedata.TreeHeight; treedata.CrownLength = 0; treedata.CrownRatio = 0; treedata.CrownVolumeConv = 0; treedata.CrownVolumeAlpha = 0; end end % End of function function treedata = update_triangulation(QSM,treedata,cylinder) % Update the mixed results: if ~isempty(QSM.triangulation) CylInd = QSM.triangulation.cylind; Rad = cylinder.radius; Len = cylinder.length; % Determine the new stem cylinder that is about the location where the % triangulation stops: nc = length(Rad); ind = (1:1:nc)'; ind = ind(cylinder.branch == 1); % cylinders in the stem S = QSM.cylinder.start(CylInd,:); % The place where the triangulation stops V = cylinder.start(ind,:)-S; d = sqrt(sum(V.*V,2)); [d,I] = min(d); V = V(I,:); CylInd = ind(I); % The new cylinder closest to the correct place if d < 0.01 TrunkVolMix = treedata.TrunkVolume-... 1000*pi*sum(Rad(1:CylInd-1).^2.*Len(1:CylInd-1))+QSM.triangulation.volume; TrunkAreaMix = treedata.TrunkArea-... 2*pi*sum(Rad(1:CylInd-1).*Len(1:CylInd-1))+QSM.triangulation.SideArea; else % Select the following cylinder h = V*cylinder.axis(CylInd,:)'; if h < 0 CylInd = CylInd+1; V = cylinder.start(CylInd,:)-S; h = V*cylinder.axis(CylInd,:)'; end Len(CylInd-1) = Len(CylInd-1)-h; TrunkVolMix = treedata.TrunkVolume-... 1000*pi*sum(Rad(1:CylInd-1).^2.*Len(1:CylInd-1))+QSM.triangulation.volume; TrunkAreaMix = treedata.TrunkArea-... 2*pi*sum(Rad(1:CylInd-1).*Len(1:CylInd-1))+QSM.triangulation.SideArea; end treedata.MixTrunkVolume = TrunkVolMix; treedata.MixTotalVolume = TrunkVolMix+treedata.BranchVolume; treedata.MixTrunkArea = TrunkAreaMix; treedata.MixTotalArea = TrunkAreaMix+treedata.BranchArea; end end function treedata = cylinder_distribution(treedata,Rad,Len,Axe,dist) %% Wood part diameter, zenith and azimuth direction distributions % Volume, area and length of wood parts as functions of cylinder % diameter, zenith, and azimuth if strcmp(dist,'Dia') Par = Rad; n = ceil(max(200*Rad)); a = 0.005; % diameter in 1 cm classes elseif strcmp(dist,'Zen') Par = 180/pi*acos(Axe(:,3)); n = 18; a = 10; % zenith direction in 10 degree angle classes elseif strcmp(dist,'Azi') Par = 180/pi*atan2(Axe(:,2),Axe(:,1))+180; n = 36; a = 10; % azimuth direction in 10 degree angle classes end CylDist = zeros(3,n); for i = 1:n K = Par >= (i-1)*a & Par < i*a; CylDist(1,i) = 1000*pi*sum(Rad(K).^2.*Len(K)); % volumes in litres CylDist(2,i) = 2*pi*sum(Rad(K).*Len(K)); % areas in litres CylDist(3,i) = sum(Len(K)); % lengths in meters end treedata.(['VolCyl',dist]) = CylDist(1,:); treedata.(['AreCyl',dist]) = CylDist(2,:); treedata.(['LenCyl',dist]) = CylDist(3,:); end function treedata = cylinder_height_distribution(treedata,Rad,Len,Sta,Axe,ind) %% Wood part height distributions % Volume, area and length of cylinders as a function of height % (in 1 m height classes) MaxHei= ceil(treedata.TreeHeight); treedata.VolCylHei = zeros(1,MaxHei); treedata.AreCylHei = zeros(1,MaxHei); treedata.LenCylHei = zeros(1,MaxHei); End = Sta+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; bot = min(Sta(:,3)); B = Sta(:,3)-bot; T = End(:,3)-bot; for j = 1:MaxHei I1 = B >= (j-2) & B < (j-1); % base below this bin J1 = B >= (j-1) & B < j; % base in this bin K1 = B >= j & B < (j+1); % base above this bin I2 = T >= (j-2) & T < (j-1); % top below this bin J2 = T >= (j-1) & T < j; % top in this bin K2 = T >= j & T < (j+1); % top above this bin C1 = ind(J1&J2); % base and top in this bin C2 = ind(J1&K2); % base in this bin, top above C3 = ind(J1&I2); % base in this bin, top below C4 = ind(I1&J2); % base in bin below, top in this C5 = ind(K1&J2); % base in bin above, top in this v1 = 1000*pi*sum(Rad(C1).^2.*Len(C1)); a1 = 2*pi*sum(Rad(C1).*Len(C1)); l1 = sum(Len(C1)); r2 = (j-B(C2))./(T(C2)-B(C2)); % relative portion in this bin v2 = 1000*pi*sum(Rad(C2).^2.*Len(C2).*r2); a2 = 2*pi*sum(Rad(C2).*Len(C2).*r2); l2 = sum(Len(C2).*r2); r3 = (B(C3)-j+1)./(B(C3)-T(C3)); % relative portion in this bin v3 = 1000*pi*sum(Rad(C3).^2.*Len(C3).*r3); a3 = 2*pi*sum(Rad(C3).*Len(C3).*r3); l3 = sum(Len(C3).*r3); r4 = (T(C4)-j+1)./(T(C4)-B(C4)); % relative portion in this bin v4 = 1000*pi*sum(Rad(C4).^2.*Len(C4).*r4); a4 = 2*pi*sum(Rad(C4).*Len(C4).*r4); l4 = sum(Len(C4).*r4); r5 = (j-T(C5))./(B(C5)-T(C5)); % relative portion in this bin v5 = 1000*pi*sum(Rad(C5).^2.*Len(C5).*r5); a5 = 2*pi*sum(Rad(C5).*Len(C5).*r5); l5 = sum(Len(C5).*r5); treedata.VolCylHei(j) = v1+v2+v3+v4+v5; treedata.AreCylHei(j) = a1+a2+a3+a4+a5; treedata.LenCylHei(j) = l1+l2+l3+l4+l5; end end function treedata = branch_distribution(treedata,branch,dist) %% Branch diameter, height, angle, zenith and azimuth distributions % Volume, area, length and number of branches as a function of branch % diamater, height, angle, zenith and aximuth BOrd = branch.order(2:end); BVol = branch.volume(2:end); BAre = branch.area(2:end); BLen = branch.length(2:end); if strcmp(dist,'Dia') Par = branch.diameter(2:end); n = ceil(max(100*Par)); a = 0.005; % diameter in 1 cm classes elseif strcmp(dist,'Hei') Par = branch.height(2:end); n = ceil(treedata.TreeHeight); a = 1; % height in 1 m classes elseif strcmp(dist,'Ang') Par = branch.angle(2:end); n = 18; a = 10; % angle in 10 degree classes elseif strcmp(dist,'Zen') Par = branch.zenith(2:end); n = 18; a = 10; % zenith direction in 10 degree angle classes elseif strcmp(dist,'Azi') Par = branch.azimuth(2:end)+180; n = 36; a = 10; % azimuth direction in 10 degree angle classes end BranchDist = zeros(8,n); for i = 1:n I = Par >= (i-1)*a & Par < i*a; BranchDist(1,i) = sum(BVol(I)); % volume (all branches) BranchDist(2,i) = sum(BVol(I & BOrd == 1)); % volume (1st-branches) BranchDist(3,i) = sum(BAre(I)); % area (all branches) BranchDist(4,i) = sum(BAre(I & BOrd == 1)); % area (1st-branches) BranchDist(5,i) = sum(BLen(I)); % length (all branches) BranchDist(6,i) = sum(BLen(I & BOrd == 1)); % length (1st-branches) BranchDist(7,i) = nnz(I); % number (all branches) BranchDist(8,i) = nnz(I & BOrd == 1); % number (1st-branches) end treedata.(['VolBranch',dist]) = BranchDist(1,:); treedata.(['VolBranch1',dist]) = BranchDist(2,:); treedata.(['AreBranch',dist]) = BranchDist(3,:); treedata.(['AreBranch1',dist]) = BranchDist(4,:); treedata.(['LenBranch',dist]) = BranchDist(5,:); treedata.(['LenBranch1',dist]) = BranchDist(6,:); treedata.(['NumBranch',dist]) = BranchDist(7,:); treedata.(['NumBranch1',dist]) = BranchDist(8,:); end function treedata = branch_order_distribution(treedata,branch) %% Branch order distributions % Volume, area, length and number of branches as a function of branch order BO = max(branch.order); BranchOrdDist = zeros(BO,4); for i = 1:max(1,BO) I = branch.order == i; BranchOrdDist(i,1) = sum(branch.volume(I)); % volumes BranchOrdDist(i,2) = sum(branch.area(I)); % areas BranchOrdDist(i,3) = sum(branch.length(I)); % lengths BranchOrdDist(i,4) = nnz(I); % number of ith-order branches end treedata.VolBranchOrd = BranchOrdDist(:,1)'; treedata.AreBranchOrd = BranchOrdDist(:,2)'; treedata.LenBranchOrd = BranchOrdDist(:,3)'; treedata.NumBranchOrd = BranchOrdDist(:,4)'; end
github
InverseTampere/TreeQSM-master
initial_boundary_curve.m
.m
TreeQSM-master/src/triangulation/initial_boundary_curve.m
6,528
utf_8
e1d5805313e080d63fe8c8cd0fe44b2e
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function Curve = initial_boundary_curve(P,TriaWidth) % --------------------------------------------------------------------- % INITIAL_BOUNDARY_CURVE.M Determines the boundary curve adaptively. % % Version 1.0.1 % Latest update 26 Nov 2019 % % Copyright (C) 2015-2017 Pasi Raumonen % --------------------------------------------------------------------- % Changes from version 1.0.0 to 1.0.1, 26 Nov 2019: % 1) Bug fix: Added "return" if the "Curve" is empty after it is first defined. %% Define suitable center % Use xy-data and even the z-coordinate to the top Top = max(P(:,3)); P = [P(:,1:2) Top*ones(size(P,1),1)]; % Define the "center" of points as the mean Center = mean(P); Center0 = Center; % If the center is outside or close to the boundary, define new center i = 0; A0 = 61; ShortestDist = 0; while ShortestDist < 0.075 && i < 100 Center = Center0+[3*ShortestDist*randn(1,2) 0]; % Randomly move the center % Compute angles of points as seen from the center V = mat_vec_subtraction(P(:,1:2),Center(1:2)); angle = 180/pi*atan2(V(:,2),V(:,1))+180; % % Check if the center is outside or near the boundary of the cross section A = false(70,1); a = ceil(angle/5); I = a > 0; A(a(I)) = true; if i == 0 ShortestDist = 0.025; elseif nnz(A) < A0 ShortestDist = 0.05; else PointDist = sqrt(sum(V.*V,2)); [ShortestDist,FirstPoint] = min(PointDist); end i = i+1; if i == 100 && ShortestDist < 0.075 i = 0; A0 = A0-2; end end %% Define first boundary curve based on the center Curve = zeros(18,1); % the boundary curve, contains indexed of the point cloud rows Curve(1) = FirstPoint; % start the curve from the point the closest the center % Modify the angles so that first point has the angle 0 a0 = angle(FirstPoint); I = angle < a0; angle(I) = angle(I)+(360-a0); angle(~I) = angle(~I)-a0; % Select the rest of the points as the closest point in 15 deg sectors % centered at 20 deg intervals np = size(P,1); Ind = (1:1:np)'; t = 0; for i = 2:18 J = angle > 12.5+20*(i-2) & angle < 27.5+20*(i-2); if ~any(J) % if no points, try 18 deg sector J = angle > 11+20*(i-2) & angle < 29+20*(i-2); end if any(J) % if sector has points, select the closest point as the curve point D = PointDist(J); ind = Ind(J); [~,J] = min(D); t = t+1; Curve(t) = ind(J); end end Curve = Curve(1:t); if isempty(Curve) return end I = true(np,1); I(Curve) = false; Ind = Ind(I); %% Adapt the initial curve to the data V = P(Curve([(2:t)'; 1]),:)-P(Curve,:); D = sqrt(sum(V(:,1:2).*V(:,1:2),2)); n = t; n0 = 1; % Continue adding new points as long as too long edges exists while any(D > 1.25*TriaWidth) && n > n0 N = [V(:,2) -V(:,1) V(:,3)]; M = P(Curve,:)+0.5*V; Curve1 = Curve; t = 0; for i = 1:n if D(i) > 1.25*TriaWidth [d,~,hc] = distances_to_line(P(Curve1,:),N(i,:),M(i,:)); I = hc > 0.01 & d < D(i)/2; if any(I) H = min(hc(I)); else H = 1; end [d,~,h] = distances_to_line(P(Ind,:),N(i,:),M(i,:)); I = d < D(i)/3 & h > -TriaWidth/2 & h < H; if any(I) ind = Ind(I); h = h(I); [h,J] = min(h); I = ind(J); t = t+1; if i < n Curve1 = [Curve1(1:t); I; Curve1(t+1:end)]; else Curve1 = [Curve1(1:t); I]; end J = Ind ~= I; Ind = Ind(J); t = t+1; else t = t+1; end else t = t+1; end end Curve = Curve1(1:t); n0 = n; n = size(Curve,1); V = P(Curve([(2:n)'; 1]),:)-P(Curve,:); D = sqrt(sum(V.*V,2)); end %% Refine the curve for longer edges if far away points n0 = n-1; while n > n0 N = [V(:,2) -V(:,1) V(:,3)]; M = P(Curve,:)+0.5*V; Curve1 = Curve; t = 0; for i = 1:n if D(i) > 0.5*TriaWidth [d,~,hc] = distances_to_line(P(Curve1,:),N(i,:),M(i,:)); I = hc > 0.01 & d < D(i)/2; if any(I) H = min(hc(I)); else H = 1; end [d,~,h] = distances_to_line(P(Ind,:),N(i,:),M(i,:)); I = d < D(i)/3 & h > -TriaWidth/3 & h < H; ind = Ind(I); h = h(I); [h,J] = min(h); if h > TriaWidth/10 I = ind(J); t = t+1; if i < n Curve1 = [Curve1(1:t); I; Curve1(t+1:end)]; else Curve1 = [Curve1(1:t); I]; end J = Ind ~= I; Ind = Ind(J); t = t+1; else t = t+1; end else t = t+1; end end Curve = Curve1(1:t); n0 = n; n = size(Curve,1); V = P(Curve([(2:n)'; 1]),:)-P(Curve,:); D = sqrt(sum(V.*V,2)); end %% Smooth the curve by defining the points by means of neighbors Curve = P(Curve,:); % Change the curve from point indexes to coordinates Curve = boundary_curve2(P,Curve,0.04,TriaWidth); if isempty(Curve) return end %% Add points for too long edges n = size(Curve,1); V = Curve([(2:n)'; 1],:)-Curve; D = sqrt(sum(V.*V,2)); Curve1 = Curve; t = 0; for i = 1:n if D(i) > TriaWidth m = floor(D(i)/TriaWidth); t = t+1; W = zeros(m,3); for j = 1:m W(j,:) = Curve(i,:)+j/(m+1)*V(i,:); end Curve1 = [Curve1(1:t,:); W; Curve1(t+1:end,:)]; t = t+m ; else t = t+1; end end Curve = Curve1; n = size(Curve,1); %% Define the curve again by equalising the point distances along the curve V = Curve([(2:n)'; 1],:)-Curve; D = sqrt(sum(V.*V,2)); L = cumsum(D); m = ceil(L(end)/TriaWidth); TriaWidth = L(end)/m; Curve1 = zeros(m,3); Curve1(1,:) = Curve(1,:); b = 1; for i = 2:m while L(b) < (i-1)*TriaWidth b = b+1; end if b > 1 a = ((i-1)*TriaWidth-L(b-1))/D(b); Curve1(i,:) = Curve(b,:)+a*V(b,:); else a = (L(b)-(i-1)*TriaWidth)/D(b); Curve1(i,:) = Curve(b,:)+a*V(b,:); end end Curve = Curve1; Intersect = check_self_intersection(Curve(:,1:2)); if Intersect Curve = zeros(0,3); end
github
InverseTampere/TreeQSM-master
boundary_curve2.m
.m
TreeQSM-master/src/triangulation/boundary_curve2.m
4,546
utf_8
66ccb1233259456e8b6ba495d5ff178a
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function Curve = boundary_curve2(P,Curve0,rball,dmax) % --------------------------------------------------------------------- % BOUNDARY_CURVE2.M Determines the boundary curve based on the % previously defined boundary curve. % % Version 1.0 % Latest update 16 Aug 2017 % % Copyright (C) 2015-2017 Pasi Raumonen % --------------------------------------------------------------------- % % Inputs: % P Point cloud of the cross section % Curve0 Seed points from previous cross section curve % rball Radius of the balls centered at seed points % dmax Maximum distance between concecutive curve points, if larger, % then create a new one between the points %% Partition the point cloud into cubes Min = double(min([P(:,1:2); Curve0(:,1:2)])); Max = double(max([P(:,1:2); Curve0(:,1:2)])); N = double(ceil((Max-Min)/rball)+5); CC = floor([P(:,1)-Min(1) P(:,2)-Min(2)]/rball)+3; % cube coordinates of the section points % Sorts the points according a lexicographical order S = [CC(:,1) CC(:,2)-1]*[1 N(1)]'; [S,I] = sort(S); % Define "partition" np = size(P,1); partition = cell(N(1),N(2)); p = 1; % The index of the point under comparison while p <= np t = 1; while (p+t <= np) && (S(p) == S(p+t)) t = t+1; end q = I(p); partition{CC(q,1),CC(q,2)} = I(p:p+t-1); p = p+t; end %% Define segments using the previous points CC = floor([Curve0(:,1)-Min(1) Curve0(:,2)-Min(2)]/rball)+3; % cube coordinates of the seed points I = CC < 3; CC(I) = 3; nc = size(Curve0,1); % number of sets Dist = 1e8*ones(np,1); % distance of point to the closest center SoP = zeros(np,1); % the segment the points belong to Radius = rball^2; for i = 1:nc points = partition(CC(i,1)-1:CC(i,1)+1,CC(i,2)-1:CC(i,2)+1); points = vertcat(points{:}); V = [P(points,1)-Curve0(i,1) P(points,2)-Curve0(i,2)]; dist = sum(V.*V,2); PointsInBall = dist < Radius; points = points(PointsInBall); dist = dist(PointsInBall); D = Dist(points); L = dist < D; I = points(L); Dist(I) = dist(L); SoP(I) = i; end %% Finalise the segments % Number of points in each segment and index of each point in its segment Num = zeros(nc,1); IndPoints = zeros(np,1); for i = 1:np if SoP(i) > 0 Num(SoP(i)) = Num(SoP(i))+1; IndPoints(i) = Num(SoP(i)); end end % Continue if enough non-emtpy segments if nnz(Num) > 0.05*nc % Initialization of the "Seg" Seg = cell(nc,1); for i = 1:nc Seg{i} = zeros(Num(i),1); end % Define the "Seg" for i = 1:np if SoP(i) > 0 Seg{SoP(i),1}(IndPoints(i),1) = i; end end %% Define the new curve points as the average of the segments Curve = zeros(nc,3); % the new boundary curve for i = 1:nc S = Seg{i}; if ~isempty(S) Curve(i,:) = mean(P(S,:),1); if norm(Curve(i,:)-Curve0(i,:)) > 1.25*dmax Curve(i,:) = Curve0(i,:); end else Curve(i,:) = Curve0(i,:); end end %% Add new points if too large distances V = Curve([2:end 1],:)-Curve(1:end,:); d = sum(V.*V,2); Large = d > dmax^2; m = nnz(Large); if m > 0 Curve0 = zeros(nc+m,3); t = 0; for i = 1:nc if Large(i) t = t+1; Curve0(t,:) = Curve(i,:); t = t+1; Curve0(t,:) = Curve(i,:)+0.5*V(i,:); else t = t+1; Curve0(t,:) = Curve(i,:); end end Curve = Curve0; end %% Remove new points if too small distances nc = size(Curve,1); V = Curve([2:end 1],:)-Curve(1:end,:); d = sum(V.*V,2); Small = d < (0.333*dmax)^2; m = nnz(Small); if m > 0 for i = 1:nc-1 if Small(i) && Small(i+1) Small(i+1) = false; end end if ~Small(nc) && Small(1) Small(1) = false; Small(nc) = true; end Curve = Curve(~Small,:); end else % If not enough new points, return the old curve Curve = Curve0; end
github
InverseTampere/TreeQSM-master
boundary_curve.m
.m
TreeQSM-master/src/triangulation/boundary_curve.m
8,054
utf_8
8dbebbed345eaa90bcef38e7c4e1da9f
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [Curve,Ind] = boundary_curve(P,Curve0,rball,dmax) % --------------------------------------------------------------------- % BOUNDARY_CURVE.M Determines the boundary curve based on the % previously defined boundary curve. % % Version 1.1.0 % Latest update 3 May 2022 % % Copyright (C) 2015-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Inputs: % P Point cloud of the cross section % Curve0 Seed points from previous cross section curve % rball Radius of the balls centered at seed points % dmax Maximum distance between concecutive curve points, if larger, % then create a new one between the points % --------------------------------------------------------------------- % Changes from version 1.0.0 to 1.1.0, 3 May 2022: % 1) Increased the cubical neighborhood in the generation of the segments %% Partition the point cloud into cubes Min = double(min([P(:,1:2); Curve0(:,1:2)])); Max = double(max([P(:,1:2); Curve0(:,1:2)])); N = double(ceil((Max-Min)/rball)+5); % cube coordinates of the section points CC = floor([P(:,1)-Min(1) P(:,2)-Min(2)]/rball)+3; % Sorts the points according a lexicographical order S = [CC(:,1) CC(:,2)-1]*[1 N(1)]'; [S,I] = sort(S); % Define "partition" np = size(P,1); partition = cell(N(1),N(2)); p = 1; % The index of the point under comparison while p <= np t = 1; while (p+t <= np) && (S(p) == S(p+t)) t = t+1; end q = I(p); partition{CC(q,1),CC(q,2)} = I(p:p+t-1); p = p+t; end %% Define segments using the previous points % cube coordinates of the seed points: CC = floor([Curve0(:,1)-Min(1) Curve0(:,2)-Min(2)]/rball)+3; I = CC < 3; CC(I) = 3; nc = size(Curve0,1); % number of sets Dist = 1e8*ones(np,1); % distance of point to the closest center SoP = zeros(np,1); % the segment the points belong to Radius = rball^2; for i = 1:nc points = partition(CC(i,1)-2:CC(i,1)+2,CC(i,2)-2:CC(i,2)+2); points = vertcat(points{:}); V = [P(points,1)-Curve0(i,1) P(points,2)-Curve0(i,2)]; dist = sum(V.*V,2); PointsInBall = dist < Radius; points = points(PointsInBall); dist = dist(PointsInBall); D = Dist(points); L = dist < D; I = points(L); Dist(I) = dist(L); SoP(I) = i; end %% Finalise the segments % Number of points in each segment and index of each point in its segment Num = zeros(nc,1); IndPoints = zeros(np,1); for i = 1:np if SoP(i) > 0 Num(SoP(i)) = Num(SoP(i))+1; IndPoints(i) = Num(SoP(i)); end end % Continue if enough non-emtpy segments if nnz(Num) > 0.05*nc % Initialization of the "Seg" Seg = cell(nc,1); for i = 1:nc Seg{i} = zeros(Num(i),1); end % Define the "Seg" for i = 1:np if SoP(i) > 0 Seg{SoP(i),1}(IndPoints(i),1) = i; end end %% Define the new curve points as the average of the segments Curve = zeros(nc,3); % the new boundary curve Empty = false(nc,1); for i = 1:nc S = Seg{i}; if ~isempty(S) Curve(i,:) = mean(P(S,:),1); if norm(Curve(i,:)-Curve0(i,:)) > 1.25*dmax Curve(i,:) = Curve0(i,:); end else Empty(i) = true; end end %% Interpolate for empty segments % For empty segments create points by interpolation from neighboring % non-empty segments if any(Empty) for i = 1:nc if Empty(i) if i > 1 && i < nc k = 0; while i+k <= nc && Empty(i+k) k = k+1; end if i+k <= nc LineEle = Curve(i+k,:)-Curve(i-1,:); else LineEle = Curve(1,:)-Curve(i-1,:); end if k < 5 for j = 1:k Curve(i+j-1,:) = Curve(i-1,:)+j/(k+1)*LineEle; end else Curve(i:i+k-1,:) = Curve0(i:i+k-1,:); end elseif i == 1 a = 0; while Empty(end-a) a = a+1; end b = 1; while Empty(b) b = b+1; end LineEle = Curve(b,:)-Curve(nc-a,:); n = a+b-1; if n < 5 for j = 1:a-1 Curve(nc-a+1+j,:) = Curve(nc-a,:)+j/n*LineEle; end for j = 1:b-1 Curve(j,:) = Curve(nc-a,:)+(j+a-1)/n*LineEle; end else Curve(nc-a+2:nc,1:2) = Curve0(nc-a+2:nc,1:2); Curve(nc-a+2:nc,3) = Curve0(nc-a+2:nc,3); Curve(1:b-1,1:2) = Curve0(1:b-1,1:2); Curve(1:b-1,3) = Curve0(1:b-1,3); end elseif i == nc LineEle = Curve(1,:)-Curve(nc-1,:); Curve(i,:) = Curve(nc-1,:)+0.5*LineEle; end end end end % Correct the height Curve(:,3) = min(Curve(:,3)); % Check self-intersection [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2)); % If self-intersection, try to modify the curve j = 1; while Intersect && j <= 5 n = size(Curve,1); InterLines = (1:1:n)'; NumberOfIntersections = cellfun('length',IntersectLines(:,1)); I = NumberOfIntersections > 0; InterLines = InterLines(I); CrossLen = vertcat(IntersectLines{I,2}); if length(CrossLen) == length(InterLines) LineEle = Curve([2:end 1],:)-Curve(1:end,:); d = sqrt(sum(LineEle.*LineEle,2)); m = length(InterLines); for i = 1:2:m if InterLines(i) ~= n Curve(InterLines(i)+1,:) = Curve(InterLines(i),:)+... 0.9*CrossLen(i)/d(InterLines(i))*LineEle(InterLines(i),:); else Curve(1,:) = Curve(InterLines(i),:)+... 0.9*CrossLen(i)/d(InterLines(i))*LineEle(InterLines(i),:); end end [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2)); j = j+1; else j = 6; end end %% Add new points if too large distances LineEle = Curve([2:end 1],:)-Curve(1:end,:); d = sum(LineEle.*LineEle,2); Large = d > dmax^2; m = nnz(Large); if m > 0 Curve0 = zeros(nc+m,3); Ind = zeros(nc+m,2); t = 0; for i = 1:nc if Large(i) t = t+1; Curve0(t,:) = Curve(i,:); if i < nc Ind(t,:) = [i i+1]; else Ind(t,:) = [i 1]; end t = t+1; Curve0(t,:) = Curve(i,:)+0.5*LineEle(i,:); if i < nc Ind(t,:) = [i+1 0]; else Ind(t,:) = [1 0]; end else t = t+1; Curve0(t,:) = Curve(i,:); if i < nc Ind(t,:) = [i i+1]; else Ind(t,:) = [i 1]; end end end Curve = Curve0; else Ind = [(1:1:nc)' [(2:1:nc)'; 1]]; end %% Remove new points if too small distances nc = size(Curve,1); LineEle = Curve([2:end 1],:)-Curve(1:end,:); d = sum(LineEle.*LineEle,2); Small = d < (0.333*dmax)^2; m = nnz(Small); if m > 0 for i = 1:nc-1 if ~Small(i) && Small(i+1) Ind(i,2) = -1; elseif Small(i) && Small(i+1) Small(i+1) = false; end end if ~Small(nc) && Small(1) Ind(nc,2) = -1; Ind(1,2) = -1; Small(1) = false; Small(nc) = true; I = Ind(:,2) > 0; Ind(2:end,1) = Ind(2:end,1)+1; Ind(I,2) = Ind(I,2)+1; end Ind = Ind(~Small,:); Curve = Curve(~Small,:); end else % If not enough new points, return the old curve Ind = [(1:1:nc)' [(2:1:nc)'; 1]]; Curve = Curve0; end
github
InverseTampere/TreeQSM-master
curve_based_triangulation.m
.m
TreeQSM-master/src/triangulation/curve_based_triangulation.m
16,621
utf_8
0a258bbf13767bf5a6c076d151b6307f
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function triangulation = curve_based_triangulation(P,TriaHeight,TriaWidth) % --------------------------------------------------------------------- % CURVE_BASED_TRIANGULATION.M Reconstructs a triangulation for the % stem-buttress surface based on boundary curves % % Version 1.1.0 % Latest update 3 May 2022 % % Copyright (C) 2015-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Inputs: % P Point cloud of the stem to be triangulated % TriaHeight Height of the triangles % TriaWidth Width of the triangles % % Output: % triangulation Structure field defining the triangulation. Contains % the following main fields: % vert Vertices of the triangulation model (nv x 3)-matrix % facet Facets (triangles) of the triangulation % (the vertices forming the facets) % fvd Color information of the facets for plotting with "patch" % volume Volume enclosed by the facets in liters % bottom The z-coordinate of the bottom of the model % top The z-coordinate of the top of the model % triah TriaHeight % triaw TriaWidth % --------------------------------------------------------------------- % Changes from version 1.0.2 to 1.1.0, 3 May 2022: % 1) Increased the radius of the balls at seed points from TriaWidth to % 2*TriaWidth in the input of "boundary_curve" % 2) Added triangle orientation check after the side is covered with % triangles so that the surface normals are pointing outward % 3) Modified the check if the new boundary curve changes only a little and % then stop reconstruction % 4) Added halving the triangle height if the boundary curve length has % increased three times. % 5) Changed the bottom level from the smallest z-coordinate to the % average of the lowest 100 z-coordinates. % 6) Minor streamlining the code and added more comments % Changes from version 1.0.2 to 1.0.3, 11 Aug 2020: % 1) Small changes in the code when computing the delaunay triangulation % of the top layer % Changes from version 1.0.1 to 1.0.2, 15 Jan 2020: % 1) Added side surface areas (side, top, bottom) to output as fields % Changes from version 1.0.0 to 1.0.1, 26 Nov 2019: % 1) Removed the plotting of the triangulation model at the end of the code %% Determine the first boundary curve np = size(P,1); [~,I] = sort(P(:,3),'descend'); P = P(I,:); Hbot = mean(P(end-100:end,3)); Htop = P(1,3); N = ceil((Htop-Hbot)/TriaHeight); Vert = zeros(1e5,3); Tria = zeros(1e5,3); TriaLay = zeros(1e5,1); VertLay = zeros(1e5,1,'uint16'); Curve = zeros(0,3); i = 0; % the layer whose cross section is under reconstruction ps = 1; while P(ps,3) > Htop-i*TriaHeight ps = ps+1; end pe = ps; while i < N/4 && isempty(Curve) % Define thin horizontal cross section of the stem i = i+1; ps = pe+1; k = 1; while P(ps+k,3) > Htop-i*TriaHeight k = k+1; end pe = ps+k-1; PSection = P(ps:pe,:); % Create initial boundary curve: iter = 0; while iter <= 15 && isempty(Curve) iter = iter+1; Curve = initial_boundary_curve(PSection,TriaWidth); end end if isempty(Curve) triangulation = zeros(0,1); disp(' No triangulation: Problem with the first curve') return end % make the height of the curve even: Curve(:,3) = max(Curve(:,3)); % Save vertices: nv = size(Curve,1); % number of vertices in the curve Vert(1:nv,:) = Curve; VertLay(1:nv) = i; t = 0; m00 = size(Curve,1); %% Determine the other boundary curves and the triangulation downwards i0 = i; i = i0+1; nv0 = 0; LayerBottom = Htop-i*TriaHeight; while i <= N && pe < np %% Define thin horizontal cross section of the stem ps = pe+1; k = 1; while ps+k <= np && P(ps+k,3) > LayerBottom k = k+1; end pe = ps+k-1; PSection = P(ps:pe,:); %% Create boundary curves using the previous curves as seeds if i > i0+1 nv0 = nv1; end % Define seed points: Curve(:,3) = Curve(:,3)-TriaHeight; Curve0 = Curve; % Create new boundary curve [Curve,Ind] = boundary_curve(PSection,Curve,2*TriaWidth,1.5*TriaWidth); if isempty(Curve) disp(' No triangulation: Empty curve') triangulation = zeros(0,1); return end Curve(:,3) = max(Curve(:,3)); %% Check if the curve intersects itself [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2)); %% If self-intersection, try to modify the curve j = 1; while Intersect && j <= 10 n = size(Curve,1); CrossLines = (1:1:n)'; NumberOfIntersections = cellfun('length',IntersectLines(:,1)); I = NumberOfIntersections > 0; CrossLines = CrossLines(I); CrossLen = vertcat(IntersectLines{I,2}); if length(CrossLen) == length(CrossLines) LineEle = Curve([2:end 1],:)-Curve(1:end,:); d = sqrt(sum(LineEle.*LineEle,2)); m = length(CrossLines); for k = 1:2:m if CrossLines(k) ~= n Curve(CrossLines(k)+1,:) = Curve(CrossLines(k),:)+... 0.9*CrossLen(k)/d(CrossLines(k))*LineEle(CrossLines(k),:); else Curve(1,:) = Curve(CrossLines(k),:)+... 0.9*CrossLen(k)/d(CrossLines(k))*LineEle(CrossLines(k),:); end end [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2)); j = j+1; else j = 11; end end m = size(Curve,1); if Intersect %% Curve self-intersects, use previous curve to extrapolate to the bottom H = Curve0(1,3)-Hbot; if H > 0.75 && Intersect triangulation = zeros(0,1); disp([' No triangulation: Self-intersection at ',... num2str(H),' m from the bottom']) return end Curve = Curve0; Curve(:,3) = Curve(:,3)-TriaHeight; Nadd = floor(H/TriaHeight)+1; m = size(Curve,1); Ind = [(1:1:m)' [(2:1:m)'; 1]]; T = H/Nadd; for k = 1:Nadd if k > 1 Curve(:,3) = Curve(:,3)-T; end Vert(nv+1:nv+m,:) = Curve; VertLay(nv+1:nv+m) = i; %% Define the triangulation between two boundary curves nv1 = nv; nv = nv+m; t0 = t+1; pass = false; for j = 1:m if Ind(j,2) > 0 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,:)]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+j+1]; elseif Ind(j,2) > 0 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,:)]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+1]; elseif Ind(j,2) == 0 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+j+1]; elseif Ind(j,2) == 0 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+1]; elseif j == 1 && Ind(j,2) == -1 t = t+1; Tria(t,:) = [nv nv1 nv0+1]; t = t+1; Tria(t,:) = [nv nv0+1 nv1+1]; t = t+1; Tria(t,:) = [nv0+1 nv0+2 nv1+1]; t = t+1; Tria(t,:) = [nv1+1 nv0+2 nv0+3]; t = t+1; Tria(t,:) = [nv1+1 nv0+3 nv1+2]; pass = true; elseif Ind(j,2) == -1 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+j+1]; t = t+1; Tria(t,:) = [nv0+Ind(j,1)+1 nv0+Ind(j,1)+2 nv1+j+1]; elseif Ind(j,2) == -1 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+1]; t = t+1; Tria(t,:) = [nv0+Ind(j,1)+1 nv0+1 nv1+1]; end end TriaLay(t0:t) = i; i = i+1; nv0 = nv1; end i = N+1; else %% No self-intersection, proceed with triangulation and new curves Vert(nv+1:nv+m,:) = Curve; VertLay(nv+1:nv+m) = i; %% If little change between Curve and Curve0, stop the reconstruction C = intersect(Curve0,Curve,"rows"); if size(C,1) > 0.7*size(Curve,1) N = i; end %% If the boundary curve has grown much longer than originally, then % decrease the triangle height if m > 3*m00 TriaHeight = TriaHeight/2; % use half the height N = N+ceil((N-i)/2); % update the number of layers m00 = m; end %% Define the triangulation between two boundary curves nv1 = nv; nv = nv+m; t0 = t+1; pass = false; for j = 1:m if Ind(j,2) > 0 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,:)]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+j+1]; elseif Ind(j,2) > 0 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,:)]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+1]; elseif Ind(j,2) == 0 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+j+1]; elseif Ind(j,2) == 0 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+1]; elseif j == 1 && Ind(j,2) == -1 t = t+1; Tria(t,:) = [nv nv1 nv0+1]; t = t+1; Tria(t,:) = [nv nv0+1 nv1+1]; t = t+1; Tria(t,:) = [nv0+1 nv0+2 nv1+1]; t = t+1; Tria(t,:) = [nv1+1 nv0+2 nv0+3]; t = t+1; Tria(t,:) = [nv1+1 nv0+3 nv1+2]; pass = true; elseif Ind(j,2) == -1 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+j+1]; t = t+1; Tria(t,:) = [nv0+Ind(j,1)+1 nv0+Ind(j,1)+2 nv1+j+1]; elseif Ind(j,2) == -1 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+1]; t = t+1; Tria(t,:) = [nv0+Ind(j,1)+1 nv0+1 nv1+1]; end end TriaLay(t0:t) = i; i = i+1; LayerBottom = LayerBottom-TriaHeight; end end Vert = Vert(1:nv,:); VertLay = VertLay(1:nv); Tria = Tria(1:t,:); TriaLay = TriaLay(1:t); %% Check the orientation of the triangles % so that surface normals are outward pointing a = round(t/10); % select the top triangles U = Vert(Tria(1:a,2),:)-Vert(Tria(1:a,1),:); V = Vert(Tria(1:a,3),:)-Vert(Tria(1:a,1),:); Center = mean(Vert(1:nv-1,:)); % the center of the stem C = Vert(Tria(1:a,1),:)+0.25*V+0.25*U; W = C(:,1:2)-Center(1:2); % vectors from the triagles to the stem's center Normals = cross(U,V); if nnz(sum(Normals(:,1:2).*W,2) < 0) > 0.5*length(C) Tria(1:t,1:2) = [Tria(1:t,2) Tria(1:t,1)]; end % U = Vert(Tria(1:t,2),:)-Vert(Tria(1:t,1),:); % V = Vert(Tria(1:t,3),:)-Vert(Tria(1:t,1),:); % Normals = cross(U,V); % Normals = normalize(Normals); % C = Vert(Tria(1:t,1),:)+0.25*V+0.25*U; % fvd = ones(t,1); % figure(5) % point_cloud_plotting(P(1,:),5,6) % patch('Vertices',Vert,'Faces',Tria,'FaceVertexCData',fvd,'FaceColor','flat') % alpha(1) % hold on % arrow_plot(C,0.1*Normals,5) % hold off % axis equal % pause %% Remove possible double triangles nt = size(Tria,1); Keep = true(nt,1); Scoord = Vert(Tria(:,1),:)+Vert(Tria(:,2),:)+Vert(Tria(:,3),:); S = sum(Scoord,2); [part,CC] = cubical_partition(Scoord,2*TriaWidth); for j = 1:nt-1 if Keep(j) points = part(CC(j,1)-1:CC(j,1)+1,CC(j,2)-1:CC(j,2)+1,CC(j,3)-1:CC(j,3)+1); points = vertcat(points{:}); I = S(j) == S(points); J = points ~= j; I = I&J&Keep(points); if any(I) p = points(I); I = intersect(Tria(j,:),Tria(p,:)); if length(I) == 3 Keep(p) = false; end end end end Tria = Tria(Keep,:); TriaLay = TriaLay(Keep); %% Generate triangles for the horizontal layers and compute the volumes % Triangles of the ground layer % Select the boundary curve: N = double(max(VertLay)); I = VertLay == N; Vert(I,3) = Hbot; ind = (1:1:nv)'; ind = ind(I); Curve = Vert(I,:); % Boundary curve of the bottom n = size(Curve,1); if n < 10 triangulation = zeros(0,1); disp(' No triangulation: Ground layer boundary curve too small') return end % Define Delaunay triangulation for the bottom C = zeros(n,2); C(:,1) = (1:1:n)'; C(1:n-1,2) = (2:1:n)'; C(n,2) = 1; warning off dt = delaunayTriangulation(Curve(:,1),Curve(:,2),C); In = dt.isInterior(); GroundTria = dt(In,:); Points = dt.Points; warning on if size(Points,1) > size(Curve,1) disp(' No triangulation: Problem with delaunay in the bottom layer') triangulation = zeros(0,1); return end GroundTria0 = GroundTria; GroundTria(:,1) = ind(GroundTria(:,1)); GroundTria(:,2) = ind(GroundTria(:,2)); GroundTria(:,3) = ind(GroundTria(:,3)); % Compute the normals and areas U = Curve(GroundTria0(:,2),:)-Curve(GroundTria0(:,1),:); V = Curve(GroundTria0(:,3),:)-Curve(GroundTria0(:,1),:); Cg = Curve(GroundTria0(:,1),:)+0.25*V+0.25*U; Ng = cross(U,V); I = Ng(:,3) > 0; % Check orientation Ng(I,:) = -Ng(I,:); Ag = 0.5*sqrt(sum(Ng.*Ng,2)); Ng = 0.5*[Ng(:,1)./Ag Ng(:,2)./Ag Ng(:,3)./Ag]; % Remove possible negative area triangles: I = Ag > 0; Ag = Ag(I); Cg = Cg(I,:); Ng = Ng(I,:); GroundTria = GroundTria(I,:); % Update the triangles: Tria = [Tria; GroundTria]; TriaLay = [TriaLay; (N+1)*ones(size(GroundTria,1),1)]; if abs(sum(Ag)-polyarea(Curve(:,1),Curve(:,2))) > 0.001*sum(Ag) disp(' No triangulation: Problem with delaunay in the bottom layer') triangulation = zeros(0,1); return end % Triangles of the top layer % Select the top curve: N = double(min(VertLay)); I = VertLay == N; ind = (1:1:nv)'; ind = ind(I); Curve = Vert(I,:); CenterTop = mean(Curve); % Delaunay triangulation of the top: n = size(Curve,1); C = zeros(n,2); C(:,1) = (1:1:n)'; C(1:n-1,2) = (2:1:n)'; C(n,2) = 1; warning off dt = delaunayTriangulation(Curve(:,1),Curve(:,2),C); Points = dt.Points; warning on if min(size(dt)) == 0 || size(Points,1) > size(Curve,1) disp(' No triangulation: Problem with delaunay in the top layer') triangulation = zeros(0,1); return end In = dt.isInterior(); TopTria = dt(In,:); TopTria0 = TopTria; TopTria(:,1) = ind(TopTria(:,1)); TopTria(:,2) = ind(TopTria(:,2)); TopTria(:,3) = ind(TopTria(:,3)); % Compute the normals and areas: U = Curve(TopTria0(:,2),:)-Curve(TopTria0(:,1),:); V = Curve(TopTria0(:,3),:)-Curve(TopTria0(:,1),:); Ct = Curve(TopTria0(:,1),:)+0.25*V+0.25*U; Nt = cross(U,V); I = Nt(:,3) < 0; Nt(I,:) = -Nt(I,:); At = 0.5*sqrt(sum(Nt.*Nt,2)); Nt = 0.5*[Nt(:,1)./At Nt(:,2)./At Nt(:,3)./At]; % Remove possible negative area triangles: I = At > 0; At = At(I); Ct = Ct(I,:); Nt = Nt(I,:); TopTria = TopTria(I,:); % Update the triangles: Tria = [Tria; TopTria]; TriaLay = [TriaLay; N*ones(size(TopTria,1),1)]; if abs(sum(At)-polyarea(Curve(:,1),Curve(:,2))) > 0.001*sum(At) disp(' No triangulation: Problem with delaunay in the top layer') triangulation = zeros(0,1); return end % Triangles of the side B = TriaLay <= max(VertLay) & TriaLay > 1; U = Vert(Tria(B,2),:)-Vert(Tria(B,1),:); V = Vert(Tria(B,3),:)-Vert(Tria(B,1),:); Cs = Vert(Tria(B,1),:)+0.25*V+0.25*U; Ns = cross(U,V); As = 0.5*sqrt(sum(Ns.*Ns,2)); Ns = 0.5*[Ns(:,1)./As Ns(:,2)./As Ns(:,3)./As]; I = As > 0; Ns = Ns(I,:); As = As(I); Cs = Cs(I,:); % Volumes in liters VTotal = sum(At.*sum(Ct.*Nt,2))+sum(As.*sum(Cs.*Ns,2))+sum(Ag.*sum(Cg.*Ng,2)); VTotal = round(10000*VTotal/3)/10; if VTotal < 0 disp(' No triangulation: Problem with volume') triangulation = zeros(0,1); return end V = Vert(Tria(:,1),1:2)-CenterTop(1:2); fvd = sqrt(sum(V.*V,2)); triangulation.vert = single(Vert); triangulation.facet = uint16(Tria); triangulation.fvd = single(fvd); triangulation.volume = VTotal; triangulation.SideArea = sum(As); triangulation.BottomArea = sum(Ag); triangulation.TopArea = sum(At); triangulation.bottom = min(Vert(:,3)); triangulation.top = max(Vert(:,3)); triangulation.triah = TriaHeight; triangulation.triaw = TriaWidth; % figure(5) % point_cloud_plotting(P,5,6) % patch('Vertices',Vert,'Faces',Tria,'FaceVertexCData',fvd,'FaceColor','flat') % % hold on % % arrow_plot(Cs,0.2*Ns,5) % % hold off % % axis equal % alpha(1)
github
InverseTampere/TreeQSM-master
check_self_intersection.m
.m
TreeQSM-master/src/triangulation/check_self_intersection.m
6,103
utf_8
28cf4603e614bcb3a761c35f28e1964f
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [Intersect,IntersectLines] = check_self_intersection(Curve) % The function takes in a curve (the coordinates of the vertices, in the % right order) and checks if the curve intersects itself % % Outputs: % Intersect Logical value indicating if the curve self-intersects % IntersectLines Cell array containing for each line element which are % the intersecting elements and how far away along % the line the intersection point is if ~isempty(Curve) dim = size(Curve,2); % two or three dimensional curve n = size(Curve,1); % number of points in the curve V = Curve([(2:n)'; 1],:)-Curve; % line elements forming the curve L = sqrt(sum(V.*V,2)); % the lengths of the line elements i = 1; % the line element under inspection Ind = (1:1:n)'; % indexes of the line elements if dim == 2 % 2d curves % directions (unit vectors) of the line elements: DirLines = [1./L.*V(:,1) 1./L.*V(:,2)]; Intersect = false; if nargout == 1 % check only if the curve intersects while i <= n-1 && ~Intersect % Select the line elements that can intersect element i if i > 1 I = Ind > i+1 | Ind < i-1; else I = Ind > i+1 & Ind < n; end ind = Ind(I)'; for j = ind % Solve for the crossing points of every line element A = [DirLines(j,:)' -DirLines(i,:)']; b = Curve(i,:)'-Curve(j,:)'; Ainv = 1/(A(1,1)*A(2,2)-A(1,2)*A(2,1))*[A(2,2) -A(1,2); -A(2,1) A(1,1)]; x = Ainv*b; % signed length along the line elements to the crossing if x(1) >= 0 && x(1) <= L(j) && x(2) >= 0 && x(2) <= L(i) Intersect = true; end end i = i+1; % study the next line element end else % determine also all intersection points (line elements) IntersectLines = cell(n,2); for i = 1:n-1 % Select the line elements that can intersect element i if i > 1 I = Ind > i+1 | Ind < i-1; else I = Ind > i+1 & Ind < n; end ind = Ind(I)'; for j = ind % Solve for the crossing points of every line element A = [DirLines(j,:)' -DirLines(i,:)']; b = Curve(i,:)'-Curve(j,:)'; Ainv = 1/(A(1,1)*A(2,2)-A(1,2)*A(2,1))*[A(2,2) -A(1,2); -A(2,1) A(1,1)]; x = Ainv*b; if x(1) >= 0 && x(1) <= L(j) && x(2) >= 0 && x(2) <= L(i) Intersect = true; % which line elements cross element i: IntersectLines{i,1} = [IntersectLines{i,1}; j]; % which line elements cross element j: IntersectLines{j,1} = [IntersectLines{j,1}; i]; % distances along element i to intersection points: IntersectLines{i,2} = [IntersectLines{i,2}; x(1)]; % distances along element j to intersection points: IntersectLines{j,2} = [IntersectLines{j,2}; x(2)]; end end end % remove possible multiple values for i = 1:n IntersectLines{i,1} = unique(IntersectLines{i,1}); IntersectLines{i,2} = min(IntersectLines{i,2}); end end elseif dim == 3 % 3d curves % directions (unit vectors) of the line elements DirLines = [1./L.*V(:,1) 1./L.*V(:,2) 1./L.*V(:,3)]; Intersect = false; if nargout == 1 % check only if the curve intersects while i <= n-1 % Select the line elements that can intersect element i if i > 1 I = Ind > i+1 | Ind < i-1; else I = Ind > i+1 & Ind < n; end % Solve for possible intersection points [~,DistOnRay,DistOnLines] = distances_between_lines(... Curve(i,:),DirLines(i,:),Curve(I,:),DirLines(I,:)); if any(DistOnRay >= 0 & DistOnRay <= L(i) &... DistOnLines > 0 & DistOnLines <= L(I)) Intersect = true; i = n; else i = i+1; % study the next line element end end else % determine also all intersection points (line elements) IntersectLines = cell(n,2); for i = 1:n-1 % Select the line elements that can intersect element i if i > 1 I = Ind > i+1 | Ind < i-1; else I = Ind > i+1 & Ind < n; end % Solve for possible intersection points [D,DistOnRay,DistOnLines] = distances_between_lines(... Curve(i,:),DirLines(i,:),Curve(I,:),DirLines(I,:)); if any(DistOnRay >= 0 & DistOnRay <= L(i) & ... DistOnLines > 0 & DistOnLines <= L(I)) Intersect = true; J = DistOnRay >= 0 & DistOnRay <= L(i) & ... DistOnLines > 0 & DistOnLines <= L(I); ind = Ind(I); ind = ind(J); DistOnLines = DistOnLines(J); IntersectLines{i,1} = ind; IntersectLines{i,2} = DistOnRay(J); % Record the elements intersecting for j = 1:length(ind) IntersectLines{ind(j),1} = [IntersectLines{ind(j),1}; i]; IntersectLines{ind(j),2} = [IntersectLines{ind(j),2}; DistOnLines(j)]; end end end % remove possible multiple values for i = 1:n IntersectLines{i} = unique(IntersectLines{i}); IntersectLines{i,2} = min(IntersectLines{i,2}); end end end else % Empty curve Intersect = false; IntersectLines = cell(1,1); end
github
InverseTampere/TreeQSM-master
branches.m
.m
TreeQSM-master/src/main_steps/branches.m
4,480
utf_8
e5a63f1d1e99bdd56ea657a41c8df921
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function branch = branches(cylinder) % --------------------------------------------------------------------- % BRANCHES.M Determines the branching structure and computes branch % attributes % % Version 3.0.0 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Determines the branches (cylinders in a segment define a branch), their order % and topological parent-child-relation. Branch number one is the trunk and % its order is zero. Notice that branch number does not tell its age in the % sense that branch number two would be the oldest branch and the number % three the second oldest. % % Inputs: % cylinder Cylinders, structure array % % Outputs: % branch Branch structure array, contains fields: % Branch order, parent, volume, length, angle, height, azimuth % and diameter % --------------------------------------------------------------------- % Changes from version 2.1.0 to 3.0.0, 2 May 2022: % 1) Changed the code such that the input "segment" and output "cylinder" % are not needed anymore, which simplified the code in many places. % Cylinder info is now computed in "cylinders" function. % Changes from version 2.0.0 to 2.1.0, 25 Jan 2020: % 1) Chanced the coding to simplify and shorten the code % 2) Added branch area and zenith direction as new fields in the % branch-structure array % 3) Removed the line were 'ChildCyls' and'CylsInSegment' fields are % removed from the cylinder-structure array Rad = cylinder.radius; Len = cylinder.length; Axe = cylinder.axis; %% Branches nc = size(Rad,1); % number of cylinder ns = max(cylinder.branch); % number of segments BData = zeros(ns,9); % branch ord, dia, vol, are, len, ang, hei, azi, zen ind = (1:1:nc)'; CiB = cell(ns,1); for i = 1:ns C = ind(cylinder.branch == i); CiB{i} = C; if ~isempty(C) BData(i,1) = cylinder.BranchOrder(C(1)); % branch order BData(i,2) = 2*Rad(C(1)); % branch diameter BData(i,3) = 1000*pi*sum(Len(C).*Rad(C).^2); % branch volume BData(i,4) = 2*pi*sum(Len(C).*Rad(C)); % branch area BData(i,5) = sum(Len(C)); % branch length % if the first cylinder is added to fill a gap, then % use the second cylinder to compute the angle: if cylinder.added(C(1)) && length(C) > 1 FC = C(2); % first cyl in the branch PC = cylinder.parent(C(1)); % parent cylinder of the branch else FC = C(1); PC = cylinder.parent(FC); end if PC > 0 BData(i,6) = 180/pi*acos(Axe(FC,:)*Axe(PC,:)'); % branch angle end BData(i,7) = cylinder.start(C(1),3)-cylinder.start(1,3); % branch height BData(i,8) = 180/pi*atan2(Axe(C(1),2),Axe(C(1),1)); % branch azimuth BData(i,9) = 180/pi*acos(Axe(C(1),3)); % branch zenith end end BData = single(BData); %% Branching structure (topology, parent-child-relation) branch.order = uint8(BData(:,1)); BPar = zeros(ns,1); Chi = cell(nc,1); for i = 1:nc c = ind(cylinder.parent == i); c = c(c ~= cylinder.extension(i)); Chi{i} = c; end for i = 1:ns C = CiB{i}; ChildCyls = unique(vertcat(Chi{C})); CB = unique(cylinder.branch(ChildCyls)); % Child branches BPar(CB) = i; end if ns <= 2^16 branch.parent = uint16(BPar); else branch.parent = uint32(BPar); end %% Finish the definition of branch branch.diameter = BData(:,2); % diameters in meters branch.volume = BData(:,3); % volumes in liters branch.area = BData(:,4); % areas in square meters branch.length = BData(:,5); % lengths in meters branch.angle = BData(:,6); % angles in degrees branch.height = BData(:,7); % heights in meters branch.azimuth = BData(:,8); % azimuth directions in angles branch.zenith = BData(:,9); % zenith directions in angles
github
InverseTampere/TreeQSM-master
tree_data.m
.m
TreeQSM-master/src/main_steps/tree_data.m
31,615
utf_8
29dd42794f0a3a84a3855ab686bba020
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [treedata,triangulation] = tree_data(cylinder,branch,trunk,inputs) % --------------------------------------------------------------------- % TREE_DATA.M Calculates some tree attributes from cylinder QSM. % % Version 3.0.1 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Inputs: % cylinder: % radius (Rad) Radii of the cylinders % length (Len) Lengths of the cylinders % start (Sta) Starting points of the cylinders % axis (Axe) Axes of the cylinders % branch: % order (BOrd) Branch order data % volume (BVol) Branch volume data % length (BLen) Branch length data % trunk Point cloud of the trunk % inputs Input structure, defines if results are displayed and % plotted and if triangulation results are computed % % Output: % treedata Tree data/attributes in a struct % --------------------------------------------------------------------- % Changes from version 3.0.0 to 3.0.1, 2 May 2022: % 1) Small changes in "crown_measures" when computing crown base to prevent % errors in special cases. % 2) Small change for how to compute the "first major branch" in % "triangulate_stem". % 3) Modified code so that "n" cannot be empty in "branch_distribution" and % cause warning % 4) Decreased the minimum triangle sizes in "triangulate_stem" % 5) The triangulation code has some changes. % 6) Minor streamlining of the code % Changes from version 2.0.2 to 3.0.0, 13 Feb 2020: % 1) Changed the setup for triangulation: % - The size of the triangles is more dependent on the dbh % - The height of the stem section is defined up to the first major branch % (branch diameter > 0.1*dbh or maximum branch diameter) but keeping % the stem diameter above 25% of dbh. % 2) Makes now more tries for triangulation, also changes triangle size % and the length of the stem section if necessary. % 3) Changed the names of some fields in the output: % - VolumeCylDiam --> VolCylDia % - LengthCylDiam --> LenCylDia % - VolumeBranchOrder --> VolBranchOrd % - LengthBranchOrder --> LenBranchOrd % - NumberBranchOrder --> NumBranchOrd % 3) Added many new fields into the output treedata, particularly distributions: % - Total length (trunk length + branch length) ("TotalLength") % - Trunk area and branch area ("TrunkArea" and "BranchArea") % - Crown dimensions: "CrownDiamAve", "CrownDiamMax","CrownAreaConv", % "CrownAreaAlpha", "CrownBaseHeight", "CrownLength", "CrownRatio", % "CrownVolumeConv", "CrownVolumeAlpha". % - Vertical tree profile "VerticalProfile" and tree diameters in % 18 directions at 20 height layers "spreads". % - Branch area as functions of diameter class and branch order % ("AreCylDia" and "AreBranchOrd") % - Volume, area and length of CYLINDERS (tree segments) in 1 meter % HEIGHT classes ("VolCylHei", "AreCylHei", "LenCylHei") % - Volume, area and length of CYLINDERS (tree segments) in 10 deg % ZENITH DIRECTION classes ("VolCylZen", "AreCylZen", "LenCylZen") % - Volume, area and length of CYLINDERS (tree segments) in 10 deg % AZIMUTH DIRECTION classes ("VolCylAzi", "AreCylAzi", "LenCylAzi") % - Volume, area, length and number of all and 1st-order BRANCHES % in 1 cm DIAMETER classes ("AreBranchDia", "AreBranch1Dia", etc.) % - Volume, area, length and number of all and 1st-order BRANCHES % in 1 meter HEIGHT classes ("AreBranchDia", "AreBranch1Dia", etc.) % - Volume, area, length and number of all and 1st-order BRANCHES % in 10 degree BRANCHING ANGLE classes % ("AreBranchAng", "AreBranch1Ang", etc.) % - Volume, area, length and number of all and 1st-order BRANCHES % in 22.5 degree branch AZIMUTH ANGLE classes % ("AreBranchAzi", "AreBranch1Azi", etc.) % - Volume, area, length and number of all and 1st-order BRANCHES % in 10 degree branch ZENITH ANGLE classes % ("AreBranchZen", "AreBranch1Zen", etc.) % 4) Added new area-related fields into the output triangulation: % - side area, top area and bottom area % 5) Added new triangulation related fields to the output treedata: % - TriaTrunkArea side area of the triangulation % - MixTrunkArea trunk area from triangulation and cylinders % - MixTotalArea total area where the MixTrunkArea used instead % of TrunkArea % 6) Structure has more subfunctions. % 7) Changed the coding for cylinder fitting of DBH to conform new output % of the least_square_cylinder. % Changes from version 2.0.1 to 2.0.2, 26 Nov 2019: % 1) Bug fix: Added a statement "C < nc" for a while command that makes sure % that the index "C" does not exceed the number of stem cylinders, when % determining the index of cylinders up to first branch. % 2) Bug fix: Changed "for i = 1:BO" to "for i = 1:max(1,BO)" where % computing branch order data. % 3) Added the plotting of the triangulation model % Changes from version 2.0.0 to 2.0.1, 9 Oct 2019: % 1) Bug fix: Changed the units (from 100m to 1m) for computing the branch % length distribution: branch length per branch order. % Define some variables from cylinder: Rad = cylinder.radius; Len = cylinder.length; nc = length(Rad); ind = (1:1:nc)'; Trunk = cylinder.branch == 1; % Trunk cylinders %% Tree attributes from cylinders % Volumes, areas, lengths, branches treedata.TotalVolume = 1000*pi*Rad.^2'*Len; treedata.TrunkVolume = 1000*pi*Rad(Trunk).^2'*Len(Trunk); treedata.BranchVolume = 1000*pi*Rad(~Trunk).^2'*Len(~Trunk); bottom = min(cylinder.start(:,3)); [top,i] = max(cylinder.start(:,3)); if cylinder.axis(i,3) > 0 top = top+Len(i)*cylinder.axis(i,3); end treedata.TreeHeight = top-bottom; treedata.TrunkLength = sum(Len(Trunk)); treedata.BranchLength = sum(Len(~Trunk)); treedata.TotalLength = treedata.TrunkLength+treedata.BranchLength; NB = length(branch.order)-1; % number of branches treedata.NumberBranches = NB; BO = max(branch.order); % maximum branch order treedata.MaxBranchOrder = BO; treedata.TrunkArea = 2*pi*sum(Rad(Trunk).*Len(Trunk)); treedata.BranchArea = 2*pi*sum(Rad(~Trunk).*Len(~Trunk)); treedata.TotalArea = 2*pi*sum(Rad.*Len); %% Diameter at breast height (dbh) % Dbh from the QSM and from a cylinder fitted particularly to the correct place treedata = dbh_cylinder(treedata,trunk,Trunk,cylinder,ind); %% Crown measures,Vertical profile and spreads [treedata,spreads] = crown_measures(treedata,cylinder,branch); %% Trunk volume and DBH from triangulation if inputs.Tria [treedata,triangulation] = triangulate_stem(... treedata,cylinder,branch,trunk); else triangulation = 0; end %% Tree Location treedata.location = cylinder.start(1,:); %% Stem taper R = Rad(Trunk); n = length(R); Taper = zeros(n+1,2); Taper(1,2) = 2*R(1); Taper(2:end,1) = cumsum(Len(Trunk)); Taper(2:end,2) = [2*R(2:end); 2*R(n)]; treedata.StemTaper = Taper'; %% Vertical profile and spreads treedata.VerticalProfile = mean(spreads,2); treedata.spreads = spreads; %% CYLINDER DISTRIBUTIONS: %% Wood part diameter distributions % Volume, area and length of wood parts as functions of cylinder diameter % (in 1cm diameter classes) treedata = cylinder_distribution(treedata,cylinder,'Dia'); %% Wood part height distributions % Volume, area and length of cylinders as a function of height % (in 1 m height classes) treedata = cylinder_height_distribution(treedata,cylinder,ind); %% Wood part zenith direction distributions % Volume, area and length of wood parts as functions of cylinder zenith % direction (in 10 degree angle classes) treedata = cylinder_distribution(treedata,cylinder,'Zen'); %% Wood part azimuth direction distributions % Volume, area and length of wood parts as functions of cylinder zenith % direction (in 10 degree angle classes) treedata = cylinder_distribution(treedata,cylinder,'Azi'); %% BRANCH DISTRIBUTIONS: %% Branch order distributions % Volume, area, length and number of branches as a function of branch order treedata = branch_order_distribution(treedata,branch); %% Branch diameter distributions % Volume, area, length and number of branches as a function of branch diameter % (in 1cm diameter classes) treedata = branch_distribution(treedata,branch,'Dia'); %% Branch height distribution % Volume, area, length and number of branches as a function of branch height % (in 1 meter classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Hei'); %% Branch angle distribution % Volume, area, length and number of branches as a function of branch angle % (in 10 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Ang'); %% Branch azimuth distribution % Volume, area, length and number of branches as a function of branch azimuth % (in 22.5 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Azi'); %% Branch zenith distribution % Volume, area, length and number of branches as a function of branch zenith % (in 10 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Zen'); %% change into single-format Names = fieldnames(treedata); n = size(Names,1); for i = 1:n treedata.(Names{i}) = single(treedata.(Names{i})); end if inputs.disp == 2 %% Generate units for displaying the treedata Units = zeros(n,3); for i = 1:n if ~inputs.Tria && strcmp(Names{i},'CrownVolumeAlpha') m = i; elseif inputs.Tria && strcmp(Names{i},'TriaTrunkLength') m = i; end if strcmp(Names{i}(1:3),'DBH') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'ume') Units(i,:) = 'L '; elseif strcmp(Names{i}(end-2:end),'ght') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'gth') Units(i,:) = 'm '; elseif strcmp(Names{i}(1:3),'vol') Units(i,:) = 'L '; elseif strcmp(Names{i}(1:3),'len') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'rea') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(1:3),'loc') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-4:end),'aConv') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-5:end),'aAlpha') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-4:end),'eConv') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-5:end),'eAlpha') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-2:end),'Ave') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'Max') Units(i,:) = 'm '; end end %% Display treedata disp('------------') disp(' Tree attributes:') for i = 1:m v = change_precision(treedata.(Names{i})); if strcmp(Names{i},'DBHtri') disp(' -----') disp(' Tree attributes from triangulation:') end disp([' ',Names{i},' = ',num2str(v),' ',Units(i,:)]) end disp(' -----') end if inputs.plot > 1 %% Plot distributions figure(6) subplot(2,4,1) plot(Taper(:,1),Taper(:,2),'-b') title('Stem taper') xlabel('Distance from base (m)') ylabel('Diameter (m)') axis tight grid on Q.treedata = treedata; subplot(2,4,2) plot_distribution(Q,6,0,0,'VolCylDia') subplot(2,4,3) plot_distribution(Q,6,0,0,'AreCylDia') subplot(2,4,4) plot_distribution(Q,6,0,0,'LenCylDia') subplot(2,4,5) plot_distribution(Q,6,0,0,'VolBranchOrd') subplot(2,4,6) plot_distribution(Q,6,0,0,'LenBranchOrd') subplot(2,4,7) plot_distribution(Q,6,0,0,'AreBranchOrd') subplot(2,4,8) plot_distribution(Q,6,0,0,'NumBranchOrd') figure(7) subplot(3,3,1) plot_distribution(Q,7,0,0,'VolCylHei') subplot(3,3,2) plot_distribution(Q,7,0,0,'AreCylHei') subplot(3,3,3) plot_distribution(Q,7,0,0,'LenCylHei') subplot(3,3,4) plot_distribution(Q,7,0,0,'VolCylZen') subplot(3,3,5) plot_distribution(Q,7,0,0,'AreCylZen') subplot(3,3,6) plot_distribution(Q,7,0,0,'LenCylZen') subplot(3,3,7) plot_distribution(Q,7,0,0,'VolCylAzi') subplot(3,3,8) plot_distribution(Q,7,0,0,'AreCylAzi') subplot(3,3,9) plot_distribution(Q,7,0,0,'LenCylAzi') figure(8) subplot(3,4,1) %if %%%%%% !!!!!!!! plot_distribution(Q,8,1,0,'VolBranchDia','VolBranch1Dia') subplot(3,4,2) plot_distribution(Q,8,1,0,'AreBranchDia','AreBranch1Dia') subplot(3,4,3) plot_distribution(Q,8,1,0,'LenBranchDia','LenBranch1Dia') subplot(3,4,4) plot_distribution(Q,8,1,0,'NumBranchDia','NumBranch1Dia') subplot(3,4,5) plot_distribution(Q,8,1,0,'VolBranchHei','VolBranch1Hei') subplot(3,4,6) plot_distribution(Q,8,1,0,'AreBranchHei','AreBranch1Hei') subplot(3,4,7) plot_distribution(Q,8,1,0,'LenBranchHei','LenBranch1Hei') subplot(3,4,8) plot_distribution(Q,8,1,0,'NumBranchHei','NumBranch1Hei') subplot(3,4,9) plot_distribution(Q,8,1,0,'VolBranchAng','VolBranch1Ang') subplot(3,4,10) plot_distribution(Q,8,1,0,'AreBranchAng','AreBranch1Ang') subplot(3,4,11) plot_distribution(Q,8,1,0,'LenBranchAng','LenBranch1Ang') subplot(3,4,12) plot_distribution(Q,8,1,0,'NumBranchAng','NumBranch1Ang') figure(9) subplot(2,4,1) plot_distribution(Q,9,1,0,'VolBranchZen','VolBranch1Zen') subplot(2,4,2) plot_distribution(Q,9,1,0,'AreBranchZen','AreBranch1Zen') subplot(2,4,3) plot_distribution(Q,9,1,0,'LenBranchZen','LenBranch1Zen') subplot(2,4,4) plot_distribution(Q,9,1,0,'NumBranchZen','NumBranch1Zen') subplot(2,4,5) plot_distribution(Q,9,1,0,'VolBranchAzi','VolBranch1Azi') subplot(2,4,6) plot_distribution(Q,9,1,0,'AreBranchAzi','AreBranch1Azi') subplot(2,4,7) plot_distribution(Q,9,1,0,'LenBranchAzi','LenBranch1Azi') subplot(2,4,8) plot_distribution(Q,9,1,0,'NumBranchAzi','NumBranch1Azi') end end % End of main function function treedata = dbh_cylinder(treedata,trunk,Trunk,cylinder,ind) % Dbh from the QSM i = 1; n = nnz(Trunk); T = ind(Trunk); while i < n && sum(cylinder.length(T(1:i))) < 1.3 i = i+1; end DBHqsm = 2*cylinder.radius(T(i)); treedata.DBHqsm = DBHqsm; % Determine DBH from cylinder fitted particularly to the correct place % Select the trunk point set V = trunk-cylinder.start(1,:); h = V*cylinder.axis(1,:)'; I = h < 1.5; J = h > 1.1; I = I&J; if nnz(I) > 100 T = trunk(I,:); % Fit cylinder cyl0 = select_cylinders(cylinder,i); cyl = least_squares_cylinder(T,cyl0); RadiusOK = 2*cyl.radius > 0.8*DBHqsm & 2*cyl.radius < 1.2*DBHqsm; if RadiusOK && abs(cylinder.axis(i,:)*cyl.axis') > 0.9 && cyl.conv && cyl.rel treedata.DBHcyl = 2*cyl.radius; else treedata.DBHcyl = DBHqsm; end else treedata.DBHcyl = DBHqsm; end % End of function end function [treedata,spreads] = crown_measures(treedata,cylinder,branch) %% Generate point clouds from the cylinder model Axe = cylinder.axis; Len = cylinder.length; Sta = cylinder.start; Tip = Sta+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; % tips of the cylinders nc = length(Len); P = zeros(5*nc,3); % four mid points on the cylinder surface t = 0; for i = 1:nc [U,V] = orthonormal_vectors(Axe(i,:)); U = cylinder.radius(i)*U; if cylinder.branch(i) == 1 % For stem cylinders generate more points R = rotation_matrix(Axe(i,:),pi/12); for k = 1:4 M = Sta(i,:)+k/4*Len(i)*Axe(i,:); for j = 1:12 if j > 1 U = R*U; end t = t+1; P(t,:) = M+U'; end end else M = Sta(i,:)+0.5*Len(i)*Axe(i,:); R = rotation_matrix(Axe(i,:),pi/4); for j = 1:4 if j > 1 U = R*U; end t = t+1; P(t,:) = M+U'; end end end P = P(1:t,:); I = ~isnan(P(:,1)); P = P(I,:); P = double([P; Sta; Tip]); P = unique(P,'rows'); %% Vertical profiles (layer diameters/spreads), mean: bot = min(P(:,3)); top = max(P(:,3)); Hei = top-bot; if Hei > 10 m = 20; elseif Hei > 2 m = 10; else m = 5; end spreads = zeros(m,18); for j = 1:m I = P(:,3) >= bot+(j-1)*Hei/m & P(:,3) < bot+j*Hei/m; X = unique(P(I,:),'rows'); if size(X,1) > 5 [K,A] = convhull(X(:,1),X(:,2)); % compute center of gravity for the convex hull and use it as % center for computing average diameters n = length(K); x = X(K,1); y = X(K,2); CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; V = mat_vec_subtraction(X(:,1:2),[CX CY]); ang = atan2(V(:,2),V(:,1))+pi; [ang,I] = sort(ang); L = sqrt(sum(V.*V,2)); L = L(I); for i = 1:18 I = ang >= (i-1)*pi/18 & ang < i*pi/18; if any(I) L1 = max(L(I)); else L1 = 0; end J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi; if any(J) L2 = max(L(J)); else L2 = 0; end spreads(j,i) = L1+L2; end end end %% Crown diameters (spreads), mean and maximum: X = unique(P(:,1:2),'rows'); [K,A] = convhull(X(:,1),X(:,2)); % compute center of gravity for the convex hull and use it as center for % computing average diameters n = length(K); x = X(K,1); y = X(K,2); CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; V = Tip(:,1:2)-[CX CY]; ang = atan2(V(:,2),V(:,1))+pi; [ang,I] = sort(ang); L = sqrt(sum(V.*V,2)); L = L(I); S = zeros(18,1); for i = 1:18 I = ang >= (i-1)*pi/18 & ang < i*pi/18; if any(I) L1 = max(L(I)); else L1 = 0; end J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi; if any(J) L2 = max(L(J)); else L2 = 0; end S(i) = L1+L2; end treedata.CrownDiamAve = mean(S); MaxDiam = 0; for i = 1:n V = mat_vec_subtraction([x y],[x(i) y(i)]); L = max(sqrt(sum(V.*V,2))); if L > MaxDiam MaxDiam = L; end end treedata.CrownDiamMax = L; %% Crown areas from convex hull and alpha shape: treedata.CrownAreaConv = A; alp = max(0.5,treedata.CrownDiamAve/10); shp = alphaShape(X(:,1),X(:,2),alp); treedata.CrownAreaAlpha = shp.area; %% Crown base % Define first major branch as the branch whose diameter > min(0.05*dbh,5cm) % and whose horizontal relative reach is more than the median reach of 1st-ord. % branches (or at maximum 10). The reach is defined as the horizontal % distance from the base to the tip divided by the dbh. dbh = treedata.DBHcyl; nb = length(branch.order); HL = zeros(nb,1); % horizontal reach branches1 = (1:1:nb)'; branches1 = branches1(branch.order == 1); % 1st-order branches nb = length(branches1); nc = size(Sta,1); ind = (1:1:nc)'; for i = 1:nb C = ind(cylinder.branch == branches1(i)); if ~isempty(C) base = Sta(C(1),:); C = C(end); tip = Sta(C,:)+Len(C)*Axe(C); V = tip(1:2)-base(1:2); HL(branches1(i)) = sqrt(V*V')/dbh*2; end end M = min(10,median(HL)); % Sort the branches according to the their heights Hei = branch.height(branches1); [Hei,SortOrd] = sort(Hei); branches1 = branches1(SortOrd); % Search the first/lowest branch: d = min(0.05,0.05*dbh); b = 0; if nb > 1 i = 1; while i < nb i = i+1; if branch.diameter(branches1(i)) > d && HL(branches1(i)) > M b = branches1(i); i = nb+2; end end if i == nb+1 && nb > 1 b = branches1(1); end end if b > 0 % search all the children of the first major branch: nb = size(branch.parent,1); Ind = (1:1:nb)'; chi = Ind(branch.parent == b); B = b; while ~isempty(chi) B = [B; chi]; n = length(chi); C = cell(n,1); for i = 1:n C{i} = Ind(branch.parent == chi(i)); end chi = vertcat(C{:}); end % define crown base height from the ground: BaseHeight = max(Sta(:,3)); % Height of the crown base for i = 1:length(B) C = ind(cylinder.branch == B(i)); ht = min(Tip(C,3)); hb = min(Sta(C,3)); h = min(hb,ht); if h < BaseHeight BaseHeight = h; end end treedata.CrownBaseHeight = BaseHeight-Sta(1,3); %% Crown length and ratio treedata.CrownLength = treedata.TreeHeight-treedata.CrownBaseHeight; treedata.CrownRatio = treedata.CrownLength/treedata.TreeHeight; %% Crown volume from convex hull and alpha shape: I = P(:,3) >= BaseHeight; X = P(I,:); [K,V] = convhull(X(:,1),X(:,2),X(:,3)); treedata.CrownVolumeConv = V; alp = max(0.5,treedata.CrownDiamAve/5); shp = alphaShape(X(:,1),X(:,2),X(:,3),alp,'HoleThreshold',10000); treedata.CrownVolumeAlpha = shp.volume; else % No branches treedata.CrownBaseHeight = treedata.TreeHeight; treedata.CrownLength = 0; treedata.CrownRatio = 0; treedata.CrownVolumeConv = 0; treedata.CrownVolumeAlpha = 0; end % End of function end function [treedata,triangulation] = ... triangulate_stem(treedata,cylinder,branch,trunk) Sta = cylinder.start; Rad = cylinder.radius; Len = cylinder.length; DBHqsm = treedata.DBHqsm; % Determine the first major branch (over 10% of dbh or the maximum % diameter branch): nb = size(branch.diameter,1); ind = (1:1:nb)'; ind = ind(branch.order == 1); [~,I] = sort(branch.height(ind)); ind = ind(I); n = length(ind); b = 1; while b <= n && branch.diameter(ind(b)) < 0.1*DBHqsm b = b+1; end b = ind(b); if b > n [~,b] = max(branch.diameter); end % Determine suitable cylinders up to the first major branch but keep the % stem diameter above one quarter (25%) of dbh: C = 1; nc = size(Sta,1); while C < nc && cylinder.branch(C) < b C = C+1; end n = nnz(cylinder.branch == 1); i = 2; while i < n && Sta(i,3) < Sta(C,3) && Rad(i) > 0.125*DBHqsm i = i+1; end CylInd = max(i,3); TrunkLenTri = Sta(CylInd,3)-Sta(1,3); EmptyTriangulation = false; % Calculate the volumes if size(trunk,1) > 1000 && TrunkLenTri >= 1 % Set the parameters for triangulation: % Compute point density, which is used to increase the triangle % size if the point density is very small PointDensity = zeros(CylInd-1,1); for i = 1:CylInd-1 I = trunk(:,3) >= Sta(i,3) & trunk(:,3) < Sta(i+1,3); PointDensity(i) = pi*Rad(i)*Len(i)/nnz(I); end PointDensity = PointDensity(PointDensity < inf); d = max(PointDensity); % Determine minimum triangle size based on dbh if DBHqsm > 1 MinTriaHeight = 0.1; elseif DBHqsm > 0.50 MinTriaHeight = 0.075; elseif DBHqsm > 0.10 MinTriaHeight = 0.05; else MinTriaHeight = 0.02; end TriaHeight0 = max(MinTriaHeight,4*sqrt(d)); % Select the trunk point set used for triangulation I = trunk(:,3) <= Sta(CylInd,3); Stem = trunk(I,:); % Do the triangulation: triangulation = zeros(1,0); l = 0; while isempty(triangulation) && l < 4 && CylInd > 2 l = l+1; TriaHeight = TriaHeight0; TriaWidth = TriaHeight; k = 0; while isempty(triangulation) && k < 3 k = k+1; j = 0; while isempty(triangulation) && j < 5 triangulation = curve_based_triangulation(Stem,TriaHeight,TriaWidth); j = j+1; end % try different triangle sizes if necessary if isempty(triangulation) && k < 3 TriaHeight = TriaHeight+0.03; TriaWidth = TriaHeight; end end % try different length of stem sections if necessary if isempty(triangulation) && l < 4 && CylInd > 2 CylInd = CylInd-1; I = trunk(:,3) <= Sta(CylInd,3); Stem = trunk(I,:); end end if ~isempty(triangulation) triangulation.cylind = CylInd; % Dbh from triangulation Vert = triangulation.vert; h = Vert(:,3)-triangulation.bottom; [~,I] = min(abs(h-1.3)); H = h(I); I = abs(h-H) < triangulation.triah/2; V = Vert(I,:); V = V([2:end 1],:)-V(1:end,:); d = sqrt(sum(V.*V,2)); treedata.DBHtri = sum(d)/pi; % volumes from the triangulation treedata.TriaTrunkVolume = triangulation.volume; TrunkVolMix = treedata.TrunkVolume-... 1000*pi*sum(Rad(1:CylInd-1).^2.*Len(1:CylInd-1))+triangulation.volume; TrunkAreaMix = treedata.TrunkArea-... 2*pi*sum(Rad(1:CylInd-1).*Len(1:CylInd-1))+triangulation.SideArea; treedata.MixTrunkVolume = TrunkVolMix; treedata.MixTotalVolume = TrunkVolMix+treedata.BranchVolume; treedata.TriaTrunkArea = triangulation.SideArea; treedata.MixTrunkArea = TrunkAreaMix; treedata.MixTotalArea = TrunkAreaMix+treedata.BranchArea; treedata.TriaTrunkLength = TrunkLenTri; else EmptyTriangulation = true; end else EmptyTriangulation = true; end if EmptyTriangulation disp(' No triangulation model produced') clear triangulation treedata.DBHtri = DBHqsm; treedata.TriaTrunkVolume = treedata.TrunkVolume; treedata.TriaTrunkArea = treedata.TrunkArea; treedata.MixTrunkVolume = treedata.TrunkVolume; treedata.MixTrunkArea = treedata.TrunkArea; treedata.MixTotalVolume = treedata.TotalVolume; treedata.MixTotalArea = treedata.TotalArea; treedata.TriaTrunkLength = 0; triangulation.vert = zeros(0,3); triangulation.facet = zeros(0,3); triangulation.fvd = zeros(0,1); triangulation.volume = 0; triangulation.SideArea = 0; triangulation.BottomArea = 0; triangulation.TopArea = 0; triangulation.bottom = 0; triangulation.top = 0; triangulation.triah = 0; triangulation.triaw = 0; triangulation.cylind = 0; end end function treedata = cylinder_distribution(treedata,cyl,dist) %% Wood part diameter, zenith and azimuth direction distributions % Volume, area and length of wood parts as functions of cylinder % diameter, zenith, and azimuth if strcmp(dist,'Dia') Par = cyl.radius; n = ceil(max(200*cyl.radius)); a = 0.005; % diameter in 1 cm classes elseif strcmp(dist,'Zen') Par = 180/pi*acos(cyl.axis(:,3)); n = 18; a = 10; % zenith direction in 10 degree angle classes elseif strcmp(dist,'Azi') Par = 180/pi*atan2(cyl.axis(:,2),cyl.axis(:,1))+180; n = 36; a = 10; % azimuth direction in 10 degree angle classes end CylDist = zeros(3,n); for i = 1:n K = Par >= (i-1)*a & Par < i*a; CylDist(1,i) = 1000*pi*sum(cyl.radius(K).^2.*cyl.length(K)); % vol in L CylDist(2,i) = 2*pi*sum(cyl.radius(K).*cyl.length(K)); % area in m^2 CylDist(3,i) = sum(cyl.length(K)); % length in m end treedata.(['VolCyl',dist]) = CylDist(1,:); treedata.(['AreCyl',dist]) = CylDist(2,:); treedata.(['LenCyl',dist]) = CylDist(3,:); end function treedata = cylinder_height_distribution(treedata,cylinder,ind) Rad = cylinder.radius; Len = cylinder.length; Axe = cylinder.axis; %% Wood part height distributions % Volume, area and length of cylinders as a function of height % (in 1 m height classes) MaxHei= ceil(treedata.TreeHeight); treedata.VolCylHei = zeros(1,MaxHei); treedata.AreCylHei = zeros(1,MaxHei); treedata.LenCylHei = zeros(1,MaxHei); End = cylinder.start+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; bot = min(cylinder.start(:,3)); B = cylinder.start(:,3)-bot; T = End(:,3)-bot; for j = 1:MaxHei I1 = B >= (j-2) & B < (j-1); % base below this bin J1 = B >= (j-1) & B < j; % base in this bin K1 = B >= j & B < (j+1); % base above this bin I2 = T >= (j-2) & T < (j-1); % top below this bin J2 = T >= (j-1) & T < j; % top in this bin K2 = T >= j & T < (j+1); % top above this bin C1 = ind(J1&J2); % base and top in this bin C2 = ind(J1&K2); % base in this bin, top above C3 = ind(J1&I2); % base in this bin, top below C4 = ind(I1&J2); % base in bin below, top in this C5 = ind(K1&J2); % base in bin above, top in this v1 = 1000*pi*sum(Rad(C1).^2.*Len(C1)); a1 = 2*pi*sum(Rad(C1).*Len(C1)); l1 = sum(Len(C1)); r2 = (j-B(C2))./(T(C2)-B(C2)); % relative portion in this bin v2 = 1000*pi*sum(Rad(C2).^2.*Len(C2).*r2); a2 = 2*pi*sum(Rad(C2).*Len(C2).*r2); l2 = sum(Len(C2).*r2); r3 = (B(C3)-j+1)./(B(C3)-T(C3)); % relative portion in this bin v3 = 1000*pi*sum(Rad(C3).^2.*Len(C3).*r3); a3 = 2*pi*sum(Rad(C3).*Len(C3).*r3); l3 = sum(Len(C3).*r3); r4 = (T(C4)-j+1)./(T(C4)-B(C4)); % relative portion in this bin v4 = 1000*pi*sum(Rad(C4).^2.*Len(C4).*r4); a4 = 2*pi*sum(Rad(C4).*Len(C4).*r4); l4 = sum(Len(C4).*r4); r5 = (j-T(C5))./(B(C5)-T(C5)); % relative portion in this bin v5 = 1000*pi*sum(Rad(C5).^2.*Len(C5).*r5); a5 = 2*pi*sum(Rad(C5).*Len(C5).*r5); l5 = sum(Len(C5).*r5); treedata.VolCylHei(j) = v1+v2+v3+v4+v5; treedata.AreCylHei(j) = a1+a2+a3+a4+a5; treedata.LenCylHei(j) = l1+l2+l3+l4+l5; end end function treedata = branch_distribution(treedata,branch,dist) %% Branch diameter, height, angle, zenith and azimuth distributions % Volume, area, length and number of branches as a function of branch % diamater, height, angle, zenith and aximuth BOrd = branch.order(2:end); BVol = branch.volume(2:end); BAre = branch.area(2:end); BLen = branch.length(2:end); if strcmp(dist,'Dia') Par = branch.diameter(2:end); n = ceil(max(100*Par)); a = 0.005; % diameter in 1 cm classes elseif strcmp(dist,'Hei') Par = branch.height(2:end); n = ceil(treedata.TreeHeight); a = 1; % height in 1 m classes elseif strcmp(dist,'Ang') Par = branch.angle(2:end); n = 18; a = 10; % angle in 10 degree classes elseif strcmp(dist,'Zen') Par = branch.zenith(2:end); n = 18; a = 10; % zenith direction in 10 degree angle classes elseif strcmp(dist,'Azi') Par = branch.azimuth(2:end)+180; n = 36; a = 10; % azimuth direction in 10 degree angle classes end if isempty(n) n = 0; end BranchDist = zeros(8,n); for i = 1:n I = Par >= (i-1)*a & Par < i*a; BranchDist(1,i) = sum(BVol(I)); % volume (all branches) BranchDist(2,i) = sum(BVol(I & BOrd == 1)); % volume (1st-branches) BranchDist(3,i) = sum(BAre(I)); % area (all branches) BranchDist(4,i) = sum(BAre(I & BOrd == 1)); % area (1st-branches) BranchDist(5,i) = sum(BLen(I)); % length (all branches) BranchDist(6,i) = sum(BLen(I & BOrd == 1)); % length (1st-branches) BranchDist(7,i) = nnz(I); % number (all branches) BranchDist(8,i) = nnz(I & BOrd == 1); % number (1st-branches) end treedata.(['VolBranch',dist]) = BranchDist(1,:); treedata.(['VolBranch1',dist]) = BranchDist(2,:); treedata.(['AreBranch',dist]) = BranchDist(3,:); treedata.(['AreBranch1',dist]) = BranchDist(4,:); treedata.(['LenBranch',dist]) = BranchDist(5,:); treedata.(['LenBranch1',dist]) = BranchDist(6,:); treedata.(['NumBranch',dist]) = BranchDist(7,:); treedata.(['NumBranch1',dist]) = BranchDist(8,:); end function treedata = branch_order_distribution(treedata,branch) %% Branch order distributions % Volume, area, length and number of branches as a function of branch order BO = max(branch.order); BranchOrdDist = zeros(BO,4); for i = 1:max(1,BO) I = branch.order == i; BranchOrdDist(i,1) = sum(branch.volume(I)); % volumes BranchOrdDist(i,2) = sum(branch.area(I)); % areas BranchOrdDist(i,3) = sum(branch.length(I)); % lengths BranchOrdDist(i,4) = nnz(I); % number of ith-order branches end treedata.VolBranchOrd = BranchOrdDist(:,1)'; treedata.AreBranchOrd = BranchOrdDist(:,2)'; treedata.LenBranchOrd = BranchOrdDist(:,3)'; treedata.NumBranchOrd = BranchOrdDist(:,4)'; end
github
InverseTampere/TreeQSM-master
cylinders.m
.m
TreeQSM-master/src/main_steps/cylinders.m
34,496
utf_8
21b6b835cd40db99681596120408488e
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function cylinder = cylinders(P,cover,segment,inputs) % --------------------------------------------------------------------- % CYLINDERS.M Fits cylinders to the branch-segments of the point cloud % % Version 3.0.0 % Latest update 1 Now 2018 % % Copyright (C) 2013-2018 Pasi Raumonen % --------------------------------------------------------------------- % % Reconstructs the surface and volume of branches of input tree with % cylinders. Subdivides each segment to smaller regions to which cylinders % are fitted in least squares sense. Returns the cylinder information and % in addition the child-relation of the cylinders plus the cylinders in % each segment. % --------------------------------------------------------------------- % Inputs: % P Point cloud, matrix % cover Cover sets % segment Segments % input Input parameters of the reconstruction: % MinCylRad Minimum cylinder radius, used in the taper corrections % ParentCor Radius correction based on radius of the parent: radii in % a branch are usually smaller than the radius of the parent % cylinder in the parent branch % TaperCor Parabola taper correction of radii inside branches. % GrowthVolCor If 1, use growth volume correction % GrowthVolFac Growth volume correction factor % % Outputs: % cylinder Structure array containing the following cylinder info: % radius Radii of the cylinders, vector % length Lengths of the cylinders, vector % axis Axes of the cylinders, matrix % start Starting points of the cylinders, matrix % parent Parents of the cylinders, vector % extension Extensions of the cylinders, vector % branch Branch of the cylinder % BranchOrder Branching order of the cylinder % PositionInBranch Position of the cylinder inside the branch % mad Mean absolute distances of points from the cylinder % surface, vector % SurfCov Surface coverage measure, vector % added Added cylinders, logical vector % UnModRadius Unmodified radii % --------------------------------------------------------------------- % Changes from version 3.0.0 to 3.1.0, 6 Oct 2021: % 1) Added the growth volume correction option ("growth_volume_correction") % back, which was removed from the previous version by a mistake. The % "growth_volume_correction" function was also corrected. % 2) Added the fields "branch", "BranchOrder", "PositionInBranch" to the % output structure "cylinder" % 3) Removed the fields "CylsInSegment" and "ChildCyls" from the output % structure "cylinder" % Changes from version 2.0.0 to 3.0.0, 13 Aug 2020: % Many comprehensive and small changes: % 1) "regions" and "cylinder_fitting" are combined into "cylinder_fitting" % and the process is more adaptive as it now fits at least 3 (up to 10) % cylinders of different lengths for each region. % 2) "lcyl" and "FilRad" parameters are not used anymore % 3) Surface coverage ("SurfCov") and mean absolute distance ("mad") are % added to the cylinder structure as fields. % 4) Surface coverage filtering is used in the definition of the regions % and removing outliers % 5) "adjustments" has many changes, particularly in the taper corrections % where the parabola-taper curve is fitted to all the data with surface % coverage as a weight. Adjustment of radii based on the parabola is % closer the parabola the smaller the surface coverage. For the stem the % taper correction is the same as for the branches. The minimum and % maximum radii corrections are also modified. % 6) Syntax has changed, particularly for the "cyl"-structure % Changes from version 2.1.0 to 2.1.1, 26 Nov 2019: % 1) Increased the minimum number "n" of estimated cylinders for % initialization of vectors at the beginning of the code. This is done % to make sure that trees without branches will not cause errors. % Changes from version 2.0.0 to 2.1.0, 3 Oct 2019: % 1) Bug fix: UnmodRadius is now defined as it should, as the radius after % least squares fitting but without parent, taper or growth vol. corrections % 2) Bug fix: Correction in "least_squares_cylinder.m", calculates the % starting point of the cylinder now correctly. % 3) Bug fix: Correct errors related to combining data when a fitted % cylinder is replaced with two shorter ones, in "cylinder_fitting" % 4) Removed some unnecessary command lines for computing radius estimates % in "regions" %% Initialization of variables Segs = segment.segments; SPar = segment.ParentSegment; SChi = segment.ChildSegment; NumOfSeg = max(size(Segs)); % number of segments n = max(2000,min(40*NumOfSeg,2e5)); c = 1; % number of cylinders determined CChi = cell(n,1); % Children of the cylinders CiS = cell(NumOfSeg,1); % Cylinders in the segment cylinder.radius = zeros(n,1,'single'); cylinder.length = zeros(n,1,'single'); cylinder.start = zeros(n,3,'single'); cylinder.axis = zeros(n,3,'single'); cylinder.parent = zeros(n,1,'uint32'); cylinder.extension = zeros(n,1,'uint32'); cylinder.added = false(n,1); cylinder.UnmodRadius = zeros(n,1,'single'); cylinder.branch = zeros(n,1,'uint16'); cylinder.SurfCov = zeros(n,1,'single'); cylinder.mad = zeros(n,1,'single'); %% Determine suitable order of segments (from trunk to the "youngest" child) bases = (1:1:NumOfSeg)'; bases = bases(SPar(:,1) == 0); nb = length(bases); SegmentIndex = zeros(NumOfSeg,1); nc = 0; for i = 1:nb nc = nc+1; SegmentIndex(nc) = bases(i); S = vertcat(SChi{bases(i)}); while ~isempty(S) n = length(S); SegmentIndex(nc+1:nc+n) = S; nc = nc+n; S = vertcat(SChi{S}); end end %% Fit cylinders individually for each segment for k = 1:NumOfSeg si = SegmentIndex(k); if si > 0 %% Some initialization about the segment Seg = Segs{si}; % the current segment under analysis nl = max(size(Seg)); % number of cover set layers in the segment [Sets,IndSets] = verticalcat(Seg); % the cover sets in the segment ns = length(Sets); % number of cover sets in the current segment Points = vertcat(cover.ball{Sets}); % the points in the segments np = length(Points); % number of points in the segment % Determine indexes of points for faster definition of regions BallSize = cellfun('length',cover.ball(Sets)); IndPoints = ones(nl,2); % indexes for points in each layer of the segment for j = 1:nl IndPoints(j,2) = sum(BallSize(IndSets(j,1):IndSets(j,2))); end IndPoints(:,2) = cumsum(IndPoints(:,2)); IndPoints(2:end,1) = IndPoints(2:end,1)+IndPoints(1:end-1,2); Base = Seg{1}; % the base of the segment nb = IndPoints(1,2); % number of points in the base % Reconstruct only large enough segments if nl > 1 && np > nb && ns > 2 && np > 20 && ~isempty(Base) %% Cylinder fitting [cyl,Reg] = cylinder_fitting(P,Points,IndPoints,nl,si); nc = numel(cyl.radius); %% Search possible parent cylinder if nc > 0 && si > 1 [PC,cyl,added] = parent_cylinder(SPar,SChi,CiS,cylinder,cyl,si); nc = numel(cyl.radius); elseif si == 1 PC = zeros(0,1); added = false; else added = false; end cyl.radius0 = cyl.radius; %% Modify cylinders if nc > 0 % Define parent cylinder: parcyl.radius = cylinder.radius(PC); parcyl.length = cylinder.length(PC); parcyl.start = cylinder.start(PC,:); parcyl.axis = cylinder.axis(PC,:); % Modify the cylinders cyl = adjustments(cyl,parcyl,inputs,Reg); end %% Save the cylinders % if at least one acceptable cylinder, then save them Accept = nc > 0 & min(cyl.radius(1:nc)) > 0; if Accept % If the parent cylinder exists, set the parent-child relations if ~isempty(PC) cylinder.parent(c) = PC; if cylinder.extension(PC) == c I = cylinder.branch(PC); cylinder.branch(c:c+nc-1) = I; CiS{I} = [CiS{I}; linspace(c,c+nc-1,nc)']; else CChi{PC} = [CChi{PC}; c]; cylinder.branch(c:c+nc-1) = si; CiS{si} = linspace(c,c+nc-1,nc)'; end else cylinder.branch(c:c+nc-1) = si; CiS{si} = linspace(c,c+nc-1,nc)'; end cylinder.radius(c:c+nc-1) = cyl.radius(1:nc); cylinder.length(c:c+nc-1) = cyl.length(1:nc); cylinder.axis(c:c+nc-1,:) = cyl.axis(1:nc,:); cylinder.start(c:c+nc-1,:) = cyl.start(1:nc,:); cylinder.parent(c+1:c+nc-1) = linspace(c,c+nc-2,nc-1); cylinder.extension(c:c+nc-2) = linspace(c+1,c+nc-1,nc-1); cylinder.UnmodRadius(c:c+nc-1) = cyl.radius0(1:nc); cylinder.SurfCov(c:c+nc-1) = cyl.SurfCov(1:nc); cylinder.mad(c:c+nc-1) = cyl.mad(1:nc); if added cylinder.added(c) = true; cylinder.added(c) = true; end c = c+nc; % number of cylinders so far (plus one) end end end end c = c-1; % number of cylinders %% Define outputs names = fieldnames(cylinder); n = max(size(names)); for k = 1:n cylinder.(names{k}) = single(cylinder.(names{k})(1:c,:)); end if c <= 2^16 cylinder.parent = uint16(cylinder.parent); cylinder.extension = uint16(cylinder.extension); end nb = max(cylinder.branch); if nb <= 2^8 cylinder.branch = uint8(cylinder.branch); elseif nb <= 2^16 cylinder.branch = uint16(cylinder.branch); end cylinder.added = logical(cylinder.added); % Define the branching order: BOrd = zeros(c,1); for i = 1:c if cylinder.parent(i) > 0 p = cylinder.parent(i); if cylinder.extension(p) == i BOrd(i) = BOrd(p); else BOrd(i) = BOrd(p)+1; end end end cylinder.BranchOrder = uint8(BOrd); % Define the cylinder position inside the branch PiB = ones(c,1); for i = 1:NumOfSeg C = CiS{i}; if ~isempty(C) n = length(C); PiB(C) = (1:1:n)'; end end if max(PiB) <= 2^8 cylinder.PositionInBranch = uint8(PiB); else cylinder.PositionInBranch = uint16(PiB); end % Growth volume correction if inputs.GrowthVolCor && c > 0 cylinder = growth_volume_correction(cylinder,inputs); end end % End of main function function [cyl,Reg] = cylinder_fitting(P,Points,Ind,nl,si) if nl > 6 i0 = 1; i = 4; % indexes of the first and last layers of the region t = 0; Reg = cell(nl,1); cyls = cell(11,1); regs = cell(11,1); data = zeros(11,4); while i0 < nl-2 %% Fit at least three cylinders of different lengths bot = Points(Ind(i0,1):Ind(i0+1,2)); Bot = average(P(bot,:)); % Bottom axis point of the region again = true; j = 0; while i+j <= nl && j <= 10 && (j <= 2 || again) %% Select points and estimate axis RegC = Points(Ind(i0,1):Ind(i+j,2)); % candidate region % Top axis point of the region: top = Points(Ind(i+j-1,1):Ind(i+j,2)); Top = average(P(top,:)); % Axis of the cylinder: Axis = Top-Bot; c0.axis = Axis/norm(Axis); % Compute the height along the axis: h = (P(RegC,:)-Bot)*c0.axis'; minh = min(h); % Correct Bot to correspond to the real bottom if j == 0 Bot = Bot+minh*c0.axis; c0.start = Bot; h = (P(RegC,:)-Bot)*c0.axis'; minh = min(h); end if i+j >= nl ht = (Top-c0.start)*c0.axis'; Top = Top+(max(h)-ht)*c0.axis; end % Compute the height of the Top: ht = (Top-c0.start)*c0.axis'; Sec = h <= ht & h >= minh; % only points below the Top c0.length = ht-minh; % length of the region/cylinder % The region for the cylinder fitting: reg = RegC(Sec); Q0 = P(reg,:); %% Filter points and estimate radius if size(Q0,1) > 20 [Keep,c0] = surface_coverage_filtering(Q0,c0,0.02,20); reg = reg(Keep); Q0 = Q0(Keep,:); else c0.radius = 0.01; c0.SurfCov = 0.05; c0.mad = 0.01; c0.conv = 1; c0.rel = 1; end %% Fit cylinder if size(Q0,1) > 9 if i >= nl && t == 0 c = least_squares_cylinder(Q0,c0); elseif i >= nl && t > 0 h = (Q0-CylTop)*c0.axis'; I = h >= 0; Q = Q0(I,:); % the section reg = reg(I); n2 = size(Q,1); n1 = nnz(~I); if n2 > 9 && n1 > 5 Q0 = [Q0(~I,:); Q]; % the point cloud for cylinder fitting W = [1/3*ones(n2,1); 2/3*ones(n1,1)]; % the weights c = least_squares_cylinder(Q0,c0,W,Q); else c = least_squares_cylinder(Q0,c0); end elseif t == 0 top = Points(Ind(i+j-3,1):Ind(i+j-2,2)); Top = average(P(top,:)); % Top axis point of the region ht = (Top-Bot)*c0.axis'; h = (Q0-Bot)*c0.axis'; I = h <= ht; Q = Q0(I,:); % the section reg = reg(I); n2 = size(Q,1); n3 = nnz(~I); if n2 > 9 && n3 > 5 Q0 = [Q; Q0(~I,:)]; % the point cloud for cylinder fitting W = [2/3*ones(n2,1); 1/3*ones(n3,1)]; % the weights c = least_squares_cylinder(Q0,c0,W,Q); else c = least_squares_cylinder(Q0,c0); end else top = Points(Ind(i+j-3,1):Ind(i+j-2,2)); Top = average(P(top,:)); % Top axis point of the region ht = (Top-CylTop)*c0.axis'; h = (Q0-CylTop)*c0.axis'; I1 = h < 0; % the bottom I2 = h >= 0 & h <= ht; % the section I3 = h > ht; % the top Q = Q0(I2,:); reg = reg(I2); n1 = nnz(I1); n2 = size(Q,1); n3 = nnz(I3); if n2 > 9 Q0 = [Q0(I1,:); Q; Q0(I3,:)]; W = [1/4*ones(n1,1); 2/4*ones(n2,1); 1/4*ones(n3,1)]; c = least_squares_cylinder(Q0,c0,W,Q); else c = c0; c.rel = 0; end end if c.conv == 0 c = c0; c.rel = 0; end if c.SurfCov < 0.2 c.rel = 0; end else c = c0; c.rel = 0; end % Collect fit data data(j+1,:) = [c.rel c.conv c.SurfCov c.length/c.radius]; cyls{j+1} = c; regs{j+1} = reg; j = j+1; % If reasonable cylinder fitted, then stop fitting new ones % (but always fit at least three cylinders) RL = c.length/c.radius; % relative length of the cylinder if again && c.rel && c.conv && RL > 2 if si == 1 && c.SurfCov > 0.7 again = false; elseif si > 1 && c.SurfCov > 0.5 again = false; end end end %% Select the best of the fitted cylinders % based on maximum surface coverage OKfit = data(1:j,1) & data(1:j,2) & data(1:j,4) > 1.5; J = (1:1:j)'; t = t+1; if any(OKfit) J = J(OKfit); end [~,I] = max(data(J,3)-0.01*data(J,4)); J = J(I); c = cyls{J}; %% Update the indexes of the layers for the next region: CylTop = c.start+c.length*c.axis; i0 = i0+1; bot = Points(Ind(i0,1):Ind(i0+1,2)); Bot = average(P(bot,:)); % Bottom axis point of the region h = (Bot-CylTop)*c.axis'; i00 = i0; while i0+1 < nl && i0 < i00+5 && h < -c.radius/3 i0 = i0+1; bot = Points(Ind(i0,1):Ind(i0+1,2)); Bot = average(P(bot,:)); % Bottom axis point of the region h = (Bot-CylTop)*c.axis'; end i = i0+5; i = min(i,nl); %% If the next section is very short part of the end of the branch % then simply increase the length of the current cylinder if nl-i0+2 < 4 reg = Points(Ind(nl-5,1):Ind(nl,2)); Q0 = P(reg,:); ht = (c.start+c.length*c.axis)*c.axis'; h = Q0*c.axis'; maxh = max(h); if maxh > ht c.length = c.length+(maxh-ht); end i0 = nl; end Reg{t} = regs{J}; if t == 1 cyl = c; names = fieldnames(cyl); n = max(size(names)); else for k = 1:n cyl.(names{k}) = [cyl.(names{k}); c.(names{k})]; end end %% compute cylinder top for the definition of the next section CylTop = c.start+c.length*c.axis; end Reg = Reg(1:t); else %% Define a region for small segments Q0 = P(Points,:); if size(Q0,1) > 10 %% Define the direction bot = Points(Ind(1,1):Ind(1,2)); Bot = average(P(bot,:)); top = Points(Ind(nl,1):Ind(nl,2)); Top = average(P(top,:)); Axis = Top-Bot; c0.axis = Axis/norm(Axis); h = Q0*c0.axis'; c0.length = max(h)-min(h); hpoint = Bot*c0.axis'; c0.start = Bot-(hpoint-min(h))*c0.axis; %% Define other outputs [Keep,c0] = surface_coverage_filtering(Q0,c0,0.02,20); Reg = cell(1,1); Reg{1} = Points(Keep); Q0 = Q0(Keep,:); cyl = least_squares_cylinder(Q0,c0); if ~cyl.conv || ~cyl.rel cyl = c0; end t = 1; else cyl = 0; t = 0; end end % Define Reg as coordinates for i = 1:t Reg{i} = P(Reg{i},:); end Reg = Reg(1:t); % End of function end function [PC,cyl,added] = parent_cylinder(SPar,SChi,CiS,cylinder,cyl,si) % Finds the parent cylinder from the possible parent segment. % Does this by checking if the axis of the cylinder, if continued, will % cross the nearby cylinders in the parent segment. % Adjust the cylinder so that it starts from the surface of its parent. rad = cyl.radius; len = cyl.length; sta = cyl.start; axe = cyl.axis; % PC Parent cylinder nc = numel(rad); added = false; if SPar(si) > 0 % parent segment exists, find the parent cylinder s = SPar(si); PC = CiS{s}; % the cylinders in the parent segment % select the closest cylinders for closer examination if length(PC) > 1 D = mat_vec_subtraction(-cylinder.start(PC,:),-sta(1,:)); d = sum(D.*D,2); [~,I] = sort(d); if length(PC) > 3 I = I(1:4); end pc = PC(I); ParentFound = false; elseif length(PC) == 1 ParentFound = true; else PC = zeros(0,1); ParentFound = true; end %% Check possible crossing points if ~ParentFound pc0 = pc; n = length(pc); % Calculate the possible crossing points of the cylinder axis, when % extended, on the surfaces of the parent candidate cylinders x = zeros(n,2); % how much the starting point has to move to cross h = zeros(n,2); % the crossing point height in the parent Axe = cylinder.axis(pc,:); Sta = cylinder.start(pc,:); for j = 1:n % Crossing points solved from a quadratic equation A = axe(1,:)-(axe(1,:)*Axe(j,:)')*Axe(j,:); B = sta(1,:)-Sta(j,:)-(sta(1,:)*Axe(j,:)')*Axe(j,:)... +(Sta(j,:)*Axe(j,:)')*Axe(j,:); e = A*A'; f = 2*A*B'; g = B*B'-cylinder.radius(pc(j))^2; di = sqrt(f^2 - 4*e*g); % the discriminant s1 = (-f + di)/(2*e); % how much the starting point must be moved to cross: s2 = (-f - di)/(2*e); if isreal(s1) %% cylinders can cross % the heights of the crossing points x(j,:) = [s1 s2]; h(j,1) = sta(1,:)*Axe(j,:)'+x(j,1)*axe(1,:)*Axe(j,:)'-... Sta(j,:)*Axe(j,:)'; h(j,2) = sta(1,:)*Axe(j,:)'+x(j,2)*axe(1,:)*Axe(j,:)'-... Sta(j,:)*Axe(j,:)'; end end %% Extend to crossing point in the (extended) parent I = x(:,1) ~= 0; % Select only candidates with crossing points pc = pc0(I); x = x(I,:); h = h(I,:); j = 1; n = nnz(I); X = zeros(n,3); % Len = cylinder.length(pc); while j <= n && ~ParentFound if x(j,1) > 0 && x(j,2) < 0 % sp inside the parent and crosses its surface if h(j,1) >= 0 && h(j,1) <= Len(j) && len(1)-x(j,1) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,1)*axe(1,:); len(1) = len(1)-x(j,1); ParentFound = true; elseif len(1)-x(j,1) > 0 if h(j,1) < 0 X(j,:) = [x(j,1) abs(h(j,1)) 0]; else X(j,:) = [x(j,1) h(j,1)-Len(j) 0]; end else X(j,:) = [x(j,1) h(j,1) 1]; end elseif x(j,1) < 0 && x(j,2) > 0 && len(1)-x(j,2) > 0 % sp inside the parent and crosses its surface if h(j,2) >= 0 && h(j,2) <= Len(j) && len(1)-x(j,2) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,2)*axe(1,:); len(1) = len(1)-x(j,2); ParentFound = true; elseif len(1)-x(j,2) > 0 if h(j,2) < 0 X(j,:) = [x(j,2) abs(h(j,2)) 0]; else X(j,:) = [x(j,2) h(j,2)-Len(j) 0]; end else X(j,:) = [x(j,2) h(j,2) 1]; end elseif x(j,1) < 0 && x(j,2) < 0 && x(j,2) < x(j,1) && len(1)-x(j,1) > 0 % sp outside the parent and crosses its surface when extended % backwards if h(j,1) >= 0 && h(j,1) <= Len(j) && len(1)-x(j,1) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,1)*axe(1,:); len(1) = len(1)-x(j,1); ParentFound = true; elseif len(1)-x(j,1) > 0 if h(j,1) < 0 X(j,:) = [x(j,1) abs(h(j,1)) 0]; else X(j,:) = [x(j,1) h(j,1)-Len(j) 0]; end else X(j,:) = [x(j,1) h(j,1) 1]; end elseif x(j,1) < 0 && x(j,2) < 0 && x(j,2) > x(j,1) && len(1)-x(j,2) > 0 % sp outside the parent and crosses its surface when extended % backwards if h(j,2) >= 0 && h(j,2) <= Len(j) && len(1)-x(j,2) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,2)*axe(1,:); len(1) = len(1)-x(j,2); ParentFound = true; elseif len(1)-x(j,2) > 0 if h(j,2) < 0 X(j,:) = [x(j,2) abs(h(j,2)) 0]; else X(j,:) = [x(j,2) h(j,2)-Len(j) 0]; end else X(j,:) = [x(j,2) h(j,2) 1]; end elseif x(j,1) > 0 && x(j,2) > 0 && x(j,2) < x(j,1) && len(1)-x(j,1) > 0 % sp outside the parent but crosses its surface when extended forward if h(j,1) >= 0 && h(j,1) <= Len(j) && len(1)-x(j,1) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,1)*axe(1,:); len(1) = len(1)-x(j,1); ParentFound = true; elseif len(1)-x(j,1) > 0 if h(j,1) < 0 X(j,:) = [x(j,1) abs(h(j,1)) 0]; else X(j,:) = [x(j,1) h(j,1)-Len(j) 0]; end else X(j,:) = [x(j,1) h(j,1) 1]; end elseif x(j,1) > 0 && x(j,2) > 0 && x(j,2) > x(j,1) && len(1)-x(j,2) > 0 % sp outside the parent and crosses its surface when extended forward if h(j,2) >= 0 && h(j,2) <= Len(j) && len(1)-x(j,2) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,2)*axe(1,:); len(1) = len(1)-x(j,2); ParentFound = true; elseif len(1)-x(j,2) > 0 if h(j,1) < 0 X(j,:) = [x(j,2) abs(h(j,2)) 0]; else X(j,:) = [x(j,2) h(j,2)-Len(j) 0]; end else X(j,:) = [x(j,2) h(j,2) 1]; end end j = j+1; end if ~ParentFound && n > 0 [H,I] = min(X(:,2)); X = X(I,:); if X(3) == 0 && H < 0.1*Len(I) PC = pc(I); sta(1,:) = sta(1,:)+X(1)*axe(1,:); len(1) = len(1)-X(1); ParentFound = true; else PC = pc(I); if nc > 1 && X(1) <= rad(1) && abs(X(2)) <= 1.25*cylinder.length(PC) % Remove the first cylinder and adjust the second S = sta(1,:)+X(1)*axe(1,:); V = sta(2,:)+len(2)*axe(2,:)-S; len(2) = norm(V); len = len(2:nc); axe(2,:) = V/norm(V); axe = axe(2:nc,:); sta(2,:) = S; sta = sta(2:nc,:); rad = rad(2:nc); cyl.mad = cyl.mad(2:nc); cyl.SurfCov = cyl.SurfCov(2:nc); nc = nc-1; ParentFound = true; elseif nc > 1 % Remove the first cylinder sta = sta(2:nc,:); len = len(2:nc); axe = axe(2:nc,:); rad = rad(2:nc); cyl.mad = cyl.mad(2:nc); cyl.SurfCov = cyl.SurfCov(2:nc); nc = nc-1; elseif isempty(SChi{si}) % Remove the cylinder nc = 0; PC = zeros(0,1); ParentFound = true; rad = zeros(0,1); elseif X(1) <= rad(1) && abs(X(2)) <= 1.5*cylinder.length(PC) % Adjust the cylinder sta(1,:) = sta(1,:)+X(1)*axe(1,:); len(1) = abs(X(1)); ParentFound = true; end end end if ~ParentFound % The parent is the cylinder in the parent segment whose axis % line is the closest to the axis line of the first cylinder % Or the parent cylinder is the one whose base, when connected % to the first cylinder is the most parallel. % Add new cylinder pc = pc0; [Dist,~,DistOnLines] = distances_between_lines(... sta(1,:),axe(1,:),cylinder.start(pc,:),cylinder.axis(pc,:)); I = DistOnLines >= 0; J = DistOnLines <= cylinder.length(pc); I = I&J; if ~any(I) I = DistOnLines >= -0.2*cylinder.length(pc); J = DistOnLines <= 1.2*cylinder.length(pc); I = I&J; end if any(I) pc = pc(I); Dist = Dist(I); DistOnLines = DistOnLines(I); [~,I] = min(Dist); DistOnLines = DistOnLines(I); PC = pc(I); Q = cylinder.start(PC,:)+DistOnLines*cylinder.axis(PC,:); V = sta(1,:)-Q; L = norm(V); V = V/L; a = acos(V*cylinder.axis(PC,:)'); h = sin(a)*L; S = Q+cylinder.radius(PC)/h*L*V; L = (h-cylinder.radius(PC))/h*L; if L > 0.01 && L/len(1) > 0.2 nc = nc+1; sta = [S; sta]; rad = [rad(1); rad]; axe = [V; axe]; len = [L; len]; cyl.mad = [cyl.mad(1); cyl.mad]; cyl.SurfCov = [cyl.SurfCov(1); cyl.SurfCov]; cyl.rel = [cyl.rel(1); cyl.rel]; cyl.conv = [cyl.conv(1); cyl.conv]; added = true; end else V = -mat_vec_subtraction(cylinder.start(pc,:),sta(1,:)); L0 = sqrt(sum(V.*V,2)); V = [V(:,1)./L0 V(:,2)./L0 V(:,3)./L0]; A = V*axe(1,:)'; [A,I] = max(A); L1 = L0(I); PC = pc(I); V = V(I,:); a = acos(V*cylinder.axis(PC,:)'); h = sin(a)*L1; S = cylinder.start(PC,:)+cylinder.radius(PC)/h*L1*V; L = (h-cylinder.radius(PC))/h*L1; if L > 0.01 && L/len(1) > 0.2 nc = nc+1; sta = [S; sta]; rad = [rad(1); rad]; axe = [V; axe]; len = [L; len]; cyl.mad = [cyl.mad(1); cyl.mad]; cyl.SurfCov = [cyl.SurfCov(1); cyl.SurfCov]; cyl.rel = [cyl.rel(1); cyl.rel]; cyl.conv = [cyl.conv(1); cyl.conv]; added = true; end end end end else % no parent segment exists PC = zeros(0,1); end % define the output cyl.radius = rad(1:nc); cyl.length = len(1:nc,:); cyl.start = sta(1:nc,:); cyl.axis = axe(1:nc,:); cyl.mad = cyl.mad(1:nc); cyl.SurfCov = cyl.SurfCov(1:nc); cyl.conv = cyl.conv(1:nc); cyl.rel = cyl.rel(1:nc); % End of function end function cyl = adjustments(cyl,parcyl,inputs,Regs) nc = size(cyl.radius,1); Mod = false(nc,1); % cylinders modified SC = cyl.SurfCov; %% Determine the maximum and the minimum radius % The maximum based on parent branch if ~isempty(parcyl.radius) MaxR = 0.95*parcyl.radius; MaxR = max(MaxR,inputs.MinCylRad); else % use the maximum from the bottom cylinders a = min(3,nc); MaxR = 1.25*max(cyl.radius(1:a)); end MinR = min(cyl.radius(SC > 0.7)); if ~isempty(MinR) && min(cyl.radius) < MinR/2 MinR = min(cyl.radius(SC > 0.4)); elseif isempty(MinR) MinR = min(cyl.radius(SC > 0.4)); if isempty(MinR) MinR = inputs.MinCylRad; end end %% Check maximum and minimum radii I = cyl.radius < MinR; cyl.radius(I) = MinR; Mod(I) = true; if inputs.ParentCor || nc <= 3 I = (cyl.radius > MaxR & SC < 0.7) | (cyl.radius > 1.2*MaxR); cyl.radius(I) = MaxR; Mod(I) = true; % For short branches modify with more restrictions if nc <= 3 I = (cyl.radius > 0.75*MaxR & SC < 0.7); if any(I) r = max(SC(I)/0.7.*cyl.radius(I),MinR); cyl.radius(I) = r; Mod(I) = true; end end end %% Use taper correction to modify radius of too small and large cylinders % Adjust radii if a small SurfCov and high SurfCov in the previous and % following cylinders for i = 2:nc-1 if SC(i) < 0.7 && SC(i-1) >= 0.7 && SC(i+1) >= 0.7 cyl.radius(i) = 0.5*(cyl.radius(i-1)+cyl.radius(i+1)); Mod(i) = true; end end %% Use taper correction to modify radius of too small and large cylinders if inputs.TaperCor if max(cyl.radius) < 0.001 %% Adjust radii of thin branches to be linearly decreasing if nc > 2 r = sort(cyl.radius); r = r(2:end-1); a = 2*mean(r); if a > max(r) a = min(0.01,max(r)); end b = min(0.5*min(cyl.radius),0.001); cyl.radius = linspace(a,b,nc)'; elseif nc > 1 r = max(cyl.radius); cyl.radius = [r; 0.5*r]; end Mod = true(nc,1); elseif nc > 4 %% Parabola adjustment of maximum and minimum % Define parabola taper shape as maximum (and minimum) radii for % the cylinders with low surface coverage branchlen = sum(cyl.length(1:nc)); % branch length L = cyl.length/2+[0; cumsum(cyl.length(1:nc-1))]; Taper = [L; branchlen]; Taper(:,2) = [1.05*cyl.radius; MinR]; sc = [SC; 1]; % Least square fitting of parabola to "Taper": A = [sum(sc.*Taper(:,1).^4) sum(sc.*Taper(:,1).^2); ... sum(sc.*Taper(:,1).^2) sum(sc)]; y = [sum(sc.*Taper(:,2).*Taper(:,1).^2); sum(sc.*Taper(:,2))]; warning off x = A\y; warning on x(1) = min(x(1),-0.0001); % tapering from the base to the tip Ru = x(1)*L.^2+x(2); % upper bound parabola Ru( Ru < MinR ) = MinR; if max(Ru) > MaxR a = max(Ru); Ru = MaxR/a*Ru; end Rl = 0.75*Ru; % lower bound parabola Rl( Rl < MinR ) = MinR; % Modify radii based on parabola: % change values larger than the parabola-values when SC < 70%: I = cyl.radius > Ru & SC < 0.7; cyl.radius(I) = Ru(I)+(cyl.radius(I)-Ru(I)).*SC(I)/0.7; Mod(I) = true; % change values larger than the parabola-values when SC > 70% and % radius is over 33% larger than the parabola-value: I = cyl.radius > 1.333*Ru & SC >= 0.7; cyl.radius(I) = Ru(I)+(cyl.radius(I)-Ru(I)).*SC(I); Mod(I) = true; % change values smaller than the downscaled parabola-values: I = (cyl.radius < Rl & SC < 0.7) | (cyl.radius < 0.5*Rl); cyl.radius(I) = Rl(I); Mod(I) = true; else %% Adjust radii of short branches to be linearly decreasing R = cyl.radius; if nnz(SC >= 0.7) > 1 a = max(R(SC >= 0.7)); b = min(R(SC >= 0.7)); elseif nnz(SC >= 0.7) == 1 a = max(R(SC >= 0.7)); b = min(R); else a = sum(R.*SC/sum(SC)); b = min(R); end Ru = linspace(a,b,nc)'; I = SC < 0.7 & ~Mod; cyl.radius(I) = Ru(I)+(R(I)-Ru(I)).*SC(I)/0.7; Mod(I) = true; end end %% Modify starting points by optimising them for given radius and axis nr = size(Regs,1); for i = 1:nc if Mod(i) if nr == nc Reg = Regs{i}; elseif i > 1 Reg = Regs{i-1}; end if abs(cyl.radius(i)-cyl.radius0(i)) > 0.005 && ... (nr == nc || (nr < nc && i > 1)) P = Reg-cyl.start(i,:); [U,V] = orthonormal_vectors(cyl.axis(i,:)); P = P*[U V]; cir = least_squares_circle_centre(P,[0 0],cyl.radius(i)); if cir.conv && cir.rel cyl.start(i,:) = cyl.start(i,:)+cir.point(1)*U'+cir.point(2)*V'; cyl.mad(i,1) = cir.mad; [~,V,h] = distances_to_line(Reg,cyl.axis(i,:),cyl.start(i,:)); if min(h) < -0.001 cyl.length(i) = max(h)-min(h); cyl.start(i,:) = cyl.start(i,:)+min(h)*cyl.axis(i,:); [~,V,h] = distances_to_line(Reg,cyl.axis(i,:),cyl.start(i,:)); end a = max(0.02,0.2*cyl.radius(i)); nl = ceil(cyl.length(i)/a); nl = max(nl,4); ns = ceil(2*pi*cyl.radius(i)/a); ns = max(ns,10); ns = min(ns,36); cyl.SurfCov(i,1) = surface_coverage2(... cyl.axis(i,:),cyl.length(i),V,h,nl,ns); end end end end %% Continuous branches % Make cylinders properly "continuous" by moving the starting points % Move the starting point to the plane defined by parent cylinder's top if nc > 1 for j = 2:nc U = cyl.start(j,:)-cyl.start(j-1,:)-cyl.length(j-1)*cyl.axis(j-1,:); if (norm(U) > 0.0001) % First define vector V and W which are orthogonal to the % cylinder axis N N = cyl.axis(j,:)'; if norm(N) > 0 [V,W] = orthonormal_vectors(N); % Now define the new starting point x = [N V W]\U'; cyl.start(j,:) = cyl.start(j,:)-x(1)*N'; if x(1) > 0 cyl.length(j) = cyl.length(j)+x(1); elseif cyl.length(j)+x(1) > 0 cyl.length(j) = cyl.length(j)+x(1); end end end end end %% Connect far away first cylinder to the parent if ~isempty(parcyl.radius) [d,V,h,B] = distances_to_line(cyl.start(1,:),parcyl.axis,parcyl.start); d = d-parcyl.radius; if d > 0.001 taper = cyl.start(1,:); E = taper+cyl.length(1)*cyl.axis(1,:); V = parcyl.radius*V/norm(V); if h >= 0 && h <= parcyl.length cyl.start(1,:) = parcyl.start+B+V; elseif h < 0 cyl.start(1,:) = parcyl.start+V; else cyl.start(1,:) = parcyl.start+parcyl.length*parcyl.axis+V; end cyl.axis(1,:) = E-cyl.start(1,:); cyl.length(1) = norm(cyl.axis(1,:)); cyl.axis(1,:) = cyl.axis(1,:)/cyl.length(1); end end % End of function end
github
InverseTampere/TreeQSM-master
correct_segments.m
.m
TreeQSM-master/src/main_steps/correct_segments.m
30,167
utf_8
3e6a16d9d908979779eec4d463d9d735
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function segment = correct_segments(P,cover,segment,inputs,RemSmall,ModBases,AddChild) % --------------------------------------------------------------------- % CORRECT_SEGMENTS.M Corrects the given segmentation. % % Version 2.0.2 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % First segments are modified by making them as long as possible. Here the % stem and 1-st order branches are handled differently as there is also % restriction to how "curved" they can be in the sense of ratio % total_length/base_tip_distance. Then, optionally, small segments that % are close to their parent and have no children are removed as unclear % (are they part of the parent or real segments?). % Then, optionally, the bases of branches are modified by % expanding them into parent segment in order to remove ledges from the % parent from locations of the branches. % Inputs: % P Point cloud % cover Cover sets % segment Segments % inputs The input structure % RemSmall If True, small unclear segments are removed % ModBase If True, bases of the segments are modified % AddChild If True, the expanded (modified) base is added to the child segment. % If AddChild = false and ModBase = true, then the expanded part is % removed from both the child and the parent. % Outputs: % segment Segments % --------------------------------------------------------------------- % Changes from version 2.0.1 to 2.0.2, 2 May 2022: % 1) Added "if ~isempty(SegChildren)... " statement to the % "modify_topology" subfunction where next branch is selected based on % the increasing branching order to prevent a rare bug % Changes from version 2.0.0 to 2.0.1, 2 Oct 2019: % 1) Main function: added "if SPar(i,1) > 1"-statement to ModBase --> % NotAddChild if nargin == 4 RemSmall = true; ModBases = false; elseif nargin == 5 ModBases = false; elseif nargin == 6 AddChild = false; end Bal = cover.ball; Segs = segment.segments; SPar = segment.ParentSegment; SChi = segment.ChildSegment; Ce = P(cover.center,:); %% Make stem and branches as long as possible if RemSmall [Segs,SPar,SChi] = modify_topology(P,Ce,Bal,Segs,SPar,SChi,inputs.PatchDiam2Max); else [Segs,SPar,SChi] = modify_topology(P,Ce,Bal,Segs,SPar,SChi,inputs.PatchDiam1); end %% Remove small child segments if RemSmall [Segs,SPar,SChi] = remove_small(Ce,Segs,SPar,SChi); end % Check the consistency of empty vector sizes ns = size(Segs,1); for i = 1:ns if isempty(SChi{i}) SChi{i} = zeros(0,1,'uint32'); end end if ModBases %% Modify the base of the segments ns = size(Segs,1); base = cell(200,1); if AddChild % Add the expanded base to the child and remove it from the parent for i = 2:ns SegC = Segs{i}; SegP = Segs{SPar(i,1)}; [SegP,Base] = modify_parent(P,Bal,Ce,SegP,SegC,SPar(i,2),inputs.PatchDiam1,base); Segs{SPar(i,1)} = SegP; SegC{1} = Base; Segs{i} = SegC; end else % Only remove the expanded base from the parent for i = 2:ns if SPar(i,1) > 1 SegC = Segs{i}; SegP = Segs{SPar(i,1)}; SegP = modify_parent(P,Bal,Ce,SegP,SegC,SPar(i,2),inputs.PatchDiam2Max,base); Segs{SPar(i,1)} = SegP; end end end end SPar = SPar(:,1); % Modify the size and type of SChi and Segs, if necessary ns = size(Segs,1); for i = 1:ns C = SChi{i}; if size(C,2) > size(C,1) && size(C,1) > 0 SChi{i} = uint32(C'); elseif size(C,1) == 0 || size(C,2) == 0 SChi{i} = zeros(0,1,'uint32'); else SChi{i} = uint32(C); end S = Segs{i}; for j = 1:size(S,1) S{j} = uint32(S{j}); end Segs{i} = S; end segment.segments = Segs; segment.ParentSegment = SPar; segment.ChildSegment = SChi; %% Generate segment data for the points np = size(P,1); ns = size(Segs,1); % Define for each point its segment if ns <= 2^16 SegmentOfPoint = zeros(np,1,'uint16'); else SegmentOfPoint = zeros(np,1,'uint32'); end for i = 1:ns S = Segs{i}; S = vertcat(S{:}); SegmentOfPoint(vertcat(Bal{S})) = i; end segment.SegmentOfPoint = SegmentOfPoint; % Define the indexes of the segments up to 3rd-order C = SChi{1}; segment.branch1indexes = C; if ~isempty(C) C = vertcat(SChi{C}); segment.branch2indexes = C; if ~isempty(C) C = vertcat(SChi{C}); segment.branch3indexes = C; else segment.branch3indexes = zeros(0,1); end else segment.branch2indexes = zeros(0,1); segment.branch3indexes = zeros(0,1); end end % End of main function function StemTop = search_stem_top(P,Ce,Bal,Segs,SPar,dmin) % Search the stem's top segment such that the resulting stem % 1) is one the highest segments (goes to the top of the tree) % 2) is horizontally close to the bottom of the stem (goes straigth up) % 3) has length close to the distance between its bottom and top (is not too curved) nseg = size(Segs,1); SegHeight = zeros(nseg,1); % heights of the tips of the segments HorDist = zeros(nseg,1); % horizontal distances of the tips from stem's center s = Segs{1}{1}; StemCen = average(Ce(s,:)); % center (x,y) of stem base for i = 1:nseg S = Segs{i}{end}(1); SegHeight(i) = Ce(S,3); HorDist(i) = norm(Ce(S,1:2)-StemCen(1:2)); end Top = max(SegHeight); % the height of the highest tip HeiDist = Top-SegHeight; % the height difference to "Top" Dist = sqrt((HorDist.^2+HeiDist.^2)); % Distance to the top LenDisRatio = 2; SearchDist = 0.5; MaxLenDisRatio = 1.05; % the maximum acceptable length/distance ratio of segments SubSegs = zeros(100,1); % Segments to be combined to form the stem while LenDisRatio > MaxLenDisRatio StemTops = (1:1:nseg)'; I = Dist < SearchDist; % only segments with distance to the top < 0.5m while ~any(I) SearchDist = SearchDist+0.5; I = Dist < SearchDist; end StemTops = StemTops(I); % Define i-1 alternative stems from StemTops n = length(StemTops); Stems = cell(n,1); Segment = cell(3000,1); for j = 1:n Seg = Segs{1}; spar = SPar; if StemTops(j) ~= 1 % Tip point was not in the current segment, modify segments SubSegs(1) = StemTops(j); nsegs = 1; segment = StemTops(j); while segment ~= 1 segment = SPar(segment,1); nsegs = nsegs+1; SubSegs(nsegs) = segment; end % Modify stem a = size(Seg,1); Segment(1:a) = Seg; a = a+1; for i = 1:nsegs-2 I = SubSegs(nsegs-i); % segment to be combined to the first segment J = SubSegs(nsegs-i-1); % above segment's child to be combined next SP = spar(I,2); % layer index of the child in the parent SegC = Segs{I}; sp = spar(J,2); % layer index of the child's child in the child if SP >= a-2 % Use the whole parent Segment(a:a+sp-1) = SegC(1:sp); spar(J,2) = a+sp-1; a = a+sp; else % Use only bottom part of the parent Segment(SP+1:SP+sp) = SegC(1:sp); a = SP+sp+1; spar(J,2) = SP+sp; end SubSegs(nsegs-i) = 1; end % Combine the last segment to the branch I = SubSegs(1); SP = spar(I,2); SegC = Segs{I}; nc = size(SegC,1); if SP >= a-2 % Use the whole parent Segment(a:a+nc-1) = SegC; a = a+nc-1; else % divide the parent segment into two parts Segment(SP+1:SP+nc) = SegC; a = SP+nc; end Stems{j,1} = Segment(1:a); else Stems{j,1} = Seg; end end % Calculate the lengths of the candidate stems N = ceil(0.5/dmin/1.4); % number of layers used for linear length approximation Lengths = zeros(n,1); Heights = zeros(n,1); for i = 1:n Seg = Stems{i,1}; ns = size(Seg,1); if ceil(ns/N) > floor(ns/N) m = ceil(ns/N); else m = ceil(ns/N)+1; end Nodes = zeros(m,3); for j = 1:m I = (j-1)*N+1; if I > ns I = ns; end S = Seg{I}; if length(S) > 1 Nodes(j,:) = average(Ce(S,:)); else S = Bal{S}; Nodes(j,:) = average(P(S,:)); end end V = Nodes(2:end,:)-Nodes(1:end-1,:); Lengths(i) = sum(sqrt(sum(V.*V,2))); V = Nodes(end,:)-Nodes(1,:); Heights(i) = norm(V); end LenDisRatio = Lengths./Heights; [LenDisRatio,I] = min(LenDisRatio); StemTop = StemTops(I); SearchDist = SearchDist+1; if SearchDist > 3 MaxLenDisRatio = 1.1; if SearchDist > 5 MaxLenDisRatio = 1.15; if SearchDist > 7 MaxLenDisRatio = 5; end end end end end % End subfunction function BranchTop = search_branch_top(P,Ce,Bal,Segs,SPar,SChi,dmin,BI) % Search the end segment for branch such that the resulting branch % 1) has length close to the distance between its bottom and top % 2) has distance close to the farthest segment end % Inputs % BI Branch (segment) index % Outputs % BranchTop The index of the segment forming the tip of the branch % originating from the base of the given segment BI % Define all the sub-segments of the given segments ns = size(Segs,1); Segments = zeros(ns,1); % the given segment and its sub-segments Segments(1) = BI; t = 2; C = SChi{BI}; while ~isempty(C) n = length(C); Segments(t:t+n-1) = C; C = vertcat(SChi{C}); t = t+n; end if t > 2 t = t-n; end Segments = Segments(1:t); % Determine linear distances from the segment tips to the base of the given % segment LinearDist = zeros(t,1); % linear distances from the Seg = Segs{Segments(1)}; BranchBase = average(Ce(Seg{1},:)); % center of branch's base for i = 1:t Seg = Segs{Segments(i)}; C = average(Ce(Seg{end},:)); % tip LinearDist(i) = norm(C-BranchBase); end LinearDist = LinearDist(1:t); % Sort the segments according their linear distance, from longest to % shortest [LinearDist,I] = sort(LinearDist,'descend'); Segments = Segments(I); % Define alternative branches from Segments Branches = cell(t,1); % the alternative segments as cell layers SubSegs = zeros(100,1); % Segments to be combined Segment = cell(3000,1); for j = 1:t Seg = Segs{BI}; spar = SPar; if Segments(j) ~= BI % Tip point was not in the current segment, modify segments SubSegs(1) = Segments(j); k = 1; S = Segments(j); while S ~= BI S = SPar(S,1); k = k+1; SubSegs(k) = S; end % Modify branch a = size(Seg,1); Segment(1:a) = Seg; a = a+1; for i = 1:k-2 I = SubSegs(k-i); % segment to be combined to the first segment J = SubSegs(k-i-1); % above segment's child to be combined next SP = spar(I,2); % layer index of the child in the parent SegC = Segs{I}; sp = spar(J,2); % layer index of the child's child in the child if SP >= a-2 % Use the whole parent Segment(a:a+sp-1) = SegC(1:sp); spar(J,2) = a+sp-1; a = a+sp; else % Use only bottom part of the parent Segment(SP+1:SP+sp) = SegC(1:sp); a = SP+sp+1; spar(J,2) = SP+sp; end SubSegs(k-i) = 1; end % Combine the last segment to the branch I = SubSegs(1); SP = spar(I,2); SegC = Segs{I}; L = size(SegC,1); if SP >= a-2 % Use the whole parent Segment(a:a+L-1) = SegC; a = a+L-1; else % divide the parent segment into two parts Segment(SP+1:SP+L) = SegC; a = SP+L; end Branches{j,1} = Segment(1:a); else Branches{j,1} = Seg; end end % Calculate the lengths of the candidate branches. Stop, if possible, when % the ratio length/linear distance is less 1.2 (branch is quite straight) N = ceil(0.25/dmin/1.4); % number of layers used for linear length approximation i = 1; % running index for while loop Continue = true; % continue while loop as long as "Continue" is true Lengths = zeros(t,1); % linear lengths of the branches while i <= t && Continue % Approximate the length with line segments connecting nodes along % the segment Seg = Branches{i,1}; ns = size(Seg,1); if ceil(ns/N) > floor(ns/N) m = ceil(ns/N); else m = ceil(ns/N)+1; end Nodes = zeros(m,3); for j = 1:m I = (j-1)*N+1; if I > ns I = ns; end S = Seg{I}; if length(S) > 1 Nodes(j,:) = average(Ce(S,:)); else S = Bal{S}; Nodes(j,:) = average(P(S,:)); end end V = Nodes(2:end,:)-Nodes(1:end-1,:); % line segments Lengths(i) = sum(sqrt(sum(V.*V,2))); % Continue as long as the length is less than 20% longer than the linear dist. % and the linear distance is over 75% of the maximum if Lengths(i)/LinearDist(i) < 1.20 && LinearDist(i) > 0.75*LinearDist(1) Continue = false; BranchTop = Segments(i); end i = i+1; end % If no suitable segment was found, try first with less strict conditions, % and if that does not work, then select the one with the largest linear distance if Continue L = Lengths./LinearDist; i = 1; while i <= t && L(i) > 1.4 && LinearDist(i) > 0.75*LinearDist(1) i = i+1; end if i <= t BranchTop = Segments(i); else BranchTop = Segments(1); end end end % End subfunction function [Segs,SPar,SChi] = modify_topology(P,Ce,Bal,Segs,SPar,SChi,dmin) % Make stem and branches as long as possible ns = size(Segs,1); Fal = false(2*ns,1); nc = ceil(ns/5); SubSegments = zeros(nc,1); % for searching sub-segments SegInd = 1; % the segment under modification UnMod = true(ns,1); UnMod(SegInd) = false; BranchOrder = 0; ChildSegInd = 1; % index of the child segments under modification while any(UnMod) ChildSegs = SChi{SegInd}; % child segments of the segment under modification if size(ChildSegs,1) < size(ChildSegs,2) ChildSegs = ChildSegs'; SChi{SegInd} = ChildSegs; end if ~isempty(Segs(SegInd)) && ~isempty(ChildSegs) if SegInd > 1 && BranchOrder > 1 % 2nd-order and higher branches % Search the tip of the sub-branches with biggest linear % distance from the current branch's base SubSegments(1) = SegInd; NSubSegs = 2; while ~isempty(ChildSegs) n = length(ChildSegs); SubSegments(NSubSegs:NSubSegs+n-1) = ChildSegs; ChildSegs = vertcat(SChi{ChildSegs}); NSubSegs = NSubSegs+n; end if NSubSegs > 2 NSubSegs = NSubSegs-n; end % Find tip-points Top = zeros(NSubSegs,3); for i = 1:NSubSegs Top(i,:) = Ce(Segs{SubSegments(i)}{end}(1),:); end % Define bottom of the branch BotLayer = Segs{SegInd}{1}; Bottom = average(Ce(BotLayer,:)); % End segment is the segment whose tip has greatest distance to % the bottom of the branch V = mat_vec_subtraction(Top,Bottom); d = sum(V.*V,2); [~,I] = max(d); TipSeg = SubSegments(I(1)); elseif SegInd > 1 && BranchOrder <= 1 % first order branches TipSeg = search_branch_top(P,Ce,Bal,Segs,SPar,SChi,dmin,SegInd); else % Stem TipSeg = search_stem_top(P,Ce,Bal,Segs,SPar,dmin); end if TipSeg ~= SegInd % Tip point was not in the current segment, modify segments SubSegments(1) = TipSeg; NSubSegs = 1; while TipSeg ~= SegInd TipSeg = SPar(TipSeg,1); NSubSegs = NSubSegs+1; SubSegments(NSubSegs) = TipSeg; end % refine branch for i = 1:NSubSegs-2 I = SubSegments(NSubSegs-i); % segment to be combined to the first segment J = SubSegments(NSubSegs-i-1); % above segment's child to be combined next SP = SPar(I,2); % layer index of the child in the parent SegP = Segs{SegInd}; SegC = Segs{I}; N = size(SegP,1); sp = SPar(J,2); % layer index of the child's child in the child if SP >= N-2 % Use the whole parent Segs{SegInd} = [SegP; SegC(1:sp)]; if sp < size(SegC,1) % use only part of the child segment Segs{I} = SegC(sp+1:end); SPar(I,2) = N+sp; ChildSegs = SChi{I}; K = SPar(ChildSegs,2) <= sp; c = ChildSegs(~K); SChi{I} = c; SPar(c,2) = SPar(c,2)-sp; ChildSegs = ChildSegs(K); SChi{SegInd} = [SChi{SegInd}; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = N+SPar(ChildSegs,2); else % use the whole child segment Segs{I} = cell(0,1); SPar(I,1) = 0; UnMod(I) = false; ChildSegs = SChi{I}; SChi{I} = zeros(0,1); c = set_difference(SChi{SegInd},I,Fal); SChi{SegInd} = [c; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = N+SPar(ChildSegs,2); end SubSegments(NSubSegs-i) = SegInd; else % divide the parent segment into two parts ns = ns+1; Segs{ns} = SegP(SP+1:end); % the top part of the parent forms a new segment SPar(ns,1) = SegInd; SPar(ns,2) = SP; UnMod(ns) = true; Segs{SegInd} = [SegP(1:SP); SegC(1:sp)]; ChildSegs = SChi{SegInd}; if size(ChildSegs,1) < size(ChildSegs,2) ChildSegs = ChildSegs'; end K = SPar(ChildSegs,2) > SP; SChi{SegInd} = ChildSegs(~K); ChildSegs = ChildSegs(K); SChi{ns} = ChildSegs; SPar(ChildSegs,1) = ns; SPar(ChildSegs,2) = SPar(ChildSegs,2)-SP; SChi{SegInd} = [SChi{SegInd}; ns]; if sp < size(SegC,1) % use only part of the child segment Segs{I} = SegC(sp+1:end); SPar(I,2) = SP+sp; ChildSegs = SChi{I}; K = SPar(ChildSegs,2) <= sp; SChi{I} = ChildSegs(~K); SPar(ChildSegs(~K),2) = SPar(ChildSegs(~K),2)-sp; ChildSegs = ChildSegs(K); SChi{SegInd} = [SChi{SegInd}; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = SP+SPar(ChildSegs,2); else % use the whole child segment Segs{I} = cell(0,1); SPar(I,1) = 0; UnMod(I) = false; ChildSegs = SChi{I}; c = set_difference(SChi{SegInd},I,Fal); SChi{SegInd} = [c; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = SP+SPar(ChildSegs,2); end SubSegments(NSubSegs-i) = SegInd; end end % Combine the last segment to the branch I = SubSegments(1); SP = SPar(I,2); SegP = Segs{SegInd}; SegC = Segs{I}; N = size(SegP,1); if SP >= N-3 % Use the whole parent Segs{SegInd} = [SegP; SegC]; Segs{I} = cell(0); SPar(I,1) = 0; UnMod(I) = false; ChildSegs = SChi{I}; if size(ChildSegs,1) < size(ChildSegs,2) ChildSegs = ChildSegs'; end c = set_difference(SChi{SegInd},I,Fal); SChi{SegInd} = [c; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = N+SPar(ChildSegs,2); else % divide the parent segment into two parts ns = ns+1; Segs{ns} = SegP(SP+1:end); SPar(ns,:) = [SegInd SP]; Segs{SegInd} = [SegP(1:SP); SegC]; Segs{I} = cell(0); SPar(I,1) = 0; UnMod(ns) = true; UnMod(I) = false; ChildSegs = SChi{SegInd}; K = SPar(ChildSegs,2) > SP; SChi{SegInd} = [ChildSegs(~K); ns]; ChildSegs = ChildSegs(K); SChi{ns} = ChildSegs; SPar(ChildSegs,1) = ns; SPar(ChildSegs,2) = SPar(ChildSegs,2)-SP; ChildSegs = SChi{I}; c = set_difference(SChi{SegInd},I,Fal); SChi{SegInd} = [c; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = SP+SPar(ChildSegs,2); end end UnMod(SegInd) = false; else UnMod(SegInd) = false; end % Select the next branch, use increasing branching order if BranchOrder > 0 && any(UnMod(SegChildren)) ChildSegInd = ChildSegInd+1; SegInd = SegChildren(ChildSegInd); elseif BranchOrder == 0 BranchOrder = BranchOrder+1; SegChildren = SChi{1}; if ~isempty(SegChildren) SegInd = SegChildren(1); else UnMod = false; end else BranchOrder = BranchOrder+1; i = 1; SegChildren = SChi{1}; while i < BranchOrder && ~isempty(SegChildren) i = i+1; L = cellfun('length',SChi(SegChildren)); Keep = L > 0; SegChildren = SegChildren(Keep); SegChildren = vertcat(SChi{SegChildren}); end I = UnMod(SegChildren); if any(I) SegChildren = SegChildren(I); SegInd = SegChildren(1); ChildSegInd = 1; end end end % Modify indexes by removing empty segments Empty = true(ns,1); for i = 1:ns if isempty(Segs{i}) Empty(i) = false; end end Segs = Segs(Empty); Ind = (1:1:ns)'; n = nnz(Empty); I = (1:1:n)'; Ind(Empty) = I; SPar = SPar(Empty,:); J = SPar(:,1) > 0; SPar(J,1) = Ind(SPar(J,1)); for i = 1:ns if Empty(i) ChildSegs = SChi{i}; if ~isempty(ChildSegs) ChildSegs = Ind(ChildSegs); SChi{i} = ChildSegs; end end end SChi = SChi(Empty); ns = n; % Modify SChi for i = 1:ns ChildSegs = SChi{i}; if size(ChildSegs,2) > size(ChildSegs,1) && size(ChildSegs,1) > 0 SChi{i} = ChildSegs'; elseif size(ChildSegs,1) == 0 || size(ChildSegs,2) == 0 SChi{i} = zeros(0,1); end Seg = Segs{i}; n = max(size(Seg)); for j = 1:n ChildSegs = Seg{j}; if size(ChildSegs,2) > size(ChildSegs,1) && size(ChildSegs,1) > 0 Seg{j} = ChildSegs'; elseif size(ChildSegs,1) == 0 || size(ChildSegs,2) == 0 Seg{j} = zeros(0,1); end end Segs{i} = Seg; end end % End of function function [Segs,SPar,SChi] = remove_small(Ce,Segs,SPar,SChi) % Removes small child segments % computes and estimate for stem radius at the base Segment = Segs{1}; % current or parent segment ns = size(Segment,1); % layers in the parent if ns > 10 EndL = 10; % ending layer index in parent else EndL = ns; end End = average(Ce(Segment{EndL},:)); % Center of end layer Start = average(Ce(Segment{1},:)); % Center of starting layer V = End-Start; % Vector between starting and ending centers V = V/norm(V); % normalize Sets = vertcat(Segment{1:EndL}); MaxRad = max(distances_to_line(Ce(Sets,:),V,Start)); Nseg = size(Segs,1); Fal = false(Nseg,1); Keep = true(Nseg,1); Sets = zeros(2000,1); for i = 1:Nseg if Keep(i) ChildSegs = SChi{i}; % child segments if ~isempty(ChildSegs) % child segments exists n = length(ChildSegs); % number of children Segment = Segs{i}; % current or parent segment ns = size(Segment,1); % layers in the parent for j = 1:n % check each child separately nl = SPar(ChildSegs(j),2); % the index of the layer in the parent the child begins if nl > 10 StartL = nl-10; % starting layer index in parent else StartL = 1; end if ns-nl > 10 EndL = nl+10; % end layer index in parent else EndL = ns; end End = average(Ce(Segment{EndL},:)); Start = average(Ce(Segment{StartL},:)); V = End-Start; % Vector between starting and ending centers V = V/norm(V); % normalize % cover sets of the child ChildSets = Segs{ChildSegs(j)}; NL = size(ChildSets,1); a = 1; for k = 1:NL S = ChildSets{k}; Sets(a:a+length(S)-1) = S; a = a+length(S); end ChildSets = Sets(1:a-1); % maximum distance in child distChild = max(distances_to_line(Ce(ChildSets,:),V,Start)); if distChild < MaxRad+0.06 % Select the cover sets of the parent between centers NL = EndL-StartL+1; a = 1; for k = 1:NL S = Segment{StartL+(k-1)}; Sets(a:a+length(S)-1) = S; a = a+length(S); end ParentSets = Sets(1:a-1); % maximum distance in parent distPar = max(distances_to_line(Ce(ParentSets,:),V,Start)); if (distChild-distPar < 0.02) || (distChild/distPar < 1.2 && distChild-distPar < 0.06) ChildChildSegs = SChi{ChildSegs(j)}; nc = length(ChildChildSegs); if nc == 0 % Remove, no child segments Keep(ChildSegs(j)) = false; Segs{ChildSegs(j)} = zeros(0,1); SPar(ChildSegs(j),:) = zeros(1,2); SChi{i} = set_difference(ChildSegs,ChildSegs(j),Fal); else L = SChi(ChildChildSegs); L = vertcat(L{:}); % child child segments if isempty(L) J = false(nc,1); for k = 1:nc segment = Segs{ChildChildSegs(k)}; if isempty(segment) J(k) = true; else segment1 = [vertcat(segment{:}); ParentSets]; distSeg = max(distances_to_line(Ce(segment1,:),V,Start)); if (distSeg-distPar < 0.02) || (distSeg/distPar < 1.2 && distSeg-distPar < 0.06) J(k) = true; end end end if all(J) % Remove ChildChildSegs1 = [ChildChildSegs; ChildSegs(j)]; nc = length(ChildChildSegs1); Segs(ChildChildSegs1) = cell(nc,1); Keep(ChildChildSegs1) = false; SPar(ChildChildSegs1,:) = zeros(nc,2); d = set_difference(ChildSegs,ChildSegs(j),Fal); SChi{i} = d; SChi(ChildChildSegs1) = cell(nc,1); end end end end end end end if i == 1 MaxRad = MaxRad/2; end end end % Modify segments and their indexing Segs = Segs(Keep); n = nnz(Keep); Ind = (1:1:Nseg)'; J = (1:1:n)'; Ind(Keep) = J; Ind(~Keep) = 0; SPar = SPar(Keep,:); J = SPar(:,1) > 0; SPar(J,1) = Ind(SPar(J,1)); % Modify SChi for i = 1:Nseg if Keep(i) ChildSegs = SChi{i}; if ~isempty(ChildSegs) ChildSegs = nonzeros(Ind(ChildSegs)); if size(ChildSegs,1) < size(ChildSegs,2) SChi{i} = ChildSegs'; else SChi{i} = ChildSegs; end else SChi{i} = zeros(0,1); end end end SChi = SChi(Keep); end % End of function function [SegP,Base] = modify_parent(P,Bal,Ce,SegP,SegC,nl,PatchDiam,base) % Expands the base of the branch backwards into its parent segment and % then removes the expansion from the parent segment. Base = SegC{1}; if ~isempty(Base) % Define the directions of the segments DirChi = segment_direction(Ce,SegC,1); DirPar = segment_direction(Ce,SegP,nl); if length(Base) > 1 BaseCent = average(Ce(Base,:)); db = distances_to_line(Ce(Base,:), DirChi', BaseCent); % distances of the sets in the base to the axis of the branch DiamBase = 2*max(db); % diameter of the base elseif length(Bal{Base}) > 1 BaseCent = average(P(Bal{Base},:)); db = distances_to_line(P(Bal{Base},:), DirChi', BaseCent); DiamBase = 2*max(db); else BaseCent = Ce(Base,:); DiamBase = 0; end % Determine the number of cover set layers "n" to be checked Angle = abs(DirChi'*DirPar); % abs of cosine of the angle between component and segment directions Nlayer = max([3,ceil(Angle*2*DiamBase/PatchDiam)]); if Nlayer > nl % can go only to the bottom of the segment Nlayer = nl; end % Check the layers layer = 0; base{1} = Base; while layer < Nlayer Sets = SegP{nl-layer}; Seg = average(Ce(Sets,:)); % mean of the cover sets' centers VBase = mat_vec_subtraction(Ce(Sets,:),BaseCent); % vectors from base's center to sets in the segment h = VBase*DirChi; B = repmat(DirChi',length(Sets),1); B = [h.*B(:,1) h.*B(:,2) h.*B(:,3)]; V = VBase-B; distSets = sqrt(sum(V.*V,2)); % distances of the sets in the segment to the axis of the branch VSeg = mat_vec_subtraction(Ce(Sets,:),Seg); % vectors from segments's center to sets in the segment lenBase = sqrt(sum(VBase.*VBase,2)); % lengths of VBase lenSeg = sqrt(sum(VSeg.*VSeg,2)); % lengths of VSeg if Angle < 0.9 K = lenBase < 1.1/(1-0.5*Angle^2)*lenSeg; % sets closer to the base's center than segment's center J = distSets < 1.25*DiamBase; % sets close enough to the axis of the branch I = K&J; else % branch almost parallel to parent I = distSets < 1.25*DiamBase; % only the distance to the branch axis counts end if all(I) || ~any(I) % stop the process if all the segment's or no segment's sets layer = Nlayer; else SegP{nl-layer} = Sets(not(I)); base{layer+2} = Sets(I); layer = layer+1; end end Base = vertcat(base{1:Nlayer+1}); end end % End of function function D = segment_direction(Ce,Seg,nl) % Defines the direction of the segment % Define bottom and top layers if nl-3 > 0 bot = nl-3; else bot = 1; end j = 1; while j < 3 && isempty(Seg{bot}) bot = bot+1; j = j+1; end if nl+2 <= size(Seg,1) top = nl+2; else top = size(Seg,1); end j = 1; while j < 3 && isempty(Seg{top}) top = top-1; j = j+1; end % Direction if top > bot Bot = average(Ce(Seg{bot},:)); Top = average(Ce(Seg{top},:)); V = Top-Bot; D = V'/norm(V); else D = zeros(3,1); end end % End of function
github
InverseTampere/TreeQSM-master
cover_sets.m
.m
TreeQSM-master/src/main_steps/cover_sets.m
10,655
utf_8
60e3bf5398cc4bf4ade45637819e26a7
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function cover = cover_sets(P,inputs,RelSize) % --------------------------------------------------------------------- % COVER_SETS.M Creates cover sets (surface patches) and their % neighbor-relation for a point cloud % % Version 2.0.1 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Covers the point cloud with small sets, which are along the surface, % such that each point belongs at most one cover set; i.e. the cover is % a partition of the point cloud. % % The cover is generated such that at first the point cloud is covered % with balls with radius "BallRad". This first cover is such that % 1) the minimum distance between the centers is "PatchDiam", and % 2) the maximum distance from any point to nearest center is also "PatchDiam". % Then the first cover of BallRad-balls is used to define a second cover: % each BallRad-ball "A" defines corresponding cover set "B" in the second cover % such that "B" contains those points of "A" that are nearer to the center of % "A" than any other center of BallRad-balls. The BallRad-balls also define % the neighbors for the second cover: Let CA and CB denote cover sets in % the second cover, and BA and BB their BallRad-balls. Then CB is % a neighbor of CA, and vice versa, if BA and CB intersect or % BB and CA intersect. % % Inputs: % P Point cloud % inputs Input stucture, the following fields are needed: % PatchDiam1 Minimum distance between centers of cover sets; i.e. the % minimum diameter of cover set in uniform covers. Does % not need nor use the third optional input "RelSize". % PatchDiam2Min Minimum diameter of cover sets for variable-size % covers. Needed if "RelSize" is given as input. % PatchDiam2Max Maximum diameter of cover sets for variable-size % covers. Needed if "RelSize" is given as input. % BallRad1 Radius of the balls used to generate the uniform cover. % These balls are also used to determine the neighbors % BallRad2 Maximum radius of the balls used to generate the % varibale-size cover. % nmin1, nmin2 Minimum number of points in a BallRad1- and % BallRad2-balls % RelSize Relative cover set size for each point % % Outputs: % cover Structure array containing the followin fields: % ball Cover sets, (n_sets x 1)-cell % center Center points of the cover sets, (n_sets x 1)-vector % neighbor Neighboring cover sets of each cover set, (n_sets x 1)-cell % Changes from version 2.0.0 to 2.0.1, 2 May 2022: % 1) Added comments and changed some variable names % 2) Enforced that input parameters are type double if ~isa(P,'double') P = double(P); end %% Large balls and centers np = size(P,1); Ball = cell(np,1); % Large balls for generation of the cover sets and their neighbors Cen = zeros(np,1,'uint32'); % the center points of the balls/cover sets NotExa = true(np,1); % the points not yet examined Dist = 1e8*ones(np,1); % distance of point to the closest center BoP = zeros(np,1,'uint32'); % the balls/cover sets the points belong nb = 0; % number of sets generated if nargin == 2 %% Same size cover sets everywhere BallRad = double(inputs.BallRad1); PatchDiamMax = double(inputs.PatchDiam1); nmin = double(inputs.nmin1); % Partition the point cloud into cubes for quick neighbor search [partition,CC] = cubical_partition(P,BallRad); % Generate the balls Radius = BallRad^2; MaxDist = PatchDiamMax^2; % random permutation of points, produces different covers for the same inputs: RandPerm = randperm(np); for i = 1:np if NotExa(RandPerm(i)) Q = RandPerm(i); % the center/seed point of the current cover set % Select the points in the cubical neighborhood of the seed: points = partition(CC(Q,1)-1:CC(Q,1)+1,CC(Q,2)-1:CC(Q,2)+1,CC(Q,3)-1:CC(Q,3)+1); points = vertcat(points{:}); % Compute distances of the points to the seed: V = [P(points,1)-P(Q,1) P(points,2)-P(Q,2) P(points,3)-P(Q,3)]; dist = sum(V.*V,2); % Select the points inside the ball: Inside = dist < Radius; if nnz(Inside) >= nmin ball = points(Inside); % the points forming the ball d = dist(Inside); % the distances of the ball's points core = (d < MaxDist); % the core points of the cover set NotExa(ball(core)) = false; % mark points as examined % define new ball: nb = nb+1; Ball{nb} = ball; Cen(nb) = Q; % Select which points belong to this ball, i.e. are closer this % seed than previously tested seeds: D = Dist(ball); % the previous distances closer = d < D; % which points are closer to this seed ball = ball(closer); % define the ball % update the ball and distance information of the points Dist(ball) = d(closer); BoP(ball) = nb; end end end else %% Use relative sizes (the size varies) % Partition the point cloud into cubes BallRad = double(inputs.BallRad2); PatchDiamMin = double(inputs.PatchDiam2Min); PatchDiamMax = double(inputs.PatchDiam2Max); nmin = double(inputs.nmin2); MRS = PatchDiamMin/PatchDiamMax; % minimum radius r = double(1.5*(double(min(RelSize))/256*(1-MRS)+MRS)*BallRad+1e-5); NE = 1+ceil(BallRad/r); if NE > 4 r = PatchDiamMax/4; NE = 1+ceil(BallRad/r); end [Partition,CC,~,Cubes] = cubical_partition(P,r,NE); I = RelSize == 0; % Don't use points with no size determined NotExa(I) = false; % Define random permutation of points (results in different covers for % same input) so that first small sets are generated RandPerm = zeros(np,1,'uint32'); I = RelSize <= 32; ind = uint32(1:1:np)'; I = ind(I); t1 = length(I); RandPerm(1:1:t1) = I(randperm(t1)); I = RelSize <= 128 & RelSize > 32; I = ind(I); t2 = length(I); RandPerm(t1+1:1:t1+t2) = I(randperm(t2)); t2 = t2+t1; I = RelSize > 128; I = ind(I); t3 = length(I); RandPerm(t2+1:1:t2+t3) = I(randperm(t3)); clearvars ind I Point = zeros(round(np/1000),1,'uint32'); e = BallRad-PatchDiamMax; for i = 1:np if NotExa(RandPerm(i)) Q = RandPerm(i); % the center/seed point of the current cover set % Compute the set size and the cubical neighborhood of the seed point: rs = double(RelSize(Q))/256*(1-MRS)+MRS; % relative radius MaxDist = PatchDiamMax*rs; % diameter of the cover set Radius = MaxDist+sqrt(rs)*e; % radius of the ball including the cover set N = ceil(Radius/r); % = number of cells needed to include the ball cubes = Cubes(CC(Q,1)-N:CC(Q,1)+N,CC(Q,2)-N:CC(Q,2)+N,CC(Q,3)-N:CC(Q,3)+N); I = cubes > 0; cubes = cubes(I); % Cubes forming the neighborhood Par = Partition(cubes); % cell-array of the points in the neighborhood % vertical catenation of the points from the cell-array S = cellfun('length',Par); stop = cumsum(S); start = [0; stop]+1; for k = 1:length(stop) Point(start(k):stop(k)) = Par{k}; end points = Point(1:stop(k)); % Compute the distance of the "points" to the seed: V = [P(points,1)-P(Q,1) P(points,2)-P(Q,2) P(points,3)-P(Q,3)]; dist = sum(V.*V,2); % Select the points inside the ball: Inside = dist < Radius^2; if nnz(Inside) >= nmin ball = points(Inside); % the points forming the ball d = dist(Inside); % the distances of the ball's points core = (d < MaxDist^2); % the core points of the cover set NotExa(ball(core)) = false; % mark points as examined % define new ball: nb = nb+1; Ball{nb} = ball; Cen(nb) = Q; % Select which points belong to this ball, i.e. are closer this % seed than previously tested seeds: D = Dist(ball); % the previous distances closer = d < D; % which points are closer to this seed ball = ball(closer); % define the ball % update the ball and distance information of the points Dist(ball) = d(closer); BoP(ball) = nb; end end end end Ball = Ball(1:nb,:); Cen = Cen(1:nb); clearvars RandPerm NotExa Dist %% Cover sets % Number of points in each ball and index of each point in its ball Num = zeros(nb,1,'uint32'); Ind = zeros(np,1,'uint32'); for i = 1:np if BoP(i) > 0 Num(BoP(i)) = Num(BoP(i))+1; Ind(i) = Num(BoP(i)); end end % Initialization of the "PointsInSets" PointsInSets = cell(nb,1); for i = 1:nb PointsInSets{i} = zeros(Num(i),1,'uint32'); end % Define the "PointsInSets" for i = 1:np if BoP(i) > 0 PointsInSets{BoP(i),1}(Ind(i)) = i; end end %% Neighbors % Define neighbors. Sets A and B are neighbors if the large ball of A % contains points of B. Notice that this is not a symmetric relation. Nei = cell(nb,1); Fal = false(nb,1); for i = 1:nb B = Ball{i}; % the points in the big ball of cover set "i" I = (BoP(B) ~= i); N = B(I); % the points of B not in the cover set "i" N = BoP(N); % select the unique elements of N: n = length(N); if n > 2 Include = true(n,1); for j = 1:n if ~Fal(N(j)) Fal(N(j)) = true; else Include(j) = false; end end Fal(N) = false; N = N(Include); elseif n == 2 if N(1) == N(2) N = N(1); end end Nei{i} = uint32(N); end % Make the relation symmetric by adding, if needed, A as B's neighbor % in the case B is A's neighbor for i = 1:nb N = Nei{i}; for j = 1:length(N) K = (Nei{N(j)} == i); if ~any(K) Nei{N(j)} = uint32([Nei{N(j)}; i]); end end end % Define output cover.ball = PointsInSets; cover.center = Cen; cover.neighbor = Nei; %% Display statistics %disp([' ',num2str(nb),' cover sets, points not covered: ',num2str(np-nnz(BoP))])
github
InverseTampere/TreeQSM-master
point_model_distance.m
.m
TreeQSM-master/src/main_steps/point_model_distance.m
5,875
utf_8
7b7c334df5d7577f4570e5e7df063761
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function pmdistance = point_model_distance(P,cylinder) % --------------------------------------------------------------------- % POINT_MODEL_DISTANCE.M Computes the distances of the points to the % cylinder model % % Version 2.1.1 % Latest update 8 Oct 2021 % % Copyright (C) 2015-2021 Pasi Raumonen % --------------------------------------------------------------------- % Changes from version 2.1.0 to 2.1.1, 8 Oct 2021: % 1) Changed the determinationa NE, the number of empty edge layers, so % that is now limited in size, before it is given as input for % cubical_partition function. % Changes from version 2.0.0 to 2.1.0, 26 Nov 2019: % 1) Bug fix: Corrected the computation of the output at the end of the % code so that trees without branches are computed correctly. % Cylinder data Rad = cylinder.radius; Len = cylinder.length; Sta = cylinder.start; Axe = cylinder.axis; BOrd = cylinder.BranchOrder; % Select randomly 25 % or max one million points for the distance comput. np0 = size(P,1); a = min(0.25*np0,1000000); I = logical(round(0.5/(1-a/np0)*rand(np0,1))); P = P(I,:); % Partition the points into cubes L = 2*median(Len); NE = max(3,min(10,ceil(max(Len)/L)))+3; [Partition,~,Info] = cubical_partition(P,L,NE); Min = Info(1:3); EL = Info(7); NE = Info(8); % Calculates the cube-coordinates of the starting points CC = floor([Sta(:,1)-Min(1) Sta(:,2)-Min(2) Sta(:,3)-Min(3)]/EL)+NE+1; % Compute the number of cubes needed for each starting point N = ceil(Len/L); % Correct N so that cube indexes are not too small or large I = CC(:,1) < N+1; N(I) = CC(I,1)-1; I = CC(:,2) < N+1; N(I) = CC(I,2)-1; I = CC(:,3) < N+1; N(I) = CC(I,3)-1; I = CC(:,1)+N+1 > Info(4); N(I) = Info(4)-CC(I,1)-1; I = CC(:,2)+N+1 > Info(5); N(I) = Info(5)-CC(I,2)-1; I = CC(:,3)+N+1 > Info(6); N(I) = Info(6)-CC(I,3)-1; % Calculate the distances to the cylinders n = size(Rad,1); np = size(P,1); Dist = zeros(np,2); % Distance and the closest cylinder of each points Dist(:,1) = 2; % Large distance initially Points = zeros(ceil(np/10),1,'int32'); % Auxiliary variable Data = cell(n,1); for i = 1:n Par = Partition(CC(i,1)-N(i):CC(i,1)+N(i),CC(i,2)-N(i):CC(i,2)+N(i),... CC(i,3)-N(i):CC(i,3)+N(i)); if N(i) > 1 S = cellfun('length',Par); I = S > 0; S = S(I); Par = Par(I); stop = cumsum(S); start = [0; stop]+1; for k = 1:length(stop) Points(start(k):stop(k)) = Par{k}(:); end points = Points(1:stop(k)); else points = vertcat(Par{:}); end [d,~,h] = distances_to_line(P(points,:),Axe(i,:),Sta(i,:)); d = abs(d-Rad(i)); Data{i} = [d h double(points)]; I = d < Dist(points,1); J = h >= 0; K = h <= Len(i); L = d < 0.5; M = I&J&K&L; points = points(M); Dist(points,1) = d(M); Dist(points,2) = i; end % Calculate the distances to the cylinders for points not yet calculated % because they are not "on side of cylinder for i = 1:n if ~isempty(Data{i}) d = Data{i}(:,1); h = Data{i}(:,2); points = Data{i}(:,3); I = d < Dist(points,1); J = h >= -0.1 & h <= 0; K = h <= Len(i)+0.1 & h >= Len(i); L = d < 0.5; M = I&(J|K)&L; points = points(M); Dist(points,1) = d(M); Dist(points,2) = i; end end % Select only the shortest 95% of distances for each cylinder N = zeros(n,1); O = zeros(np,1); for i = 1:np if Dist(i,2) > 0 N(Dist(i,2)) = N(Dist(i,2))+1; O(i) = N(Dist(i,2)); end end Cyl = cell(n,1); for i = 1:n Cyl{i} = zeros(N(i),1); end for i = 1:np if Dist(i,2) > 0 Cyl{Dist(i,2)}(O(i)) = i; end end DistCyl = zeros(n,1); % Average point distance to each cylinder for i = 1:n I = Cyl{i}; m = length(I); if m > 19 % select the smallest 95% of distances d = sort(Dist(I,1)); DistCyl(i) = mean(d(1:floor(0.95*m))); elseif m > 0 DistCyl(i) = mean(Dist(I,1)); end end % Define the output pmdistance.CylDist = single(DistCyl); pmdistance.median = median(DistCyl(:,1)); pmdistance.mean = mean(DistCyl(:,1)); pmdistance.max = max(DistCyl(:,1)); pmdistance.std = std(DistCyl(:,1)); T = BOrd == 0; B1 = BOrd == 1; B2 = BOrd == 2; B = DistCyl(~T,1); T = DistCyl(T,1); B1 = DistCyl(B1,1); B2 = DistCyl(B2,1); pmdistance.TrunkMedian = median(T); pmdistance.TrunkMean = mean(T); pmdistance.TrunkMax = max(T); pmdistance.TrunkStd = std(T); if ~isempty(B) pmdistance.BranchMedian = median(B); pmdistance.BranchMean = mean(B); pmdistance.BranchMax = max(B); pmdistance.BranchStd = std(B); else pmdistance.BranchMedian = 0; pmdistance.BranchMean = 0; pmdistance.BranchMax = 0; pmdistance.BranchStd = 0; end if ~isempty(B1) pmdistance.Branch1Median = median(B1); pmdistance.Branch1Mean = mean(B1); pmdistance.Branch1Max = max(B1); pmdistance.Branch1Std = std(B1); else pmdistance.Branch1Median = 0; pmdistance.Branch1Mean = 0; pmdistance.Branch1Max = 0; pmdistance.Branch1Std = 0; end if ~isempty(B2) pmdistance.Branch2Median = median(B2); pmdistance.Branch2Mean = mean(B2); pmdistance.Branch2Max = max(B2); pmdistance.Branch2Std = std(B2); else pmdistance.Branch2Median = 0; pmdistance.Branch2Mean = 0; pmdistance.Branch2Max = 0; pmdistance.Branch2Std = 0; end
github
InverseTampere/TreeQSM-master
tree_sets.m
.m
TreeQSM-master/src/main_steps/tree_sets.m
28,351
utf_8
7b0856d9e0338fff9560f3d810b825c8
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [cover,Base,Forb] = tree_sets(P,cover,inputs,segment) % --------------------------------------------------------------------- % TREE_SETS.M Determines the base of the trunk and the cover sets % belonging to the tree, updates the neighbor-relation % % Version 2.3.0 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Determines the cover sets that belong to the tree. Determines also the % base of the tree and updates the neighbor-relation such that all of the % tree is connected, i.e., the cover sets belonging to the tree form a % single connected component. Optionally uses information from existing % segmentation to make sure that stem and 1st-, 2nd-, 3rd-order branches % are properly connnected. % --------------------------------------------------------------------- % Inputs: % P Point cloud % cover Cover sets, their centers and neighbors % PatchDiam Minimum diameter of the cover sets % OnlyTree Logical value indicating if the point cloud contains only % points from the tree to be modelled % segment Previous segments % % Outputs: % cover Cover sets with updated neigbors % Base Base of the trunk (the cover sets forming the base) % Forb Cover sets not part of the tree % --------------------------------------------------------------------- % Changes from version 2.2.0 to 2.3.0, 2 May 2022: % 1) Added new lines of code at the end of the "define_main_branches" to % make sure that the "Trunk" variable defines connected stem % Changes from version 2.1.0 to 2.2.0, 13 Aug 2020: % 1) "define_base_forb": Changed the base height specification from % 0.1*aux.Height to 0.02*aux.Height % 2) "define_base_forb": changed the cylinder fitting syntax corresponding % to the new input and outputs of "least_squares_cylinder" % 3) "make_tree_connected”: Removed "Trunk(Base) = false;" at the beginning % of the function as unnecessary and to prevent errors in a special case % where the Trunk is equal to Base. % 4) "make_tree_connected”: Removed from the end the generation of "Trunk" % again and the new call for the function % 5) "make_tree_connected”: Increased the minimum distance of a component % to be removed from 8m to 12m. % Changes from version 2.0.0 to 2.1.0, 11 Oct 2019: % 1) "define_main_branches": modified the size of neighborhood "balls0", % added seven lines of code, prevents possible error of too low or big % indexes on "Par" % 2) Increased the maximum base height from 0.5m to 1.5m % 3) "make_tree_connected": added at the end a call for the function itself, % if the tree is not yet connected, thus running the function again if % necessary %% Define auxiliar object clear aux aux.nb = max(size(cover.center)); % number of cover sets aux.Fal = false(aux.nb,1); aux.Ind = (1:1:aux.nb)'; aux.Ce = P(cover.center,1:3); % Coordinates of the center points aux.Hmin = min(aux.Ce(:,3)); aux.Height = max(aux.Ce(:,3))-aux.Hmin; %% Define the base of the trunk and the forbidden sets if nargin == 3 [Base,Forb,cover] = define_base_forb(P,cover,aux,inputs); else inputs.OnlyTree = true; [Base,Forb,cover] = define_base_forb(P,cover,aux,inputs,segment); end %% Define the trunk (and the main branches) if nargin == 3 [Trunk,cover] = define_trunk(cover,aux,Base,Forb,inputs); else [Trunk,cover] = define_main_branches(cover,segment,aux,inputs); end %% Update neighbor-relation to make the whole tree connected [cover,Forb] = make_tree_connected(cover,aux,Forb,Base,Trunk,inputs); end % End of the main function function [Base,Forb,cover] = define_base_forb(P,cover,aux,inputs,segment) % Defines the base of the stem and the forbidden sets (the sets containing % points not from the tree, i.e, ground, understory, etc.) Ce = aux.Ce; if inputs.OnlyTree && nargin == 4 % No ground in the point cloud, the base is the lowest part BaseHeight = min(1.5,0.02*aux.Height); I = Ce(:,3) < aux.Hmin+BaseHeight; Base = aux.Ind(I); Forb = aux.Fal; % Make sure the base, as the bottom of point cloud, is not in multiple parts Wb = max(max(Ce(Base,1:2))-min(Ce(Base,1:2))); Wt = max(max(Ce(:,1:2))-min(Ce(:,1:2))); k = 1; while k <= 5 && Wb > 0.3*Wt BaseHeight = BaseHeight-0.05; BaseHeight = max(BaseHeight,0.05); if BaseHeight > 0 I = Ce(:,3) < aux.Hmin+BaseHeight; else [~,I] = min(Ce(:,3)); end Base = aux.Ind(I); Wb = max(max(Ce(Base,1:2))-min(Ce(Base,1:2))); k = k+1; end elseif inputs.OnlyTree % Select the stem sets from the previous segmentation and define the % base BaseHeight = min(1.5,0.02*aux.Height); SoP = segment.SegmentOfPoint(cover.center); stem = aux.Ind(SoP == 1); I = Ce(stem,3) < aux.Hmin+BaseHeight; Base = stem(I); Forb = aux.Fal; else % Point cloud contains non-tree points. % Determine the base from the "height" and "density" of cover sets % by projecting the sets to the xy-plane Bal = cover.ball; Nei = cover.neighbor; % The vertices of the rectangle containing C Min = double(min(Ce)); Max = double(max(Ce(:,1:2))); % Number of rectangles with edge length "E" in the plane E = min(0.1,0.015*aux.Height); n = double(ceil((Max(1:2)-Min(1:2))/E)+1); % Calculates the rectangular-coordinates of the points px = floor((Ce(:,1)-Min(1))/E)+1; py = floor((Ce(:,2)-Min(2))/E)+1; % Sorts the points according a lexicographical order LexOrd = [px py-1]*[1 n(1)]'; [LexOrd,SortOrd] = sort(LexOrd); Partition = cell(n(1),n(2)); hei = zeros(n(1),n(2)); % "height" of the cover sets in the squares den = hei; % density of the cover sets in the squares baseden = hei; p = 1; % The index of the point under comparison while p <= aux.nb t = 1; while (p+t <= aux.nb) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end q = SortOrd(p); J = SortOrd(p:p+t-1); Partition{px(q),py(q)} = J; p = p+t; K = ceil(10*(Ce(J,3)-Min(3)+0.01)/(aux.Height-0.01)); B = K <= 2; K = unique(K); hei(px(q),py(q)) = length(K)/10; den(px(q),py(q)) = t; baseden(px(q),py(q)) = nnz(B); end den = den/max(max(den)); % normalize baseden = baseden/max(max(baseden)); % function whose maximum determines location of the trunk f = den.*hei.*baseden; % smooth the function by averaging over 8-neighbors x = zeros(n(1),n(2)); y = zeros(n(1),n(2)); for i = 2:n(1)-1 for j = 2:n(2)-1 f(i,j) = mean(mean(f(i-1:i+1,j-1:j+1))); x(i,j) = Min(1)+i*E; y(i,j) = Min(2)+j*E; end end f = f/max(max(f)); % Trunk location is around the maximum f-value I = f > 0.5; Trunk0 = Partition(I); % squares that contain the trunk Trunk0 = vertcat(Trunk0{:}); HBottom = min(Ce(Trunk0,3)); I = Ce(Trunk0,3) > HBottom+min(0.02*aux.Height,0.3); J = Ce(Trunk0,3) < HBottom+min(0.08*aux.Height,1.5); I = I&J; % slice close to bottom should contain the trunk Trunk = Trunk0(I); Trunk = union(Trunk,vertcat(Nei{Trunk})); % Expand with neighbors Trunk = union(Trunk,vertcat(Nei{Trunk})); % Expand with neighbors Trunk = union(Trunk,vertcat(Nei{Trunk})); % Expand with neighbors % Define connected components of Trunk and select the largest component [Comp,CS] = connected_components(Nei,Trunk,0,aux.Fal); [~,I] = max(CS); Trunk = Comp{I}; % Fit cylinder to Trunk I = Ce(Trunk,3) < HBottom+min(0.1*aux.Height,2); % Select the bottom part Trunk = Trunk(I); Trunk = union(Trunk,vertcat(Nei{Trunk})); Points = Ce(Trunk,:); c.start = mean(Points); c.axis = [0 0 1]; c.radius = mean(distances_to_line(Points,c.axis,c.start)); c = least_squares_cylinder(Points,c); % Remove far away points and fit new cylinder dis = distances_to_line(Points,c.axis,c.start); [~,I] = sort(abs(dis)); I = I(1:ceil(0.9*length(I))); Points = Points(I,:); Trunk = Trunk(I); c = least_squares_cylinder(Points,c); % Select the sets in the bottom part of the trunk and remove sets too % far away form the cylinder axis (also remove far away points from sets) I = Ce(Trunk0,3) < HBottom+min(0.04*aux.Height,0.6); TrunkBot = Trunk0(I); TrunkBot = union(TrunkBot,vertcat(Nei{TrunkBot})); TrunkBot = union(TrunkBot,vertcat(Nei{TrunkBot})); n = length(TrunkBot); Keep = true(n,1); % Keep sets that are close enough the axis a = max(0.06,0.2*c.radius); b = max(0.04,0.15*c.radius); for i = 1:n d = distances_to_line(Ce(TrunkBot(i),:),c.axis,c.start); if d < c.radius+a B = Bal{Trunk(i)}; d = distances_to_line(P(B,:),c.axis,c.start); I = d < c.radius+b; Bal{Trunk(i)} = B(I); else Keep(i) = false; end end TrunkBot = TrunkBot(Keep); % Select the above part of the trunk and combine with the bottom I = Ce(Trunk0,3) > HBottom+min(0.03*aux.Height,0.45); Trunk = Trunk0(I); Trunk = union(Trunk,vertcat(Nei{Trunk})); Trunk = union(Trunk,TrunkBot); BaseHeight = min(1.5,0.02*aux.Height); % Determine the base Bot = min(Ce(Trunk,3)); J = Ce(Trunk,3) < Bot+BaseHeight; Base = Trunk(J); % Determine "Forb", i.e, ground and non-tree sets by expanding Trunk % as much as possible Trunk = union(Trunk,vertcat(Nei{Trunk})); Forb = aux.Fal; Ground = setdiff(vertcat(Nei{Base}),Trunk); Ground = setdiff(union(Ground,vertcat(Nei{Ground})),Trunk); Forb(Ground) = true; Forb(Base) = false; Add = Forb; while any(Add) Add(vertcat(Nei{Add})) = true; Add(Forb) = false; Add(Trunk) = false; Forb(Add) = true; end % Try to expand the "Forb" more by adding all the bottom sets Bot = min(Ce(Trunk,3)); Ground = Ce(:,3) < Bot+0.03*aux.Height; Forb(Ground) = true; Forb(Trunk) = false; cover.ball = Bal; end end % End of function function [Trunk,cover] = define_trunk(cover,aux,Base,Forb,inputs) % This function tries to make sure that likely "route" of the trunk from % the bottom to the top is connected. However, this does not mean that the % final trunk follows this "route". Nei = cover.neighbor; Ce = aux.Ce; % Determine the output "Trunk" which indicates which sets are part of % likely trunk Trunk = aux.Fal; Trunk(Base) = true; % Expand Trunk from the base above with neighbors as long as possible Exp = Base; % the current "top" of Trunk % select the unique neighbors of Exp Exp = unique_elements([Exp; vertcat(Nei{Exp})],aux.Fal); I = Trunk(Exp); J = Forb(Exp); Exp = Exp(~I|~J); % Only non forbidden sets that are not already in Trunk Trunk(Exp) = true; % Add the expansion Exp to Trunk L = 0.25; % maximum height difference in Exp from its top to bottom H = max(Ce(Trunk,3))-L; % the minimum bottom heigth for the current Exp % true as long as the expansion is possible with original neighbors: FirstMod = true; while ~isempty(Exp) % Expand Trunk similarly as above as long as possible H0 = H; Exp0 = Exp; Exp = union(Exp,vertcat(Nei{Exp})); I = Trunk(Exp); Exp = Exp(~I); I = Ce(Exp,3) >= H; Exp = Exp(I); Trunk(Exp) = true; if ~isempty(Exp) H = max(Ce(Exp,3))-L; end % If the expansion Exp is empty and the top of the tree is still over 5 % meters higher, then search new neighbors from above if (isempty(Exp) || H < H0+inputs.PatchDiam1/2) && H < aux.Height-5 % Generate rectangular partition of the sets if FirstMod FirstMod = false; % The vertices of the rectangle containing C Min = double(min(Ce(:,1:2))); Max = double(max(Ce(:,1:2))); nb = size(Ce,1); % Number of rectangles with edge length "E" in the plane EdgeLenth = 0.2; NRect = double(ceil((Max-Min)/EdgeLenth)+1); % Calculates the rectangular-coordinates of the points px = floor((Ce(:,1)-Min(1))/EdgeLenth)+1; py = floor((Ce(:,2)-Min(2))/EdgeLenth)+1; % Sorts the points according a lexicographical order LexOrd = [px py-1]*[1 NRect(1)]'; [LexOrd,SortOrd] = sort(LexOrd); Partition = cell(NRect(1),NRect(2)); p = 1; % The index of the point under comparison while p <= nb t = 1; while (p+t <= nb) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end q = SortOrd(p); J = SortOrd(p:p+t-1); Partition{px(q),py(q)} = J; p = p+t; end end % Select the region that is connected to a set above it if ~isempty(Exp) Region = Exp; else Region = Exp0; end % Select the minimum and maximum rectangular coordinate of the % region X1 = min(px(Region)); if X1 <= 2 X1 = 3; end X2 = max(px(Region)); if X2 >= NRect(1)-1 X2 = NRect(1)-2; end Y1 = min(py(Region)); if Y1 <= 2 Y1 = 3; end Y2 = max(py(Region)); if Y2 >= NRect(2)-1 Y2 = NRect(2)-2; end % Select the sets in the 2 meter layer above the region sets = Partition(X1-2:X2+2,Y1-2:Y2+2); sets = vertcat(sets{:}); K = aux.Fal; K(sets) = true; % the potential sets I = Ce(:,3) > H; J = Ce(:,3) < H+2; I = I&J&K; I(Trunk) = false; % Must be non-Trunk sets SetsAbove = aux.Ind(I); % Search the closest connection between Region and SetsAbove that % is enough upward sloping (angle to the vertical has cosine larger % than 0.7) if ~isempty(SetsAbove) % Compute the distances and cosines of the connections n = length(Region); m = length(SetsAbove); Dist = zeros(n,m); Cos = zeros(n,m); for i = 1:n V = mat_vec_subtraction(Ce(SetsAbove,:),Ce(Region(i),:)); Len = sum(V.*V,2); v = normalize(V); Dist(i,:) = Len'; Cos(i,:) = v(:,3)'; end I = Cos > 0.7; % select those connection with large enough cosines % if not any, search with smaller cosines t = 0; while ~any(I) t = t+1; I = Cos > 0.7-t*0.05; end % Search the minimum distance Dist(~I) = 3; if n > 1 && m > 1 [d,I] = min(Dist); [~,J] = min(d); I = I(J); elseif n == 1 && m > 1 [~,J] = min(Dist); I = 1; elseif m == 1 && n < 1 [~,I] = min(Dist); J = 1; else I = 1; % the set in component to be connected J = 1; % the set in "trunk" to be connected end % Join to "SetsAbove" I = Region(I); J = SetsAbove(J); % make the connection Nei{I} = [Nei{I}; J]; Nei{J} = [Nei{J}; I]; % Expand "Trunk" again Exp = union(Region,vertcat(Nei{Region})); I = Trunk(Exp); Exp = Exp(~I); I = Ce(Exp,3) >= H; Exp = Exp(I); Trunk(Exp) = true; H = max(Ce(Exp,3))-L; end end end cover.neighbor = Nei; end % End of function function [Trunk,cover] = define_main_branches(cover,segment,aux,inputs) % If previous segmentation exists, then use it to make the sets in its main % branches (stem and first (second or even up to third) order branches) % connected. This ensures that similar branching structure as in the % existing segmentation is possible. Bal = cover.ball; Nei = cover.neighbor; Ce = aux.Ce; % Determine sets in the main branches of previous segmentation nb = size(Bal,1); MainBranches = zeros(nb,1); SegmentOfPoint = segment.SegmentOfPoint; % Determine which branch indexes define the main branches MainBranchIndexes = false(max(SegmentOfPoint),1); MainBranchIndexes(1) = true; MainBranchIndexes(segment.branch1indexes) = true; MainBranchIndexes(segment.branch2indexes) = true; MainBranchIndexes(segment.branch3indexes) = true; for i = 1:nb BranchInd = nonzeros(SegmentOfPoint(Bal{i})); if ~isempty(BranchInd) ind = min(BranchInd); if MainBranchIndexes(ind) MainBranches(i) = min(BranchInd); end end end % Define the trunk sets Trunk = aux.Fal; Trunk(MainBranches > 0) = true; % Update the neighbors to make the main branches connected [Par,CC] = cubical_partition(Ce,3*inputs.PatchDiam2Max,10); Sets = zeros(aux.nb,1,'uint32'); BI = max(MainBranches); N = size(Par); for i = 1:BI if MainBranchIndexes(i) Branch = MainBranches == i; % The sets forming branch "i" % the connected components of "Branch": Comps = connected_components(Nei,Branch,1,aux.Fal); n = size(Comps,1); % Connect the components to each other as long as there are more than % one component while n > 1 for j = 1:n comp = Comps{j}; NC = length(comp); % Determine branch sets closest to the component c = unique(CC(comp,:),'rows'); m = size(c,1); t = 0; NearSets = zeros(0,1); while isempty(NearSets) NearSets = aux.Fal; t = t+1; for k = 1:m x1 = max(1,c(k,1)-t); x2 = min(c(k,1)+t,N(1)); y1 = max(1,c(k,2)-t); y2 = min(c(k,2)+t,N(2)); z1 = max(1,c(k,3)-t); z2 = min(c(k,3)+t,N(3)); balls0 = Par(x1:x2,y1:y2,z1:z2); if t == 1 balls = vertcat(balls0{:}); else S = cellfun('length',balls0); I = S > 0; S = S(I); balls0 = balls0(I); stop = cumsum(S); start = [0; stop]+1; for l = 1:length(stop) Sets(start(l):stop(l)) = balls0{l}; end balls = Sets(1:stop(l)); end I = Branch(balls); balls = balls(I); NearSets(balls) = true; end NearSets(comp) = false; % Only the non-component cover sets NearSets = aux.Ind(NearSets); end % Determine the closest sets for "comp" if ~isempty(NearSets) d = pdist2(Ce(comp,:),Ce(NearSets,:)); if NC == 1 && length(NearSets) == 1 IU = 1; % the set in component to be connected JU = 1; % the set in "trunk" to be connected elseif NC == 1 [du,JU] = min(d); IU = 1; elseif length(NearSets) == 1 [du,IU] = min(d); JU = 1; else [d,IU] = min(d); [du,JU] = min(d); IU = IU(JU); end % Join to the closest component I = comp(IU); J = NearSets(JU); % make the connection Nei{I} = [Nei{I}; J]; Nei{J} = [Nei{J}; I]; end end Comps = connected_components(Nei,Branch,1,aux.Fal); n = size(Comps,1); end end end % Update the neigbors to connect 1st-order branches to the stem Stem = MainBranches == 1; Stem = aux.Ind(Stem); MainBranchIndexes = false(max(SegmentOfPoint),1); MainBranchIndexes(segment.branch1indexes) = true; BI = max(segment.branch1indexes); if isempty(BI) BI = 0; end for i = 2:BI if MainBranchIndexes(i) Branch = MainBranches == i; Branch = aux.Ind(Branch); if ~isempty(Branch) Neigbors = MainBranches(vertcat(Nei{Branch})) == 1; if ~any(Neigbors) d = pdist2(Ce(Branch,:),Ce(Stem,:)); if length(Branch) > 1 && length(Stem) > 1 [d,I] = min(d); [d,J] = min(d); I = I(J); elseif length(Branch) == 1 && length(Stem) > 1 [d,J] = min(d); I = 1; elseif length(Stem) == 1 && length(Branch) > 1 [d,I] = min(d); J = 1; elseif length(Branch) == 1 && length(Stem) == 1 I = 1; % the set in component to be connected J = 1; % the set in "trunk" to be connected end % Join the Branch to Stem I = Branch(I); J = Stem(J); Nei{I} = [Nei{I}; J]; Nei{J} = [Nei{J}; I]; end end end end cover.neighbor = Nei; % Check if the trunk is still in mutliple components and select the bottom % component to define "Trunk": [comps,cs] = connected_components(cover.neighbor,Trunk,aux.Fal); if length(cs) > 1 [cs,I] = sort(cs,'descend'); comps = comps(I); Stem = MainBranches == 1; Trunk = aux.Fal; i = 1; C = comps{i}; while i <= length(cs) && ~any(Stem(C)) i = i+1; C = comps{i}; end Trunk(C) = true; end end % End of function function [cover,Forb] = make_tree_connected(cover,aux,Forb,Base,Trunk,inputs) % Update neighbor-relation for whole tree such that the whole tree is one % connected component Nei = cover.neighbor; Ce = aux.Ce; % Expand trunk as much as possible Trunk(Forb) = false; Exp = Trunk; while any(Exp) Exp(vertcat(Nei{Exp})) = true; Exp(Trunk) = false; Exp(Forb) = false; Exp(Base) = false; Trunk(Exp) = true; end % Define "Other", sets not yet connected to trunk or Forb Other = ~aux.Fal; Other(Forb) = false; Other(Trunk) = false; Other(Base) = false; % Determine parameters on the extent of the "Nearby Space" and acceptable % component size % cell size for "Nearby Space" = k0 times PatchDiam: k0 = min(10,ceil(0.2/inputs.PatchDiam1)); % current cell size, increases by k0 every time when new connections cannot % be made: k = k0; if inputs.OnlyTree Cmin = 0; else Cmin = ceil(0.1/inputs.PatchDiam1); % minimum accepted component size, % smaller ones are added to Forb, the size triples every round end % Determine the components of "Other" if any(Other) Comps = connected_components(Nei,Other,1,aux.Fal); nc = size(Comps,1); NonClassified = true(nc,1); %plot_segs(P,Comps,6,1,cover.ball) %pause else NonClassified = false; end bottom = min(Ce(Base,3)); % repeat search and connecting as long as "Other" sets exists while any(NonClassified) npre = nnz(NonClassified); % number of "Other" sets before new connections again = true; % check connections again with same "distance" if true % Partition the centers of the cover sets into cubes with size k*dmin [Par,CC] = cubical_partition(Ce,k*inputs.PatchDiam1); Neighbors = cell(nc,1); Sizes = zeros(nc,2); Pass = true(nc,1); first_round = true; while again % Check each component: part of "Tree" or "Forb" for i = 1:nc if NonClassified(i) && Pass(i) comp = Comps{i}; % candidate component for joining to the tree % If the component is neighbor of forbidden sets, remove it J = Forb(vertcat(Nei{comp})); if any(J) NonClassified(i) = false; Forb(comp) = true; Other(comp) = false; else % Other wise check nearest sets for a connection NC = length(comp); if first_round % Select the cover sets the nearest to the component c = unique(CC(comp,:),'rows'); m = size(c,1); B = cell(m,1); for j = 1:m balls = Par(c(j,1)-1:c(j,1)+1,... c(j,2)-1:c(j,2)+1,c(j,3)-1:c(j,3)+1); B{j} = vertcat(balls{:}); end NearSets = vertcat(B{:}); % Only the non-component cover sets aux.Fal(comp) = true; I = aux.Fal(NearSets); NearSets = NearSets(~I); aux.Fal(comp) = false; NearSets = unique(NearSets); Neighbors{i} = NearSets; if isempty(NearSets) Pass(i) = false; end % No "Other" sets I = Other(NearSets); NearSets = NearSets(~I); else NearSets = Neighbors{i}; % No "Other" sets I = Other(NearSets); NearSets = NearSets(~I); end % Select different class from NearSets I = Trunk(NearSets); J = Forb(NearSets); trunk = NearSets(I); % "Trunk" sets forb = NearSets(J); % "Forb" sets if length(trunk) ~= Sizes(i,1) || length(forb) ~= Sizes(i,2) Sizes(i,:) = [length(trunk) length(forb)]; % If large component is tall and close to ground, then % search the connection near the component's bottom if NC > 100 hmin = min(Ce(comp,3)); H = max(Ce(comp,3))-hmin; if H > 5 && hmin < bottom+5 I = Ce(NearSets,3) < hmin+0.5; NearSets = NearSets(I); I = Trunk(NearSets); J = Forb(NearSets); trunk = NearSets(I); % "Trunk" sets forb = NearSets(J); % "Forb" sets end end % Determine the closest sets for "trunk" if ~isempty(trunk) d = pdist2(Ce(comp,:),Ce(trunk,:)); if NC == 1 && length(trunk) == 1 dt = d; % the minimum distance IC = 1; % the set in component to be connected IT = 1; % the set in "trunk" to be connected elseif NC == 1 [dt,IT] = min(d); IC = 1; elseif length(trunk) == 1 [dt,IC] = min(d); IT = 1; else [d,IC] = min(d); [dt,IT] = min(d); IC = IC(IT); end else dt = 700; end % Determine the closest sets for "forb" if ~isempty(forb) d = pdist2(Ce(comp,:),Ce(forb,:)); df = min(d); if length(df) > 1 df = min(df); end else df = 1000; end % Determine what to do with the component if (dt > 12 && dt < 100) || (NC < Cmin && dt > 0.5 && dt < 10) % Remove small isolated component Forb(comp) = true; Other(comp) = false; NonClassified(i) = false; elseif 3*df < dt || (df < dt && df > 0.25) % Join the component to "Forb" Forb(comp) = true; Other(comp) = false; NonClassified(i) = false; elseif (df == 1000 && dt == 700) || dt > k*inputs.PatchDiam1 % Isolated component, do nothing else % Join to "Trunk" I = comp(IC); J = trunk(IT); Other(comp) = false; Trunk(comp) = true; NonClassified(i) = false; % make the connection Nei{I} = [Nei{I}; J]; Nei{J} = [Nei{J}; I]; end end end end end first_round = false; % If "Other" has decreased, do another check with same "distance" if nnz(NonClassified) < npre again = true; npre = nnz(NonClassified); else again = false; end end k = k+k0; % increase the cell size of the nearby search space Cmin = 3*Cmin; % increase the acceptable component size end Forb(Base) = false; cover.neighbor = Nei; end % End of function
github
InverseTampere/TreeQSM-master
segments.m
.m
TreeQSM-master/src/main_steps/segments.m
13,369
utf_8
775d0a7de8b20ebd931b2cf4c554cabf
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function segment = segments(cover,Base,Forb) % --------------------------------------------------------------------- % SEGMENTS.M Segments the covered point cloud into branches. % % Version 2.10 % Latest update 16 Aug 2017 % % Copyright (C) 2013-2017 Pasi Raumonen % --------------------------------------------------------------------- % Segments the tree into branches and records their parent-child-relations. % Bifurcations are recognized by studying connectivity of a "study" % region moving along the tree. In case of multiple connected components % in "study", the components are classified as the continuation and branches. % % Inputs: % cover Cover sets % Base Base of the tree % Forb Cover sets not part of the tree % % Outputs: % segment Structure array containing the followin fields: % segments Segments found, (n_seg x 1)-cell, each cell contains a cell array the cover sets % ParentSegment Parent segment of each segment, (n_seg x 1)-vector, % equals to zero if no parent segment % ChildSegment Children segments of each segment, (n_seg x 1)-cell Nei = cover.neighbor; nb = size(Nei,1); % The number of cover sets a = max([200000 nb/100]); % Estimate for maximum number of segments SBas = cell(a,1); % The segment bases found Segs = cell(a,1); % The segments found SPar = zeros(a,2,'uint32'); % The parent segment of each segment SChi = cell(a,1); % The children segments of each segment % Initialize SChi SChi{1} = zeros(5000,1,'uint32'); C = zeros(200,1); for i = 2:a SChi{i} = C; end NChi = zeros(a,1); % Number of child segments found for each segment Fal = false(nb,1); % Logical false-vector for cover sets s = 1; % The index of the segment under expansion b = s; % The index of the latest found base SBas{s} = Base; Seg = cell(1000,1); % The cover set layers in the current segment Seg{1} = Base; ForbAll = Fal; % The forbidden sets ForbAll(Forb) = true; ForbAll(Base) = true; Forb = ForbAll; % The forbidden sets for the segment under expansion Continue = true; % True as long as the component can be segmented further NewSeg = true; % True if the first Cut for the current segment nl = 1; % The number of cover set layers currently in the segment % Segmenting stops when there are no more segments to be found while Continue && (b < nb) % Update the forbidden sets Forb(Seg{nl}) = true; % Define the study Cut = define_cut(Nei,Seg{nl},Forb,Fal); CutSize = length(Cut); if NewSeg NewSeg = false; ns = min(CutSize,6); end % Define the components of cut and study regions if CutSize > 0 CutComps = cut_components(Nei,Cut,CutSize,Fal,Fal); nc = size(CutComps,1); if nc > 1 [StudyComps,Bases,CompSize,Cont,BaseSize] = ... study_components(Nei,ns,Cut,CutComps,Forb,Fal,Fal); nc = length(Cont); end else nc = 0; end % Classify study region components if nc == 1 % One component, continue expansion of the current segment nl = nl+1; if size(Cut,2) > 1 Seg{nl} = Cut'; else Seg{nl} = Cut; end elseif nc > 1 % Classify the components of the Study region Class = component_classification(CompSize,Cont,BaseSize,CutSize); for i = 1:nc if Class(i) == 1 Base = Bases{i}; ForbAll(Base) = true; Forb(StudyComps{i}) = true; J = Forb(Cut); Cut = Cut(~J); b = b+1; SBas{b} = Base; SPar(b,:) = [s nl]; NChi(s) = NChi(s)+1; SChi{s}(NChi(s)) = b; end end % Define the new cut. % If the cut is empty, determine the new base if isempty(Cut) Segs{s} = Seg(1:nl); S = vertcat(Seg{1:nl}); ForbAll(S) = true; if s < b s = s+1; Seg{1} = SBas{s}; Forb = ForbAll; NewSeg = true; nl = 1; else Continue = false; end else if size(Cut,2) > 1 Cut = Cut'; end nl = nl+1; Seg{nl} = Cut; end else % If the study region has zero size, then the current segment is % complete and determine the base of the next segment Segs{s} = Seg(1:nl); S = vertcat(Seg{1:nl}); ForbAll(S) = true; if s < b s = s+1; Seg{1} = SBas{s}; Forb = ForbAll; NewSeg = true; nl = 1; else Continue = false; end end end Segs = Segs(1:b); SPar = SPar(1:b,:); schi = SChi(1:b); % Define output SChi = cell(b,1); for i = 1:b if NChi(i) > 0 SChi{i} = uint32(schi{i}(1:NChi(i))); else SChi{i} = zeros(0,1,'uint32'); end S = Segs{i}; for j = 1:size(S,1) S{j} = uint32(S{j}); end Segs{i} = S; end clear Segment segment.segments = Segs; segment.ParentSegment = SPar; segment.ChildSegment = SChi; end % End of the main function % Define subfunctions function Cut = define_cut(Nei,CutPre,Forb,Fal) % Defines the "Cut" region Cut = vertcat(Nei{CutPre}); Cut = unique_elements(Cut,Fal); I = Forb(Cut); Cut = Cut(~I); end % End of function function [Components,CompSize] = cut_components(Nei,Cut,CutSize,Fal,False) % Define the connected components of the Cut if CutSize == 1 % Cut is connected and therefore Study is also CompSize = 1; Components = cell(1,1); Components{1} = Cut; elseif CutSize == 2 I = Nei{Cut(1)} == Cut(2); if any(I) Components = cell(1,1); Components{1} = Cut; CompSize = 1; else Components = cell(2,1); Components{1} = Cut(1); Components{2} = Cut(2); CompSize = [1 1]; end elseif CutSize == 3 I = Nei{Cut(1)} == Cut(2); J = Nei{Cut(1)} == Cut(3); K = Nei{Cut(2)} == Cut(3); if any(I)+any(J)+any(K) >= 2 CompSize = 1; Components = cell(1,1); Components{1} = Cut; elseif any(I) Components = cell(2,1); Components{1} = Cut(1:2); Components{2} = Cut(3); CompSize = [2 1]; elseif any(J) Components = cell(2,1); Components{1} = Cut([1 3]'); Components{2} = Cut(2); CompSize = [2 1]; elseif any(K) Components = cell(2,1); Components{1} = Cut(2:3); Components{2} = Cut(1); CompSize = [2 1]; else CompSize = [1 1 1]; Components = cell(3,1); Components{1} = Cut(1); Components{2} = Cut(2); Components{3} = Cut(3); end else Components = cell(CutSize,1); CompSize = zeros(CutSize,1); Comp = zeros(CutSize,1); Fal(Cut) = true; nc = 0; % number of components found m = Cut(1); i = 0; while i < CutSize Added = Nei{m}; I = Fal(Added); Added = Added(I); a = length(Added); Comp(1) = m; Fal(m) = false; t = 1; while a > 0 Comp(t+1:t+a) = Added; Fal(Added) = false; t = t+a; Ext = vertcat(Nei{Added}); Ext = unique_elements(Ext,False); I = Fal(Ext); Added = Ext(I); a = length(Added); end i = i+t; nc = nc+1; Components{nc} = Comp(1:t); CompSize(nc) = t; if i < CutSize J = Fal(Cut); m = Cut(J); m = m(1); end end Components = Components(1:nc); CompSize = CompSize(1:nc); end end % End of function function [Components,Bases,CompSize,Cont,BaseSize] = ... study_components(Nei,ns,Cut,CutComps,Forb,Fal,False) % Define Study as a cell-array Study = cell(ns,1); StudySize = zeros(ns,1); Study{1} = Cut; StudySize(1) = length(Cut); if ns >= 2 N = Cut; i = 1; while i < ns Forb(N) = true; N = vertcat(Nei{N}); N = unique_elements(N,Fal); I = Forb(N); N = N(~I); if ~isempty(N) i = i+1; Study{i} = N; StudySize(i) = length(N); else Study = Study(1:i); StudySize = StudySize(1:i); i = ns+1; end end end % Define study as a vector ns = length(StudySize); studysize = sum(StudySize); study = vertcat(Study{:}); % Determine the components of study nc = size(CutComps,1); i = 1; % index of cut component j = 0; % number of elements attributed to components k = 0; % number of study components Fal(study) = true; Components = cell(nc,1); CompSize = zeros(nc,1); Comp = zeros(studysize,1); while i <= nc C = CutComps{i}; while j < studysize a = length(C); Comp(1:a) = C; Fal(C) = false; if a > 1 Add = unique_elements(vertcat(Nei{C}),False); else Add = Nei{C}; end t = a; I = Fal(Add); Add = Add(I); a = length(Add); while a > 0 Comp(t+1:t+a) = Add; Fal(Add) = false; t = t+a; Add = vertcat(Nei{Add}); Add = unique_elements(Add,False); I = Fal(Add); Add = Add(I); a = length(Add); end j = j+t; k = k+1; Components{k} = Comp(1:t); CompSize(k) = t; if j < studysize C = zeros(0,1); while i < nc && isempty(C) i = i+1; C = CutComps{i}; J = Fal(C); C = C(J); end if i == nc && isempty(C) j = studysize; i = nc+1; end else i = nc+1; end end Components = Components(1:k); CompSize = CompSize(1:k); end % Determine BaseSize and Cont Cont = true(k,1); BaseSize = zeros(k,1); Bases = cell(k,1); if k > 1 Forb(study) = true; Fal(study) = false; Fal(Study{1}) = true; for i = 1:k % Determine the size of the base of the components Set = unique_elements([Components{i}; Study{1}],False); False(Components{i}) = true; I = False(Set)&Fal(Set); False(Components{i}) = false; Set = Set(I); Bases{i} = Set; BaseSize(i) = length(Set); end Fal(Study{1}) = false; Fal(Study{ns}) = true; Forb(study) = true; for i = 1:k % Determine if the component can be extended Set = unique_elements([Components{i}; Study{ns}],False); False(Components{i}) = true; I = False(Set)&Fal(Set); False(Components{i}) = false; Set = Set(I); if ~isempty(Set) N = vertcat(Nei{Set}); N = unique_elements(N,False); I = Forb(N); N = N(~I); if isempty(N) Cont(i) = false; end else Cont(i) = false; end end end end % End of function function Class = component_classification(CompSize,Cont,BaseSize,CutSize) % Classifies study region components: % Class(i) == 0 continuation % Class(i) == 1 branch nc = size(CompSize,1); StudySize = sum(CompSize); Class = ones(nc,1); % true if a component is a branch to be further segmented ContiComp = 0; % Simple initial classification for i = 1:nc if BaseSize(i) == CompSize(i) && ~Cont(i) % component has no expansion, not a branch Class(i) = 0; elseif BaseSize(i) == 1 && CompSize(i) <= 2 && ~Cont(i) % component has very small expansion, not a branch Class(i) = 0; elseif BaseSize(i)/CutSize < 0.05 && 2*BaseSize(i) >= CompSize(i) && ~Cont(i) % component has very small expansion or is very small, not a branch Class(i) = 0; elseif CompSize(i) <= 3 && ~Cont(i) % very small component, not a branch Class(i) = 0; elseif BaseSize(i)/CutSize >= 0.7 || CompSize(i) >= 0.7*StudySize % continuation of the segment Class(i) = 0; ContiComp = i; else % Component is probably a branch end end Branches = Class == 1; if ContiComp == 0 && any(Branches) Ind = (1:1:nc)'; Branches = Ind(Branches); [~,I] = max(CompSize(Branches)); Class(Branches(I)) = 0; end end % End of function
github
InverseTampere/TreeQSM-master
filtering.m
.m
TreeQSM-master/src/main_steps/filtering.m
8,700
utf_8
67b53b588752ce6985691d1aff849e99
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function Pass = filtering(P,inputs) % --------------------------------------------------------------------- % FILTERING.M Filters noise from point clouds. % % Version 3.0.0 % Latest update 3 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Filters the point cloud as follows: % % 1) the possible NaNs are removed. % % 2) (optional, done if filter.k > 0) Statistical kth-nearest neighbor % distance outlier filtering based on user defined "k" (filter.k) and % multiplier for standard deviation (filter.nsigma): Determines the % kth-nearest neighbor distance for all points and then removes the points % whose distances are over average_distance + nsigma*std. Computes the % statistics for each meter layer in vertical direction so that the % average distances and SDs can change as the point density decreases. % % 3) (optional, done if filter.radius > 0) Statistical point density % filtering based on user defined ball radius (filter.radius) and multiplier % for standard deviation (filter.nsigma): Balls of radius "filter.radius" % centered at each point are defined for all points and the number of % points included ("point density") are computed and then removes the points % whose density is smaller than average_density - nsigma*std. Computes the % statistics for each meter layer in vertical direction so that the % average densities and SDs can change as the point density decreases. % % 4) (optional, done if filter.ncomp > 0) Small component filtering based % on user defined cover (filter.PatchDiam1, filter.BallRad1) and threshold % (filter.ncomp): Covers the point cloud and determines the connected % components of the cover and removes the points from the small components % that have less than filter.ncomp cover sets. % % 5) (optional, done if filter.EdgeLength > 0) cubical downsampling of the % point cloud based on user defined cube size (filter.EdgeLength): % selects randomly one point from each cube % % Does the filtering in the above order and thus always applies the next % fitering to the point cloud already filtered by the previous methods. % Statistical kth-nearest neighbor distance outlier filtering and the % statistical point density filtering are meant to be exlusive to each % other. % % Inputs: % P Point cloud % inputs Inputs structure with the following subfields: % filter.EdgeLength Edge length of the cubes in the cubical downsampling % filter.k k of knn method % filter.radius Radius of the balls in the density filtering % filter.nsigma Multiplier for standard deviation, determines how % far from the mean the threshold is in terms of SD. % Used in both the knn and the density filtering % filter.ncomp Threshold number of components in the small % component filtering % filter.PatchDiam1 Defines the patch/cover set size for the component % filtering % filter.BallRad1 Defines the neighbors for the component filtering % filter.plot If true, plots the filtered point cloud % Outputs: % Pass Logical vector indicating points passing the filtering % --------------------------------------------------------------------- % Changes from version 2.0.0 to 3.0.0, 3 May 2022: % Major changes and additions. % 1) Added two new filtering options: statistical kth-nearest neighbor % distance outlier filtering and cubical downsampling. % 2) Changed the old point density filtering, which was based on given % threshold, into statistical point density filtering, where the % threshold is based on user defined statistical measure % 3) All the input parameters are given by "inputs"-structure that can be % defined by "create_input" script % 4) Streamlined the coding and what is displayed %% Initial data processing % Only double precision data if ~isa(P,'double') P = double(P); end % Only x,y,z-data if size(P,2) > 3 P = P(:,1:3); end np = size(P,1); np0 = np; ind = (1:1:np)'; Pass = false(np,1); disp('----------------------') disp(' Filtering...') disp([' Points before filtering: ',num2str(np)]) %% Remove possible NaNs F = ~any(isnan(P),2); if nnz(F) < np disp([' Points with NaN removed: ',num2str(np-nnz(Pass))]) ind = ind(F); end %% Statistical kth-nearest neighbor distance outlier filtering if inputs.filter.k > 0 % Compute the knn distances Q = P(ind,:); np = size(Q,1); [~, kNNdist] = knnsearch(Q,Q,'dist','euclidean','k',inputs.filter.k); kNNdist = kNNdist(:,end); % Change the threshold kNNdistance according the average and standard % deviation for every vertical layer of 1 meter in height hmin = min(Q(:,3)); hmax = max(Q(:,3)); H = ceil(hmax-hmin); F = false(np,1); ind = (1:1:np)'; for i = 1:H I = Q(:,3) < hmin+i & Q(:,3) >= hmin+i-1; points = ind(I); d = kNNdist(points); J = d < mean(d)+inputs.filter.nsigma*std(d); points = points(J); F(points) = 1; end ind = ind(F); disp([' Points removed as statistical outliers: ',num2str(np-length(ind))]) end %% Statistical point density filtering if inputs.filter.radius > 0 Q = P(ind,:); np = size(Q,1); % Partition the point cloud into cubes [partition,CC] = cubical_partition(Q,inputs.filter.radius); % Determine the number of points inside a ball for each point NumOfPoints = zeros(np,1); r1 = inputs.filter.radius^2; for i = 1:np if NumOfPoints(i) == 0 points = partition(CC(i,1)-1:CC(i,1)+1,CC(i,2)-1:CC(i,2)+1,CC(i,3)-1:CC(i,3)+1); points = vertcat(points{:,:}); cube = Q(points,:); p = partition{CC(i,1),CC(i,2),CC(i,3)}; for j = 1:length(p) dist = (Q(p(j),1)-cube(:,1)).^2+(Q(p(j),2)-cube(:,2)).^2+(Q(p(j),3)-cube(:,3)).^2; J = dist < r1; NumOfPoints(p(j)) = nnz(J); end end end % Change the threshold point density according the average and standard % deviation for every vertical layer of 1 meter in height hmin = min(Q(:,3)); hmax = max(Q(:,3)); H = ceil(hmax-hmin); F = false(np,1); ind = (1:1:np)'; for i = 1:H I = Q(:,3) < hmin+i & Q(:,3) >= hmin+i-1; points = ind(I); N = NumOfPoints(points); J = N > mean(N)-inputs.filter.nsigma*std(N); points = points(J); F(points) = 1; end ind = ind(F); disp([' Points removed as statistical outliers: ',num2str(np-length(ind))]) end %% Small component filtering if inputs.filter.ncomp > 0 % Cover the point cloud with patches input.BallRad1 = inputs.filter.BallRad1; input.PatchDiam1 = inputs.filter.PatchDiam1; input.nmin1 = 0; Q = P(ind,:); np = size(Q,1); cover = cover_sets(Q,input); % Determine the separate components Components = connected_components(cover.neighbor,0,inputs.filter.ncomp); % The filtering B = vertcat(Components{:}); % patches in the components points = vertcat(cover.ball{B}); % points in the components F = false(np,1); F(points) = true; ind = ind(F); disp([' Points with small components removed: ',num2str(np-length(ind))]) end %% Cubical downsampling if inputs.filter.EdgeLength > 0 Q = P(ind,:); np = size(Q,1); F = cubical_downsampling(Q,inputs.filter.EdgeLength); ind = ind(F); disp([' Points removed with downsampling: ',num2str(np-length(ind))]) end %% Define the output and display summary results Pass(ind) = true; np = nnz(Pass); disp([' Points removed in total: ',num2str(np0-np)]) disp([' Points removed in total (%): ',num2str(round((1-np/np0)*1000)/10)]) disp([' Points left: ',num2str(np)]) %% Plot the filtered and unfiltered point clouds if inputs.filter.plot plot_comparison(P(Pass,:),P(~Pass,:),1,1,1) plot_point_cloud(P(Pass,:),2,1) end
github
InverseTampere/TreeQSM-master
relative_size.m
.m
TreeQSM-master/src/main_steps/relative_size.m
3,969
utf_8
ca5b31c61626f8eab338648a462c355b
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function RS = relative_size(P,cover,segment) % --------------------------------------------------------------------- % RELATIVE_SIZE.M Determines relative cover set size for points in new covers % % Version 2.00 % Latest update 16 Aug 2017 % % Copyright (C) 2014-2017 Pasi Raumonen % --------------------------------------------------------------------- % % Uses existing segmentation and its branching structure to determine % relative size of the cover sets distributed over new covers. The idea is % to decrease the relative size as the branch size decreases. This is % realised so that the relative size at the base of a branch is % proportional to the size of the stem's base, measured as number of % cover sets in the first few layers. Also when we approach the % tip of the branch, the relative size decreases to the minimum. % Maximum relative size is 256 at the bottom of the % stem and the minimum is 1 at the tip of every branch. % % Output: % RS Relative size (1-256), uint8-vector, (n_points x 1) Bal = cover.ball; Cen = cover.center; Nei = cover.neighbor; Segs = segment.segments; SChi = segment.ChildSegment; np = size(P,1); % number of points ns = size(Segs,1); % number of segments %% Use branching order and height as apriori info % Determine the branch orders of the segments Ord = zeros(ns,1); C = SChi{1}; order = 0; while ~isempty(C) order = order+order; Ord(C) = order; C = vertcat(SChi{C}); end maxO = order+1; % maximum branching order (plus one) % Determine tree height Top = max(P(Cen,3)); Bot = min(P(Cen,3)); H = Top-Bot; %% Determine "base size" compared to the stem base % BaseSize is the relative size of the branch base compared to the stem % base, measured as number of cover sets in the first layers of the cover % sets. If it is larger than apriori upper limit based on branching order % and branch height, then correct to the apriori limit BaseSize = zeros(ns,1); % Determine first the base size at the stem S = Segs{1}; n = size(S,1); if n >= 2 m = min([6 n]); BaseSize(1) = mean(cellfun(@length,S(2:m))); else BaseSize(1) = length(S{1}); end % Then define base size for other segments for i = 2:ns S = Segs{i}; n = size(S,1); if n >= 2 m = min([6 n]); BaseSize(i) = ceil(mean(cellfun(@length,S(2:m)))/BaseSize(1)*256); else BaseSize(i) = length(S{1})/BaseSize(1)*256; end bot = min(P(Cen(S{1}),3)); h = bot-Bot; % height of the segment's base BS = ceil(256*(maxO-Ord(i))/maxO*(H-h)/H); % maximum apriori base size if BaseSize(i) > BS BaseSize(i) = BS; end end BaseSize(1) = 256; %% Determine relative size for points TS = 1; RS = zeros(np,1,'uint8'); for i = 1:ns S = Segs{i}; s = size(S,1); for j = 1:s Q = S{j}; RS(vertcat(Bal{Q})) = BaseSize(i)-(BaseSize(i)-TS)*sqrt((j-1)/s); end end %% Adjust the relative size at the base of child segments RS0 = RS; for i = 1:ns C = SChi{i}; n = length(C); if n > 0 for j = 1:n S = Segs{C(j)}; B = S{1}; N = vertcat(Nei{B}); if size(S,1) > 1 N = setdiff(N,S{2}); end N = union(N,B); N = vertcat(Bal{N}); RS(N) = RS0(N)/2; end end end
github
InverseTampere/TreeQSM-master
func_grad_cylinder.m
.m
TreeQSM-master/src/least_squares_fitting/func_grad_cylinder.m
3,370
utf_8
20d0b6e220003ae8a669e991c4c73090
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [dist,J] = func_grad_cylinder(par,P,weight) % --------------------------------------------------------------------- % FUNC_GRAD_CYLINDER.M Function and gradient calculation for % least-squares cylinder fit. % % Version 2.2.0 % Latest update 5 Oct 2021 % % Copyright (C) 2013-2021 Pasi Raumonen % --------------------------------------------------------------------- % % Input % par Cylinder parameters [x0 y0 alpha beta r]' % P Point cloud % weight (Optional) Weights for the points % % Output % dist Signed distances of points to the cylinder surface: % dist(i) = sqrt(xh(i)^2 + yh(i)^2) - r, where % [xh yh zh]' = Ry(beta) * Rx(alpha) * ([x y z]' - [x0 y0 0]') % J Jacobian matrix d dist(i)/d par(j). % Five cylinder parameters: % Location = axis point intersects xy-plane: x0 and y0 (z0 == 0) % Rotation angles around x and y axis = alpha and beta % Radius = r % % Transformed points: % Pt = [xh yx zh] = Ry(beta) * Rx(alpha) * (P - [x0 y0 0]) % % "Plane points": % Qt = Pt * I2 = [xh yh]; % % Distance: % D(x0,y0,alpha,beta,r) = sqrt( dot(Qt,Qt) )-r = sqrt( Qt*Qt' )-r % % Least squares = minimize Sum( D^2 ) over x0, y0, alpha, beta and r % % rt = sqrt( dot(Qt,Qt) ) % N = Qt/rt % % Jacobian for D with respect to x0, y0, alpha, beta: % dD/di = dot( N,dQt/di ) = dot( Qt/rt,dQt/di ) % % R = Ry*Rx % dQt/dx0 = R*[-1 0 0]' % dQt/dy0 = R*[0 -1 0]' % dQt/dalpha = (P-[x0 y0 0])*DRx'; % dQt/dalpha = (P-[x0 y0 0])*DRy'; % Changes from version 2.1.0 to 2.2.0, 5 Oct 20201: % 1) Minor changes in syntax % Changes from version 2.0.0 to 2.1.0, 14 July 2020: % 1) Added optional input for weights of the points x0 = par(1); y0 = par(2); alpha = par(3); beta = par(4); r = par(5); % Determine the rotation matrices and their derivatives [R,DR1,DR2] = form_rotation_matrices([alpha beta]); % Calculate the distances Pt = (P-[x0 y0 0])*R'; xt = Pt(:,1); yt = Pt(:,2); rt = sqrt(xt.*xt + yt.*yt); dist = rt-r; % Distances to the cylinder surface if nargin == 3 dist = weight.*dist; % Weighted distances end % form the Jacobian matrix if nargout > 1 N = [xt./rt yt./rt]; m = size(P,1); J = zeros(m,5); A1 = (R*[-1 0 0]')'; A = eye(2); A(1,1) = A1(1); A(2,2) = A1(2); J(:,1) = sum(N(:,1:2)*A,2); A2 = (R*[0 -1 0]')'; A(1,1) = A2(1); A(2,2) = A2(2); J(:,2) = sum(N(:,1:2)*A,2); A3 = (P-[x0 y0 0])*DR1'; J(:,3) = sum(N(:,1:2).*A3(:,1:2),2); A4 = (P-[x0 y0 0])*DR2'; J(:,4) = sum(N(:,1:2).*A4(:,1:2),2); J(:,5) = -1*ones(m,1); if nargin == 3 % Weighted Jacobian J = [weight.*J(:,1) weight.*J(:,2) weight.*J(:,3) ... weight.*J(:,4) weight.*J(:,5)]; end end
github
InverseTampere/TreeQSM-master
func_grad_axis.m
.m
TreeQSM-master/src/least_squares_fitting/func_grad_axis.m
3,013
utf_8
7a75b492055072602912f3a4b149510d
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [dist,J] = func_grad_axis(P,par,weight) % --------------------------------------------------------------------- % FUNC_GRAD_CYLINDER.M Function and gradient calculation for % least-squares cylinder fit. % % Version 2.1.0 % Latest update 14 July 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % % Input % par Cylinder parameters [x0 y0 alpha beta r]' % P Point cloud % weight (Optional) Weights for the points % % Output % dist Signed distances of points to the cylinder surface: % dist(i) = sqrt(xh(i)^2 + yh(i)^2) - r, where % [xh yh zh]' = Ry(beta) * Rx(alpha) * ([x y z]' - [x0 y0 0]') % J Jacobian matrix d dist(i)/d par(j). % Changes from version 2.0.0 to 2.1.0, 14 July 2020: % 1) Added optional input for weights of the points % Five cylinder parameters: % Location = axis point intersects xy-plane: x0 and y0 (z0 == 0) % Rotation angles around x and y axis = alpha and beta % Radius = r % % Transformed points: % Pt = [xh yx zh] = Ry(beta) * Rx(alpha) * (P - [x0 y0 0]) % % "Plane points": % Qt = Pt * I2 = [xh yh]; % % Distance: % D(x0,y0,alpha,beta,r) = sqrt( dot(Qt,Qt) )-r = sqrt( Qt*Qt' )-r % % Least squares = minimize Sum( D^2 ) over x0, y0, alpha, beta and r % % rt = sqrt( dot(Qt,Qt) ) % N = Qt/rt % % Jacobian for D with respect to x0, y0, alpha, beta: % dD/di = dot( N,dQt/di ) = dot( Qt/rt,dQt/di ) % % R = Ry*Rx % dQt/dx0 = R*[-1 0 0]' % dQt/dy0 = R*[0 -1 0]' % dQt/dalpha = (P-[x0 y0 0])*DRx'; % dQt/dalpha = (P-[x0 y0 0])*DRy'; x0 = par(1); y0 = par(2); alpha = par(3); beta = par(4); r = par(5); % Determine the rotation matrices and their derivatives [R,DR1,DR2] = form_rotation_matrices([alpha beta]); % Calculate the distances Pt = (P-[x0 y0 0])*R'; xt = Pt(:,1); yt = Pt(:,2); rt = sqrt(xt.*xt + yt.*yt); dist = rt-r; % Distances to the cylinder surface if nargin == 3 dist = weight.*dist; % Weighted distances end % form the Jacobian matrix if nargout > 1 N = [xt./rt yt./rt]; m = size(P,1); J = zeros(m,2); A3 = (P-[x0 y0 0])*DR1'; J(:,1) = sum(N(:,1:2).*A3(:,1:2),2); A4 = (P-[x0 y0 0])*DR2'; J(:,2) = sum(N(:,1:2).*A4(:,1:2),2); if nargin == 3 % Weighted Jacobian J = [weight.*J(:,1) weight.*J(:,2)]; end end
github
InverseTampere/TreeQSM-master
nlssolver.m
.m
TreeQSM-master/src/least_squares_fitting/nlssolver.m
2,534
utf_8
d76f851140186c08867124872cbcc554
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [par,d,conv,rel] = nlssolver(par,P,weight) % --------------------------------------------------------------------- % NLSSOLVER.M Nonlinear least squares solver for cylinders. % % Version 2.1.0 % Latest update 14 July 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % % Input % par Intial estimates of the parameters % P Point cloud % % Output % par Optimised parameter values % d Distances of points to cylinder % conv True if fitting converged % rel True if condition number was not very bad, fit was reliable % Changes from version 2.0.0 to 2.1.0, 14 July 2020: % 1) Added optional input for weights of the points maxiter = 50; iter = 0; conv = false; rel = true; if nargin == 2 NoWeights = true; else NoWeights = false; end %% Gauss-Newton iterations while iter < maxiter && ~conv && rel %% Calculate the distances and Jacobian if NoWeights [d0, J] = func_grad_cylinder(par,P); else [d0, J] = func_grad_cylinder(par,P,weight); end %% Calculate update step SS0 = norm(d0); % Squared sum of the distances % solve for the system of equations: % par(i+1) = par(i) - (J'J)^(-1)*J'd0(par(i)) A = J'*J; b = J'*d0; warning off p = -A\b; % solve for the system of equations warning on par = par+p; % update the parameters %% Check reliability if rcond(-R) < 10000*eps rel = false; end %% Check convergence: % The distances with the new parameter values: if NoWeights d = func_grad_cylinder(par,P); else d = func_grad_cylinder(par,P,weight); end SS1 = norm(d); % Squared sum of the distances if abs(SS0-SS1) < 1e-4 conv = true; end iter = iter + 1; end
github
InverseTampere/TreeQSM-master
least_squares_axis.m
.m
TreeQSM-master/src/least_squares_fitting/least_squares_axis.m
3,918
utf_8
f47fffa17b2cc0925b40301fcc7076dd
function cyl = least_squares_axis(P,Axis,Point0,Rad0,weight) % --------------------------------------------------------------------- % LEAST_SQUARES_AXIS.M Least-squares cylinder axis fitting using % Gauss-Newton when radius and point are given % % Version 1.0 % Latest update 1 Oct 2021 % % Copyright (C) 2017-2021 Pasi Raumonen % --------------------------------------------------------------------- % Input % P 3d point cloud % Axis0 Initial axis estimate (1 x 3) % Point0 Initial estimate of axis point (1 x 3) % Rad0 Initial estimate of the cylinder radius % weight (Optional) Weights for each point % % Output % cyl Structure array with the following fields % axis Cylinder axis (optimized here) % radius Radius of the cylinder (from the input) % start Axis point (from the input) % mad Mean absolute distance of the points to the cylinder surface % SurfCov Surface coverage, how much of the cylinder surface is covered % with points % conv If conv = 1, the algorithm has converged % rel If rel = 1, the algorithm has reliable answer in terms of % matrix inversion with a good enough condition number % --------------------------------------------------------------------- %% Initial estimates and other settings res = 0.03; % "Resolution level" for computing surface coverage par = [0 0]'; maxiter = 50; % maximum number of Gauss-Newton iteration iter = 0; % number of iterations so far conv = false; % converge of Gauss-Newton algorithm rel = true; % are the results reliable, system matrix not badly conditioned if nargin == 4 weight = ones(size(P,1),1); end Rot0 = rotate_to_z_axis(Axis); Pt = (P-Point0)*Rot0'; Par = [0 0 0 0 Rad0]'; %% Gauss-Newton iterations while iter < maxiter && ~conv && rel % Calculate the distances and Jacobian [dist,J] = func_grad_axis(Pt,Par); % Calculate update step and gradient. SS0 = norm(dist); % Squared sum of the distances % solve for the system of equations: % par(i+1) = par(i) - (J'J)^(-1)*J'd(par(i)) A = J'*J; b = J'*dist; warning off p = -A\b; % solve for the system of equations warning on % Update par = par+p; % Check if the updated parameters lower the squared sum value Par = [0; 0; par; Rad0]; dist = func_grad_axis(Pt,Par); SS1 = norm(dist); if SS1 > SS0 % Update did not decreased the squared sum, use update with much % shorter update step par = par-0.95*p; Par = [0; 0; par; Rad0]; dist = func_grad_axis(Pt,Par); SS1 = norm(dist); end % Check reliability rel = true; if rcond(A) < 10000*eps rel = false; end % Check convergence if abs(SS0-SS1) < 1e-5 conv = true; end iter = iter+1; end %% Output % Inverse transformation to find axis and point on axis % corresponding to original data Rot = form_rotation_matrices(par); Axis = Rot0'*Rot'*[0 0 1]'; % axis direction % Compute the point distances to the axis [dist,~,h] = distances_to_line(P,Axis,Point0); dist = dist-Rad0; % distances without weights Len = max(h)-min(h); % Compute mad (for points with maximum weights) if nargin <= 4 mad = mean(abs(dist)); % mean absolute distance to the circle else I = weight == max(weight); mad = mean(abs(dist(I))); % mean absolute distance to the circle end % Compute SurfCov, minimum 3*8 grid if ~any(isnan(par)) && rel && conv nl = ceil(Len/res); nl = max(nl,3); ns = ceil(2*pi*Rad0/res); ns = max(ns,8); ns = min(36,ns); SurfCov = single(surface_coverage(P,Axis,Point0,nl,ns,0.8*Rad0)); else SurfCov = single(0); end %% Define the output clear cir cyl.radius = Rad0; cyl.start = Point0; cyl.axis = Axis'; cyl.mad = mad; cyl.SurfCov = SurfCov; cyl.conv = conv; cyl.rel = rel;
github
InverseTampere/TreeQSM-master
rotate_to_z_axis.m
.m
TreeQSM-master/src/least_squares_fitting/rotate_to_z_axis.m
1,206
utf_8
249265c0c3047e01a4cc30792d37be20
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [R,D,a] = rotate_to_z_axis(Vec) % -------------------------------------------------------------------------- % ROTATE_TO_Z_AXIS.M Forms the rotation matrix to rotate the vector to % a point along the positive z-axis. % % Input % Vec Vector (3 x 1) % % Output % R Rotation matrix, with R * Vec = [0 0 z]', z > 0 D = cross(Vec,[0 0 1]); if norm(D) > 0 a = acos(Vec(3)); R = rotation_matrix(D,a); else R = eye(3); a = 0; D = [1 0 0]; end
github
InverseTampere/TreeQSM-master
least_squares_cylinder.m
.m
TreeQSM-master/src/least_squares_fitting/least_squares_cylinder.m
6,889
utf_8
60305126c9e7fe2681c9f15ee98d5e21
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function cyl = least_squares_cylinder(P,cyl0,weight,Q) % --------------------------------------------------------------------- % LEAST_SQUARES_CYLINDER.M Least-squares cylinder using Gauss-Newton. % % Version 2.0.0 % Latest update 5 Oct 2021 % % Copyright (C) 2013-2021 Pasi Raumonen % --------------------------------------------------------------------- % Input % P Point cloud % cyl0 Initial estimates of the cylinder parameters % weight (Optional) Weights of the points for fitting % Q (Optional) Subset of "P" where the cylinder is intended % % Output % cyl Structure array containing the following fields: % radius Radius of the cylinder % length Length of the cylinder % start Point on the axis at the bottom of the cylinder (1 x 3) % axis Axis direction of the cylinder (1 x 3) % mad Mean absolute distance between points and cylinder surface % SurfCov Relative cover of the cylinder's surface by the points % dist Radial distances from the points to the cylinder (m x 1) % conv If conv = 1, the algorithm has converged % rel If rel = 1, the algorithm has reliable answer in terms of % matrix inversion with a good enough condition number % --------------------------------------------------------------------- % Changes from version 1.3.0 to 2.0.0, 5 Oct 2021: % 1) Included the Gauss-Newton iterations into this function (removed the % call to nlssolver function) % 2) Changed how the updata step is solved from the Jacobian % 3) Simplified some expressions and added comments % 4) mad is computed only from the points along the cylinder length in the % case of the optional input "Q" is given. % 5) Changed the surface coverage estimation by filtering out points whose % distance to the axis is less than 80% of the radius % Changes from version 1.2.0 to 1.3.0, 14 July 2020: % 1) Changed the input parameters of the cylinder to the struct format. % 2) Added optional input for weights % 3) Added optional input "Q", a subset of "P", the cylinder is intended % to be fitted in this subset but it is fitted to "P" to get better % estimate of the axis direction and radius % Changes from version 1.1.0 to 1.2.0, 14 Jan 2020: % 1) Changed the outputs and optionally the inputs to the struct format. % 2) Added new output, "mad", which is the mean absolute distance of the % points from the surface of the cylinder. % 3) Added new output, "SurfCov", that measures how well the surface of the % cylinder is covered by the points. % 4) Added new output, "SurfCovDis", which is a matrix of mean point distances % from layer/sector-intersections to the axis. % 5) Added new output, "SurfCovVol", which is an estimate of the cylinder's % volume based on the radii in "SurfCovDis" and "cylindrical sectors". % 6) Added new optional input "res" which gives the point resolution level % for computing SurfCov: the width and length of sectors/layers. % Changes from version 1.0.0 to 1.1.0, 3 Oct 2019: % 1) Bug fix: --> "Point = Rot0'*([par(1) par(2) 0]')..." %% Initialize data and values res = 0.03; % "Resolution level" for computing surface coverage maxiter = 50; % maximum number of Gauss-Newton iterations iter = 0; conv = false; % Did the iterations converge rel = true; % Are the results reliable (condition number was not very bad) if nargin == 2 NoWeights = true; % No point weight given for the fitting else NoWeights = false; end % Transform the data to close to standard position via a translation % followed by a rotation Rot0 = rotate_to_z_axis(cyl0.axis); Pt = (P-cyl0.start)*Rot0'; % Initial estimates par = [0 0 0 0 cyl0.radius]'; %% Gauss-Newton algorithm % find estimate of rotation-translation-radius parameters that transform % the data so that the best-fit cylinder is one in standard position while iter < maxiter && ~conv && rel %% Calculate the distances and Jacobian if NoWeights [d0,J] = func_grad_cylinder(par,Pt); else [d0,J] = func_grad_cylinder(par,Pt,weight); end %% Calculate update step SS0 = norm(d0); % Squared sum of the distances % solve for the system of equations: % par(i+1) = par(i) - (J'J)^(-1)*J'd0(par(i)) A = J'*J; b = J'*d0; warning off p = -A\b; % solve for the system of equations warning on par = par+p; % update the parameters %% Check reliability if rcond(-A) < 10000*eps rel = false; end %% Check convergence: % The distances with the new parameter values: if NoWeights dist = func_grad_cylinder(par,Pt); else dist = func_grad_cylinder(par,Pt,weight); end SS1 = norm(dist); % Squared sum of the distances if abs(SS0-SS1) < 1e-4 conv = true; end iter = iter + 1; end %% Compute the cylinder parameters and other outputs cyl.radius = single(par(5)); % radius % Inverse transformation to find axis and point on axis % corresponding to original data Rot = form_rotation_matrices(par(3:4)); Axis = Rot0'*Rot'*[0 0 1]'; % axis direction Point = Rot0'*([par(1) par(2) 0]')+cyl0.start'; % axis point % Compute the start, length and mad, translate the axis point to the % cylinder's bottom: % If the fourth input (point cloud Q) is given, use it for the start, % length, mad, and SurfCov if nargin == 4 if size(Q,1) > 5 P = Q; end end H = P*Axis; % heights along the axis hmin = min(H); cyl.length = single(abs(max(H)-hmin)); hpoint = Axis'*Point; Point = Point-(hpoint-hmin)*Axis; % axis point at the cylinder's bottom cyl.start = single(Point'); cyl.axis = single(Axis'); % Compute mad for the points along the cylinder length: if nargin >= 6 I = weight == max(weight); cyl.mad = single(average(abs(dist(I)))); % mean absolute distance else cyl.mad = single(average(abs(dist))); % mean absolute distance end cyl.conv = conv; cyl.rel = rel; % Compute SurfCov, minimum 3*8 grid if ~any(isnan(Axis)) && ~any(isnan(Point)) && rel && conv nl = max(3,ceil(cyl.length/res)); ns = ceil(2*pi*cyl.radius/res); ns = min(36,max(ns,8)); SurfCov = surface_coverage(P,Axis',Point',nl,ns,0.8*cyl.radius); cyl.SurfCov = single(SurfCov); else cyl.SurfCov = single(0); end
github
InverseTampere/TreeQSM-master
form_rotation_matrices.m
.m
TreeQSM-master/src/least_squares_fitting/form_rotation_matrices.m
1,449
utf_8
b8928d5554f70ccfc10d9b4a2e5af802
% This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see <http://www.gnu.org/licenses/>. function [R,dR1,dR2] = form_rotation_matrices(theta) % -------------------------------------------------------------------------- % FORM_ROTATION_MATRICES.M Forms rotation matrices R = R2*R1 and its % derivatives % % Input % theta Plane rotation angles (t1, t2) % % Output % R Rotation matrix % R1 Plane rotation [1 0 0; 0 c1 -s1; 0 s1 c1] % R2 Plane rotation [c2 0 s2; 0 1 0; -s2 0 c2] c = cos(theta); s = sin(theta); R1 = [1 0 0; 0 c(1) -s(1); 0 s(1) c(1)]; R = R1; R2 = [c(2) 0 s(2); 0 1 0; -s(2) 0 c(2)]; R = R2*R; if nargout > 1 dR1 = [0 0 0; 0 -R1(3,2) -R1(2,2); 0 R1(2,2) -R1(3,2)]; end if nargout > 2 dR2 = [-R2(1,3) 0 R2(1,1); 0 0 0; -R2(1,1) 0 -R2(1,3)]; end
github
soumendu041/clustering-network-valued-data-master
moments.m
.m
clustering-network-valued-data-master/moments.m
897
utf_8
1e2789b8f0f75799935c1311361a06e2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Comparison of graphs via normalizec count statistics/moments of the adjacency % matrix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = moments(A, k, method) % A = adjacency matrix of the desired graph % k = no. of moments requied % method = 'exact' or 'approx': 'exact' returns exact counts and % 'approx' returns normalized traces of powers of adjacency matrix y = zeros(k,1); if (strcmp(method,'approx')) n = size(A, 1); temp = A; for t = 1:k y(t) = trace(temp)/exp((1+t/2)*log(n)); % this normalization is for dense graphs temp = temp*temp; end elseif (strcmp(method, 'exact')) n = size(A, 1); % need to call those count functions Purna di downloaded end end
github
wvu-navLab/RobustGNSS-master
ccolamd_test.m
.m
RobustGNSS-master/gtsam/gtsam/3rdparty/CCOLAMD/MATLAB/ccolamd_test.m
11,944
utf_8
ab91fed9a7d6b40fa30544983b26cc7f
function ccolamd_test %CCOLAMD_TEST extensive test of ccolamd and csymamd % % Example: % ccolamd_test % % See also csymamd, ccolamd, ccolamd_make. % Copyright 1998-2007, Timothy A. Davis, Stefan Larimore, and Siva Rajamanickam % Developed in collaboration with J. Gilbert and E. Ng. help ccolamd_test global ccolamd_default_knobs csymamd_default_knobs ccolamd_default_knobs = [0 10 10 1 0] ; csymamd_default_knobs = [10 1 0] ; fprintf ('Compiling ccolamd, csymamd, and test mexFunctions.\n') ; ccolamd_make ; d = '' ; if (~isempty (strfind (computer, '64'))) d = '-largeArrayDims' ; end cmd = sprintf ( ... 'mex -DDLONG -O %s -I../../SuiteSparse_config -I../Include ', d) ; src = '../Source/ccolamd.c ../../SuiteSparse_config/SuiteSparse_config.c' ; if (~(ispc || ismac)) % for POSIX timing routine src = [src ' -lrt'] ; end eval ([cmd 'ccolamdtestmex.c ' src]) ; eval ([cmd 'csymamdtestmex.c ' src]) ; fprintf ('Done compiling.\n') ; fprintf ('\nThe following codes will be tested:\n') ; which ccolamd which csymamd which ccolamdtestmex which csymamdtestmex fprintf ('\nStarting the tests. Please be patient.\n') ; h = waitbar (0, 'COLAMD test') ; rand ('state', 0) ; randn ('state', 0) ; A = sprandn (500,500,0.4) ; p = ccolamd (A, [0 10 10 1 1]) ; check_perm (p, A) ; p = ccolamd (A, [1 2 7 1 1]) ; check_perm (p, A) ; p = ccolamd (A, [1 2 10 0 1]) ; check_perm (p, A) ; p = ccolamd (A, [9 2 3 1 1]) ; check_perm (p, A) ; p = csymamd (A, [10 1 1]) ; check_perm (p, A) ; p = csymamd (A, [4 1 1]) ; check_perm (p, A) ; p = csymamd (A, [9 0 1]) ; check_perm (p, A) ; fprintf ('Null matrices') ; A = zeros (0,0) ; A = sparse (A) ; p = ccolamd (A) ; check_perm (p, A) ; p = csymamd (A) ; check_perm (p, A) ; A = zeros (0, 100) ; A = sparse (A) ; p = ccolamd (A) ; check_perm (p, A) ; A = zeros (100, 0) ; A = sparse (A) ; p = ccolamd (A) ; check_perm (p, A) ; fprintf (' OK\n') ; fprintf ('Matrices with a few dense row/cols\n') ; for trial = 1:20 waitbar (trial/20, h, 'CCOLAMD: dense rows/cols') ; % random square unsymmetric matrix A = rand_matrix (1000, 1000, 1, 10, 20) ; [m n] = size (A) ; cmember = irand (min (trial,n), n) ; for tol = [0:.1:2 3:20 1e6] B = A + A' ; p = ccolamd (A, [ ]) ; check_perm (p, A) ; p = ccolamd (A, [1 tol tol 1]) ; check_perm (p, A) ; p = ccolamd (A, [0 tol tol 1]) ; check_perm (p, A) ; p = ccolamd (A, [1 tol tol 0]) ; check_perm (p, A) ; p = ccolamd (A, [0 tol tol 1]) ; check_perm (p, A) ; p = csymamd (A, [tol 1]) ; check_perm (p, A) ; p = csymamd (A, tol) ; check_perm (p, A) ; p = csymamd (A, [ ]) ; check_perm (p, A) ; p = csymamd (B, [tol 0]) ; check_perm (p, A) ; p = ccolamd (A, [0 tol -1 1]) ; check_perm (p, A) ; p = ccolamd (A, [0 -1 tol 1]) ; check_perm (p, A) ; % check with non-null cmember p = ccolamd (A, [ ], cmember) ; check_perm (p, A) ; p = ccolamd (A, [1 tol tol 1], cmember) ; check_perm (p, A) ; p = ccolamd (A, [0 tol tol 1], cmember) ; check_perm (p, A) ; p = ccolamd (A, [1 tol tol 0], cmember) ; check_perm (p, A) ; p = ccolamd (A, [0 tol tol 1], cmember) ; check_perm (p, A) ; p = csymamd (A, [tol 1], cmember) ; check_perm (p, A) ; p = csymamd (A, tol, cmember) ; check_perm (p, A) ; p = csymamd (A, [ ], cmember) ; check_perm (p, A) ; p = csymamd (B, [tol 0], cmember) ; check_perm (p, A) ; p = ccolamd (A, [0 tol -1 1], cmember) ; check_perm (p, A) ; p = ccolamd (A, [0 -1 tol 1], cmember) ; check_perm (p, A) ; p = ccolamd (A, [ ], [ ]) ; check_perm (p, A) ; p = ccolamd (A, [1 tol tol 1], [ ]) ; check_perm (p, A) ; p = ccolamd (A, [0 tol tol 1], [ ]) ; check_perm (p, A) ; p = ccolamd (A, [1 tol tol 0], [ ]) ; check_perm (p, A) ; p = ccolamd (A, [0 tol tol 1], [ ]) ; check_perm (p, A) ; p = csymamd (A, [tol 1], [ ]) ; check_perm (p, A) ; p = csymamd (A, tol, [ ]) ; check_perm (p, A) ; p = csymamd (A, [ ], [ ]) ; check_perm (p, A) ; p = csymamd (B, [tol 0], [ ]) ; check_perm (p, A) ; p = ccolamd (A, [0 tol -1 1], [ ]) ; check_perm (p, A) ; p = ccolamd (A, [0 -1 tol 1], [ ]) ; check_perm (p, A) ; end end fprintf (' OK\n') ; fprintf ('General matrices\n') ; for trial = 1:400 waitbar (trial/400, h, 'CCOLAMD: with dense rows/cols') ; % matrix of random mtype mtype = irand (3) ; A = rand_matrix (2000, 2000, mtype, 0, 0) ; p = ccolamd (A) ; check_perm (p, A) ; if (mtype == 3) p = csymamd (A) ; check_perm (p, A) ; end end fprintf (' OK\n') ; fprintf ('Test error handling with invalid inputs\n') ; % Check different erroneous input. for trial = 1:30 waitbar (trial/30, h, 'CCOLAMD: error handling') ; A = rand_matrix (1000, 1000, 2, 0, 0) ; for err = 1:13 p = Tcolamd (A, [ccolamd_default_knobs 1 err], [ ]) ; if (p(1) ~= -1) %#ok check_perm (p, A) ; end if (err == 1) % check different (valid) input args to ccolamd p = Acolamd (A) ; p2 = Acolamd (A, [ccolamd_default_knobs 0 0]) ; if (any (p ~= p2)) error ('ccolamd: mismatch 1!') ; end end B = A'*A ; p = Tsymamd (B, [-1 1 0 err], [ ]) ; if (p(1) ~= -1) %#ok check_perm (p, A) ; end if (err == 1) % check different (valid) input args to csymamd p = Asymamd (B) ; check_perm (p, A) ; p2 = Asymamd (B, [csymamd_default_knobs 0]) ; if (any (p ~= p2)) error ('symamd: mismatch 1!') ; end end end end fprintf (' OK\n') ; fprintf ('Matrices with a few empty columns\n') ; for trial = 1:400 waitbar (trial/400, h, 'CCOLAMD: with empty rows/cols') ; % some are square, some are rectangular n = 0 ; while (n < 5) A = rand_matrix (1000, 1000, irand (2), 0, 0) ; [m n] = size (A) ; end % Add 5 null columns at random locations. null_col = randperm (n) ; A (:, null_col) = 0 ; % Order the matrix and make sure that the null columns are ordered last. p = ccolamd (A, [1 1e6 1e6 0]) ; check_perm (p, A) ; % find all null columns in A null_col = find (sum (spones (A), 1) == 0) ; nnull = length (null_col) ; if (any (null_col ~= p ((n-nnull+1):n))) error ('ccolamd: Null cols are not ordered last in natural order') ; end end fprintf (' OK\n') ; fprintf ('Matrices with a few empty rows and columns\n') ; for trial = 1:400 waitbar (trial/400, h, 'CCOLAMD: with empty rows/cols') ; % symmetric matrices n = 0 ; while (n < 5) A = rand_matrix (1000, 1000, 3, 0, 0) ; [m n] = size (A) ; end % Add 5 null columns and rows at random locations. null_col = randperm (n) ; A (:, null_col) = 0 ; A (null_col, :) = 0 ; % Order the matrix and make sure that the null rows/cols are ordered last. p = csymamd (A, -1) ; check_perm (p, A) ; % find all null rows/columns in A Alo = tril (A, -1) ; null_col = ... find ((sum (spones (Alo), 1) == 0) & (sum (spones (Alo), 2) == 0)') ; nnull = length (null_col) ; if (any (null_col ~= p ((n-nnull+1):n))) error ('csymamd: Null cols are not ordered last in natural order') ; end end fprintf (' OK\n') ; fprintf ('Matrices with a few empty rows\n') ; % Test matrices with null rows inserted. for trial = 1:400 waitbar (trial/400, h, 'CCOLAMD: with null rows') ; m = 0 ; while (m < 5) A = rand_matrix (1000, 1000, 2, 0, 0) ; m = size (A,1) ; end % Add 5 null rows at random locations. null_row = randperm (m) ; null_row = sort (null_row (1:5)) ; A (null_row, :) = 0 ; p = ccolamd (A) ; check_perm (p, A) ; end fprintf (' OK\n') ; fprintf ('\nccolamd and csymamd: all tests passed\n\n') ; close (h) ; %------------------------------------------------------------------------------- function p = Acolamd (S, knobs) % Acolamd: compare ccolamd and Tcolamd results global ccolamd_default_knobs if (nargin < 2) p = ccolamd (S) ; p1 = Tcolamd (S, [ccolamd_default_knobs 0 0], [ ]) ; else p = ccolamd (S, knobs) ; p1 = Tcolamd (S, knobs, [ ]) ; end check_perm (p, S) ; check_perm (p1, S) ; if (any (p1 ~= p)) narg = nargin ; if (nargin == 2) save bad S narg knobs else save bad S narg end error ('Acolamd mismatch!') ; end %------------------------------------------------------------------------------- function p = Asymamd (S, knobs) % Asymamd: compare csymamd and Tsymamd results global csymamd_default_knobs if (nargin < 2) p = csymamd (S) ; p1 = Tsymamd (S, [csymamd_default_knobs 0], [ ]) ; else p = csymamd (S, knobs) ; p1 = Tsymamd (S, knobs, [ ]) ; end if (any (p1 ~= p)) error ('Asymamd mismatch!') ; end %------------------------------------------------------------------------------- function check_perm (p, A, cmember) % check_perm: check for a valid permutation vector if (isempty (A) & isempty (p)) %#ok % empty permutation vectors of empty matrices are OK return end if (isempty (p)) error ('Bad permutation: cannot be empty') ; end [m n] = size (A) ; [p_m p_n] = size (p) ; if (p_n == 1) % force p to be a row vector p = p' ; [p_m p_n] = size (p) ; end if (n ~= p_n) error ('Bad permutation: wrong size') ; end if (p_m ~= 1) ; % p must be a vector error ('Bad permutation: not a vector') ; else if (any (sort (p) - (1:p_n))) error ('Bad permutation') ; end end if (nargin > 2) % check cmember c = cmember (p) ; % c must be monotonically non-decreasing c = diff (c) ; if (any (c < 0)) error ('permutation breaks the cmember constraints') ; end end %------------------------------------------------------------------------------- function i = irand (n,s) % irand: return a random vector of size s, with values between 1 and n if (nargin == 1) s = 1 ; end i = min (n, 1 + floor (rand (1,s) * n)) ; %------------------------------------------------------------------------------- function A = rand_matrix (n_max, m_max, mtype, d_rows, d_cols) % rand_matrix: return a random sparse matrix % % A = rand_matrix (n_max, m_max, mtype, d_rows, d_cols) % % A binary matrix of random size, at most n_max-by-m_max, with d_rows dense rows % and d_cols dense columns. % % mtype 1: square unsymmetric (m_max is ignored) % mtype 2: rectangular % mtype 3: symmetric (m_max is ignored) n = irand (n_max) ; if (mtype ~= 2) % square m = n ; else m = irand (m_max) ; end A = sprand (m, n, 10 / max (m,n)) ; if (d_rows > 0) % add dense rows for k = 1:d_rows i = irand (m) ; nz = irand (n) ; p = randperm (n) ; p = p (1:nz) ; A (i,p) = 1 ; end end if (d_cols > 0) % add dense cols for k = 1:d_cols j = irand (n) ; nz = irand (m) ; p = randperm (m) ; p = p (1:nz) ; A (p,j) = 1 ; end end A = spones (A) ; % ensure that there are no empty columns d = find (full (sum (A,1)) == 0) ; %#ok A (m,d) = 1 ; %#ok % ensure that there are no empty rows d = find (full (sum (A,2)) == 0) ; %#ok A (d,n) = 1 ; %#ok if (mtype == 3) % symmetric A = A + A' + speye (n) ; end A = spones (A) ; %------------------------------------------------------------------------------- % Tcolamd: run ccolamd in a testing mode %------------------------------------------------------------------------------- function p = Tcolamd (S, knobs, cmember) % knobs (5) = 1 ; p = ccolamdtestmex (S, knobs, cmember) ; if (p (1) ~= -1) check_perm (p, S) ; end %------------------------------------------------------------------------------- % Tsymamd: run csymamd in a testing mode %------------------------------------------------------------------------------- function p = Tsymamd (S, knobs, cmember) % knobs (2) = 1 ; p = csymamdtestmex (S, knobs, cmember) ; if (p (1) ~= -1) check_perm (p, S) ; end
github
wvu-navLab/RobustGNSS-master
geodarea.m
.m
RobustGNSS-master/gtsam/gtsam/3rdparty/GeographicLib/matlab/geodarea.m
4,241
utf_8
a20b9abbe24d8781e0c053b3ddfd9f3a
function [A, P, N] = geodarea(lats, lons, ellipsoid) %GEODAREA Surface area of polygon on an ellipsoid % % A = GEODAREA(lats, lons) % [A, P, N] = GEODAREA(lats, lons, ellipsoid) % % calculates the surface area A of the geodesic polygon specified by the % input vectors lats, lons (in degrees). The ellipsoid vector is of the % form [a, e], where a is the equatorial radius in meters, e is the % eccentricity. If ellipsoid is omitted, the WGS84 ellipsoid (more % precisely, the value returned by DEFAULTELLIPSOID) is used. There is % no need to "close" the polygon by repeating the first point. Multiple % polygons can be specified by separating the vertices by NaNs in the % vectors. Thus a series of quadrilaterals can be specified as two 5 x K % arrays where the 5th row is NaN. The output, A, is in meters^2. % Counter-clockwise traversal counts as a positive area. Only simple % polygons (which do not intersect themselves) are supported. Also % returned are the perimeters of the polygons in P (meters) and the % numbers of vertices in N. GEODDOC gives the restrictions on the % allowed ranges of the arguments. % % GEODAREA loosely duplicates the functionality of the AREAINT function % in the MATLAB mapping toolbox. The major difference is that the % polygon edges are taken to be geodesics and the area contributed by % each edge is computed using a series expansion with is accurate % regardless of the length of the edge. The formulas are derived in % % C. F. F. Karney, Algorithms for geodesics, % J. Geodesy 87, 43-55 (2013); % http://dx.doi.org/10.1007/s00190-012-0578-z % Addenda: http://geographiclib.sf.net/geod-addenda.html % % See also GEODDOC, GEODDISTANCE, GEODRECKON, POLYGONAREA, % DEFAULTELLIPSOID. % Copyright (c) Charles Karney (2012-2013) <[email protected]>. % % This file was distributed with GeographicLib 1.31. if nargin < 2, error('Too few input arguments'), end if nargin < 3, ellipsoid = defaultellipsoid; end if ~isequal(size(lats), size(lons)) error('lats, lons have incompatible sizes') end if length(ellipsoid(:)) ~= 2 error('ellipsoid must be a vector of size 2') end lat1 = lats(:); lon1 = lons(:); M = length(lat1); ind = [0; find(isnan(lat1 + lon1))]; if length(ind) == 1 || ind(end) ~= M ind = [ind; M + 1]; end K = length(ind) - 1; A = zeros(K, 1); P = A; N = A; if M == 0, return, end lat2 = [lat1(2:end, 1); 0]; lon2 = [lon1(2:end, 1); 0]; m0 = min(M, ind(1:end-1) + 1); m1 = max(1, ind(2:end) - 1); lat2(m1) = lat1(m0); lon2(m1) = lon1(m0); a = ellipsoid(1); e2 = ellipsoid(2)^2; f = e2 / (1 + sqrt(1 - e2)); b = (1 - f) * a; c2 = (a^2 + b^2 * atanhee(1, e2)) / 2; area0 = 4 * pi * c2; [s12, ~, ~, S12] = geoddistance(lat1, lon1, lat2, lon2, ellipsoid); cross = transit(lon1, lon2); for k = 1 : K N(k) = m1(k) - m0(k) + 1; P(k) = accumulator(s12(m0(k):m1(k))); [As, At] = accumulator(S12(m0(k):m1(k))); crossings = sum(cross(m0(k):m1(k))); if mod(crossings, 2) ~= 0, [As, At] = accumulator( ((As < 0) * 2 - 1) * area0 / 2, As, At); end As = -As; At = -At; if As > area0/2 As = accumulator( -area0 / 2, As, At); elseif As <= -area0/2 As = accumulator( area0 / 2, As, At); end A(k) = As; end end function cross = transit(lon1, lon2) %TRANSIT Count crossings of prime meridian % % CROSS = TRANSIT(LON1, LON2) return 1 or -1 if crossing prime meridian % in east or west direction. Otherwise return zero. lon1 = AngNormalize(lon1); lon2 = AngNormalize(lon2); lon12 = AngDiff(lon1, lon2); cross = zeros(length(lon1), 1); cross(lon1 < 0 & lon2 >= 0 & lon12 > 0) = 1; cross(lon2 < 0 & lon1 >= 0 & lon12 < 0) = -1; end function [s, t] = accumulator(x, s, t) %ACCUMULATOR Accurately sum x % % [S, T] = ACCUMULATOR(X, S, T) accumulate the sum of the elements of X % into [S, T] using extended precision. S and T are scalars. if nargin < 3, t = 0; end if nargin < 2, s = 0; end for y = x(:)', % Here's Shewchuk's solution... [z, u] = sumx(y, t); [s, t] = sumx(z, s); if s == 0 s = u; else t = t + u; end end end
github
wvu-navLab/RobustGNSS-master
geoddistance.m
.m
RobustGNSS-master/gtsam/gtsam/3rdparty/GeographicLib/matlab/geoddistance.m
17,333
utf_8
3b8e33df114efbd010cafcfdd2b79868
function [s12, azi1, azi2, S12, m12, M12, M21, a12] = geoddistance ... (lat1, lon1, lat2, lon2, ellipsoid) %GEODDISTANCE Distance between points on an ellipsoid % % [s12, azi1, azi2] = GEODDISTANCE(lat1, lon1, lat2, lon2) % [s12, azi1, azi2, S12, m12, M12, M21, a12] = % GEODDISTANCE(lat1, lon1, lat2, lon2, ellipsoid) % % solves the inverse geodesic problem of finding of length and azimuths % of the shortest geodesic between points specified by lat1, lon1, lat2, % lon2. The input latitudes and longitudes, lat1, lon1, lat2, lon2, can % be scalars or arrays of equal size and must be expressed in degrees. % The ellipsoid vector is of the form [a, e], where a is the equatorial % radius in meters, e is the eccentricity. If ellipsoid is omitted, the % WGS84 ellipsoid (more precisely, the value returned by % DEFAULTELLIPSOID) is used. The output s12 is the distance in meters % and azi1 and azi2 are the forward azimuths at the end points in % degrees. The other optional outputs, S12, m12, M12, M21, a12 are % documented in GEODDOC. GEODDOC also gives the restrictions on the % allowed ranges of the arguments. % % When given a combination of scalar and array inputs, the scalar inputs % are automatically expanded to match the size of the arrays. % % This is an implementation of the algorithm given in % % C. F. F. Karney, Algorithms for geodesics, % J. Geodesy 87, 43-55 (2013); % http://dx.doi.org/10.1007/s00190-012-0578-z % Addenda: http://geographiclib.sf.net/geod-addenda.html % % This function duplicates some of the functionality of the DISTANCE % function in the MATLAB mapping toolbox. Differences are % % * When the ellipsoid argument is omitted, use the WGS84 ellipsoid. % * The routines work for prolate (as well as oblate) ellipsoids. % * The azimuth at the second end point azi2 is returned. % * The solution is accurate to round off for abs(e) < 0.2. % * The algorithm converges for all pairs of input points. % * Additional properties of the geodesic are calcuated. % % See also GEODDOC, GEODRECKON, GEODAREA, GEODESICINVERSE, % DEFAULTELLIPSOID. % Copyright (c) Charles Karney (2012, 2013) <[email protected]>. % % This file was distributed with GeographicLib 1.31. % % This is a straightforward transcription of the C++ implementation in % GeographicLib and the C++ source should be consulted for additional % documentation. This is a vector implementation and the results returned % with array arguments are identical to those obtained with multiple calls % with scalar arguments. The biggest change was to eliminate the branching % to allow a vectorized solution. if nargin < 4, error('Too few input arguments'), end if nargin < 5, ellipsoid = defaultellipsoid; end try Z = lat1 + lon1 + lat2 + lon2; S = size(Z); Z = zeros(S); lat1 = lat1 + Z; lon1 = lon1 + Z; lat2 = lat2 + Z; lon2 = lon2 + Z; Z = Z(:); catch err error('lat1, lon1, s12, azi1 have incompatible sizes') end if length(ellipsoid(:)) ~= 2 error('ellipsoid must be a vector of size 2') end degree = pi/180; tiny = sqrt(realmin); tol0 = eps; tolb = eps * sqrt(eps); maxit1 = 20; maxit2 = maxit1 + (-log2(eps) + 1) + 10; a = ellipsoid(1); e2 = ellipsoid(2)^2; f = e2 / (1 + sqrt(1 - e2)); f1 = 1 - f; ep2 = e2 / (1 - e2); n = f / (2 - f); b = a * f1; areap = nargout >= 4; scalp = nargout >= 6; A3x = A3coeff(n); C3x = C3coeff(n); lon12 = AngDiff(AngNormalize(lon1(:)), AngNormalize(lon2(:))); lon12 = AngRound(lon12); lonsign = 2 * (lon12 >= 0) - 1; lon12 = lonsign .* lon12; lat1 = AngRound(lat1(:)); lat2 = AngRound(lat2(:)); swapp = 2 * (abs(lat1) >= abs(lat2)) - 1; lonsign(swapp < 0) = - lonsign(swapp < 0); [lat1(swapp < 0), lat2(swapp < 0)] = swap(lat1(swapp < 0), lat2(swapp < 0)); latsign = 2 * (lat1 < 0) - 1; lat1 = latsign .* lat1; lat2 = latsign .* lat2; phi = lat1 * degree; sbet1 = f1 * sin(phi); cbet1 = cos(phi); cbet1(lat1 == -90) = tiny; [sbet1, cbet1] = SinCosNorm(sbet1, cbet1); phi = lat2 * degree; sbet2 = f1 * sin(phi); cbet2 = cos(phi); cbet2(abs(lat2) == 90) = tiny; [sbet2, cbet2] = SinCosNorm(sbet2, cbet2); c = cbet1 < -sbet1 & cbet2 == cbet1; sbet2(c) = (2 * (sbet2(c) < 0) - 1) .* sbet1(c); c = ~(cbet1 < -sbet1) & abs(sbet2) == - sbet1; cbet2(c) = cbet1(c); dn1 = sqrt(1 + ep2 * sbet1.^2); dn2 = sqrt(1 + ep2 * sbet2.^2); lam12 = lon12 * degree; slam12 = sin(lam12); slam12(lon12 == 180) = 0; clam12 = cos(lam12); sig12 = Z; ssig1 = Z; csig1 = Z; ssig2 = Z; csig2 = Z; calp1 = Z; salp1 = Z; calp2 = Z; salp2 = Z; s12 = Z; m12 = Z; M12 = Z; M21 = Z; omg12 = Z; m = lat1 == -90 | slam12 == 0; if any(m) calp1(m) = clam12(m); salp1(m) = slam12(m); calp2(m) = 1; salp2(m) = 0; ssig1(m) = sbet1(m); csig1(m) = calp1(m) .* cbet1(m); ssig2(m) = sbet2(m); csig2(m) = calp2(m) .* cbet2(m); sig12(m) = atan2(max(csig1(m) .* ssig2(m) - ssig1(m) .* csig2(m), 0), ... csig1(m) .* csig2(m) + ssig1(m) .* ssig2(m)); [s12(m), m12(m), ~, M12(m), M21(m)] = ... Lengths(n, sig12(m), ... ssig1(m), csig1(m), dn1(m), ssig2(m), csig2(m), dn2(m), ... cbet1(m), cbet2(m), scalp, ep2); m = m & (sig12 < 1 | m12 >= 0); m12(m) = m12(m) * b; s12(m) = s12(m) * b; end eq = ~m & sbet1 == 0; if f > 0 eq = eq & lam12 < pi - f * pi; end calp1(eq) = 0; calp2(eq) = 0; salp1(eq) = 1; salp2(eq) = 1; s12(eq) = a * lam12(eq); sig12(eq) = lam12(eq) / f1; omg12(eq) = sig12(eq); m12(eq) = b * sin(omg12(eq)); M12(eq) = cos(omg12(eq)); M21(eq) = M12(eq); g = ~eq & ~m; dnm = Z; [sig12(g), salp1(g), calp1(g), salp2(g), calp2(g), dnm(g)] = ... InverseStart(sbet1(g), cbet1(g), dn1(g), sbet2(g), cbet2(g), dn2(g), ... lam12(g), f, A3x); s = g & sig12 >= 0; s12(s) = b * sig12(s) .* dnm(s); m12(s) = b * dnm(s).^2 .* sin(sig12(s) ./ dnm(s)); if scalp M12(s) = cos(sig12(s) ./ dnm(s)); M21(s) = M12(s); end omg12(s) = lam12(s) ./ (f1 * dnm(s)); g = g & sig12 < 0; salp1a = Z + tiny; calp1a = Z + 1; salp1b = Z + tiny; calp1b = Z - 1; ssig1 = Z; csig1 = Z; ssig2 = Z; csig2 = Z; epsi = Z; v = Z; dv = Z; numit = Z; tripn = Z > 0; tripb = tripn; gsave = g; for k = 0 : maxit2 - 1 if k == 0 && ~any(g), break, end numit(g) = k; [v(g), dv(g), ... salp2(g), calp2(g), sig12(g), ... ssig1(g), csig1(g), ssig2(g), csig2(g), epsi(g), omg12(g)] = ... Lambda12(sbet1(g), cbet1(g), dn1(g), ... sbet2(g), cbet2(g), dn2(g), ... salp1(g), calp1(g), f, A3x, C3x); v = v - lam12; g = g & ~(tripb | ~(abs(v) >= ((tripn * 6) + 2) * tol0)); if ~any(g), break, end c = g & v > 0; if k <= maxit1 c = c & calp1 ./ salp1 > calp1b ./ salp1b; end salp1b(c) = salp1(c); calp1b(c) = calp1(c); c = g & v < 0; if k <= maxit1 c = c & calp1 ./ salp1 < calp1a ./ salp1a; end salp1a(c) = salp1(c); calp1a(c) = calp1(c); if k == maxit1, tripn(g) = false; end if k < maxit1 dalp1 = -v ./ dv; sdalp1 = sin(dalp1); cdalp1 = cos(dalp1); nsalp1 = salp1 .* cdalp1 + calp1 .* sdalp1; calp1(g) = calp1(g) .* cdalp1(g) - salp1(g) .* sdalp1(g); salp1(g) = nsalp1(g); tripn = g & abs(v) <= 16 * tol0; c = g & ~(dv > 0 & nsalp1 > 0 & abs(dalp1) < pi); tripn(c) = false; else c = g; end salp1(c) = (salp1a(c) + salp1b(c))/2; calp1(c) = (calp1a(c) + calp1b(c))/2; [salp1(g), calp1(g)] = SinCosNorm(salp1(g), calp1(g)); tripb(c) = (abs(salp1a(c) - salp1(c)) + (calp1a(c) - calp1(c)) < tolb | ... abs(salp1(c) - salp1b(c)) + (calp1(c) - calp1b(c)) < tolb); end g = gsave; [s12(g), m12(g), ~, M12(g), M21(g)] = ... Lengths(epsi(g), sig12(g), ... ssig1(g), csig1(g), dn1(g), ssig2(g), csig2(g), dn2(g), ... cbet1(g), cbet2(g), scalp, ep2); m12(g) = m12(g) * b; s12(g) = s12(g) * b; omg12(g) = lam12(g) - omg12(g); s12 = 0 + s12; if areap salp0 = salp1 .* cbet1; calp0 = hypot(calp1, salp1 .* sbet1); ssig1 = sbet1; csig1 = calp1 .* cbet1; ssig2 = sbet2; csig2 = calp2 .* cbet2; k2 = calp0.^2 * ep2; epsi = k2 ./ (2 * (1 + sqrt(1 + k2)) + k2); A4 = (a^2 * e2) * calp0 .* salp0; [ssig1, csig1] = SinCosNorm(ssig1, csig1); [ssig2, csig2] = SinCosNorm(ssig2, csig2); C4x = C4coeff(n); C4a = C4f(epsi, C4x); B41 = SinCosSeries(false, ssig1, csig1, C4a); B42 = SinCosSeries(false, ssig2, csig2, C4a); S12 = A4 .* (B42 - B41); S12(calp0 == 0 | salp0 == 0) = 0; l = ~m & omg12 < 0.75 * pi & sbet2 - sbet1 < 1.75; alp12 = Z; somg12 = sin(omg12(l)); domg12 = 1 + cos(omg12(l)); dbet1 = 1 + cbet1(l); dbet2 = 1 + cbet2(l); alp12(l) = 2 * atan2(somg12 .* (sbet1(l) .* dbet2 + sbet2(l) .* dbet1), ... domg12 .* (sbet1(l) .* sbet2(l) + dbet1 .* dbet2)); l = ~l; salp12 = salp2(l) .* calp1(l) - calp2(l) .* salp1(l); calp12 = calp2(l) .* calp1(l) + salp2(l) .* salp1(l); s = salp12 == 0 & calp12 < 0; salp12(s) = tiny * calp1(s); calp12(s) = -1; alp12(l) = atan2(salp12, calp12); c2 = (a^2 + b^2 * atanhee(1, e2)) / 2; S12 = 0 + swapp .* lonsign .* latsign .* (S12 + c2 * alp12); end [salp1(swapp<0), salp2(swapp<0)] = swap(salp1(swapp<0), salp2(swapp<0)); [calp1(swapp<0), calp2(swapp<0)] = swap(calp1(swapp<0), calp2(swapp<0)); if scalp [M12(swapp<0), M21(swapp<0)] = swap(M12(swapp<0), M21(swapp<0)); end salp1 = salp1 .* swapp .* lonsign; calp1 = calp1 .* swapp .* latsign; salp2 = salp2 .* swapp .* lonsign; calp2 = calp2 .* swapp .* latsign; azi1 = 0 - atan2(-salp1, calp1) / degree; azi2 = 0 - atan2(-salp2, calp2) / degree; a12 = sig12 / degree; s12 = reshape(s12, S); azi1 = reshape(azi1, S); azi2 = reshape(azi2, S); m12 = reshape(m12, S); M12 = reshape(M12, S); M21 = reshape(M21, S); a12 = reshape(a12, S); if (areap) S12 = reshape(S12, S); end end function [sig12, salp1, calp1, salp2, calp2, dnm] = ... InverseStart(sbet1, cbet1, dn1, sbet2, cbet2, dn2, lam12, f, A3x) %INVERSESTART Compute a starting point for Newton's method N = length(sbet1); f1 = 1 - f; e2 = f * (2 - f); ep2 = e2 / (1 - e2); n = f / (2 - f); tol0 = eps; tol1 = 200 * tol0; tol2 = sqrt(eps); etol2 = 0.1 * tol2 / sqrt( max(0.001, abs(f)) * min(1, 1 - f/2) / 2 ); xthresh = 1000 * tol2; sig12 = -ones(N, 1); salp2 = NaN(N, 1); calp2 = NaN(N, 1); sbet12 = sbet2 .* cbet1 - cbet2 .* sbet1; cbet12 = cbet2 .* cbet1 + sbet2 .* sbet1; sbet12a = sbet2 .* cbet1 + cbet2 .* sbet1; s = cbet12 >= 0 & sbet12 < 0.5 & cbet2 .* lam12 < 0.5; omg12 = lam12; dnm = NaN(N, 1); sbetm2 = (sbet1(s) + sbet2(s)).^2; sbetm2 = sbetm2 ./ (sbetm2 + (cbet1(s) + cbet2(s)).^2); dnm(s) = sqrt(1 + ep2 * sbetm2); omg12(s) = omg12(s) ./ (f1 * dnm(s)); somg12 = sin(omg12); comg12 = cos(omg12); salp1 = cbet2 .* somg12; t = cbet2 .* sbet1 .* somg12.^2; calp1 = cvmgt(sbet12 + t ./ (1 + comg12), ... sbet12a - t ./ (1 - comg12), ... comg12 >= 0); ssig12 = hypot(salp1, calp1); csig12 = sbet1 .* sbet2 + cbet1 .* cbet2 .* comg12; s = s & ssig12 < etol2; salp2(s) = cbet1(s) .* somg12(s); calp2(s) = somg12(s).^2 ./ (1 + comg12(s)); calp2(s & comg12 < 0) = 1 - comg12(s & comg12 < 0); calp2(s) = sbet12(s) - cbet1(s) .* sbet2(s) .* calp2(s); [salp2, calp2] = SinCosNorm(salp2, calp2); sig12(s) = atan2(ssig12(s), csig12(s)); s = ~(s | abs(n) > 0.1 | csig12 >= 0 | ssig12 >= 6 * abs(n) * pi * cbet1.^2); if any(s) if f >= 0 k2 = sbet1(s).^2 * ep2; epsi = k2 ./ (2 * (1 + sqrt(1 + k2)) + k2); lamscale = f * cbet1(s) .* A3f(epsi, A3x) * pi; betscale = lamscale .* cbet1(s); x = (lam12(s) - pi) ./ lamscale; y = sbet12a(s) ./ betscale; else cbet12a = cbet2(s) .* cbet1(s) - sbet2(s) .* sbet1(s); bet12a = atan2(sbet12a(s), cbet12a); [~, m12b, m0] = ... Lengths(n, pi + bet12a, ... sbet1(s), -cbet1(s), dn1(s), sbet2(s), cbet2(s), dn2(s), ... cbet1(s), cbet2(s), false); x = -1 + m12b ./ (cbet1(s) .* cbet2(s) .* m0 * pi); betscale = cvmgt(sbet12a(s) ./ x, - f * cbet1(s).^2 * pi, x < -0.01); lamscale = betscale ./ cbet1(s); y = (lam12(s) - pi) ./ lamscale; end k = Astroid(x, y); if f >= 0 omg12a = -x .* k ./ (1 + k); else omg12a = -y .* (1 + k) ./ k; end omg12a = lamscale .* omg12a; somg12 = sin(omg12a); comg12 = -cos(omg12a); salp1(s) = cbet2(s) .* somg12; calp1(s) = sbet12a(s) - cbet2(s) .* sbet1(s) .* somg12.^2 ./ (1 - comg12); str = y > -tol1 & x > -1 - xthresh; if any(str) salp1s = salp1(s); calp1s = calp1(s); if f >= 0 salp1s(str) = min(1, -x(str)); calp1s(str) = -sqrt(1 - salp1s(str).^2); else calp1s(str) = max(cvmgt(0, -1, x(str) > -tol1), x(str)); salp1s(str) = sqrt(1 - calp1s(str).^2); end salp1(s) = salp1s; calp1(s) = calp1s; end end calp1(salp1 <= 0) = 0; salp1(salp1 <= 0) = 1; [salp1, calp1] = SinCosNorm(salp1, calp1); end function k = Astroid(x, y) % ASTROID Solve the astroid equation % % K = ASTROID(X, Y) solves the quartic polynomial Eq. (55) % % K^4 + 2 * K^3 - (X^2 + Y^2 - 1) * K^2 - 2*Y^2 * K - Y^2 = 0 % % for the positive root K. X and Y are column vectors of the same size % and the returned value K has the same size. k = zeros(length(x), 1); p = x.^2; q = y.^2; r = (p + q - 1) / 6; fl1 = ~(q == 0 & r <= 0); p = p(fl1); q = q(fl1); r = r(fl1); S = p .* q / 4; r2 = r.^2; r3 = r .* r2; disc = S .* (S + 2 * r3); u = r; fl2 = disc >= 0; T3 = S(fl2) + r3(fl2); T3 = T3 + (1 - 2 * (T3 < 0)) .* sqrt(disc(fl2)); T = cbrt(T3); u(fl2) = u(fl2) + T + cvmgt(r2(fl2) ./ T, 0, T ~= 0); ang = atan2(sqrt(-disc(~fl2)), -(S(~fl2) + r3(~fl2))); u(~fl2) = u(~fl2) + 2 * r(~fl2) .* cos(ang / 3); v = sqrt(u.^2 + q); uv = u + v; fl2 = u < 0; uv(fl2) = q(fl2) ./ (v(fl2) - u(fl2)); w = (uv - q) ./ (2 * v); k(fl1) = uv ./ (sqrt(uv + w.^2) + w); end function [lam12, dlam12, ... salp2, calp2, sig12, ssig1, csig1, ssig2, csig2, epsi, domg12] = ... Lambda12(sbet1, cbet1, dn1, sbet2, cbet2, dn2, salp1, calp1, f, A3x, C3x) %LAMBDA12 Solve the hybrid problem tiny = sqrt(realmin); f1 = 1 - f; e2 = f * (2 - f); ep2 = e2 / (1 - e2); calp1(sbet1 == 0 & calp1 == 0) = -tiny; salp0 = salp1 .* cbet1; calp0 = hypot(calp1, salp1 .* sbet1); ssig1 = sbet1; somg1 = salp0 .* sbet1; csig1 = calp1 .* cbet1; comg1 = csig1; [ssig1, csig1] = SinCosNorm(ssig1, csig1); salp2 = cvmgt(salp0 ./ cbet2, salp1, cbet2 ~= cbet1); calp2 = cvmgt(sqrt((calp1 .* cbet1).^2 + ... cvmgt((cbet2 - cbet1) .* (cbet1 + cbet2), ... (sbet1 - sbet2) .* (sbet1 + sbet2), ... cbet1 < -sbet1)) ./ cbet2, ... abs(calp1), cbet2 ~= cbet1 | abs(sbet2) ~= -sbet1); ssig2 = sbet2; somg2 = salp0 .* sbet2; csig2 = calp2 .* cbet2; comg2 = csig2; [ssig2, csig2] = SinCosNorm(ssig2, csig2); sig12 = atan2(max(csig1 .* ssig2 - ssig1 .* csig2, 0), ... csig1 .* csig2 + ssig1 .* ssig2); omg12 = atan2(max(comg1 .* somg2 - somg1 .* comg2, 0), ... comg1 .* comg2 + somg1 .* somg2); k2 = calp0.^2 * ep2; epsi = k2 ./ (2 * (1 + sqrt(1 + k2)) + k2); C3a = C3f(epsi, C3x); B312 = SinCosSeries(true, ssig2, csig2, C3a) - ... SinCosSeries(true, ssig1, csig1, C3a); h0 = -f * A3f(epsi, A3x); domg12 = salp0 .* h0 .* (sig12 + B312); lam12 = omg12 + domg12; [~, dlam12] = ... Lengths(epsi, sig12, ... ssig1, csig1, dn1, ssig2, csig2, dn2, cbet1, cbet2, false); dlam12 = dlam12 .* f1 ./ (calp2 .* cbet2); z = calp2 == 0; dlam12(z) = - 2 * f1 .* dn1(z) ./ sbet1(z); end function [s12b, m12b, m0, M12, M21] = ... Lengths(epsi, sig12, ssig1, csig1, dn1, ssig2, csig2, dn2, ... cbet1, cbet2, scalp, ep2) %LENGTHS Compute various lengths associate with a geodesic if isempty(sig12) s12b = []; m12b = []; m0 = []; M12 = []; M21 = []; return end C1a = C1f(epsi); C2a = C2f(epsi); A1m1 = A1m1f(epsi); AB1 = (1 + A1m1) .* (SinCosSeries(true, ssig2, csig2, C1a) - ... SinCosSeries(true, ssig1, csig1, C1a)); A2m1 = A2m1f(epsi); AB2 = (1 + A2m1) .* (SinCosSeries(true, ssig2, csig2, C2a) - ... SinCosSeries(true, ssig1, csig1, C2a)); m0 = A1m1 - A2m1; J12 = m0 .* sig12 + (AB1 - AB2); m12b = dn2 .* (csig1 .* ssig2) - dn1 .* (ssig1 .* csig2) - ... csig1 .* csig2 .* J12; s12b = (1 + A1m1) .* sig12 + AB1; if scalp csig12 = csig1 .* csig2 + ssig1 .* ssig2; t = ep2 * (cbet1 - cbet2) .* (cbet1 + cbet2) ./ (dn1 + dn2); M12 = csig12 + (t .* ssig2 - csig2 .* J12) .* ssig1 ./ dn1; M21 = csig12 - (t .* ssig1 - csig1 .* J12) .* ssig2 ./ dn2; else M12 = sig12 + NaN; M21 = M12; end end
github
wvu-navLab/RobustGNSS-master
tranmerc_fwd.m
.m
RobustGNSS-master/gtsam/gtsam/3rdparty/GeographicLib/matlab/tranmerc_fwd.m
5,674
utf_8
acff0226812f95bc17989337218cdde5
function [x, y, gam, k] = tranmerc_fwd(lat0, lon0, lat, lon, ellipsoid) %TRANMERC_FWD Forward transverse Mercator projection % % [X, Y] = TRANMERC_FWD(LAT0, LON0, LAT, LON) % [X, Y, GAM, K] = TRANMERC_FWD(LAT0, LON0, LAT, LON, ELLIPSOID) % % performs the forward transverse Mercator projection of points (LAT,LON) % to (X,Y) using (LAT0,LON0) as the center of projection. These input % arguments can be scalars or arrays of equal size. The ELLIPSOID vector % is of the form [a, e], where a is the equatorial radius in meters, e is % the eccentricity. If ellipsoid is omitted, the WGS84 ellipsoid (more % precisely, the value returned by DEFAULTELLIPSOID) is used. GEODPROJ % defines the projection and gives the restrictions on the allowed ranges % of the arguments. The inverse projection is given by TRANMERC_INV. % % GAM and K give metric properties of the projection at (LAT,LON); GAM is % the meridian convergence at the point and K is the scale. % % LAT0, LON0, LAT, LON, GAM are in degrees. The projected coordinates X, % Y are in meters (more precisely the units used for the equatorial % radius). K is dimensionless. % % This implementation of the projection is based on the series method % described in % % C. F. F. Karney, Transverse Mercator with an accuracy of a few % nanometers, J. Geodesy 85(8), 475-485 (Aug. 2011); % Addenda: http://geographiclib.sf.net/tm-addenda.html % % This extends the series given by Krueger (1912) to sixth order in the % flattening. This is a substantially better series than that used by % the MATLAB mapping toolbox. In particular the errors in the projection % are less than 5 nanometers withing 3900 km of the central meridian (and % less than 1 mm within 7600 km of the central meridian). The mapping % can be continued accurately over the poles to the opposite meridian. % % This routine depends on the MATLAB File Exchange package "Geodesics on % an ellipsoid of revolution": % % http://www.mathworks.com/matlabcentral/fileexchange/39108 % % See also GEODPROJ, TRANMERC_INV, GEODDISTANCE, DEFAULTELLIPSOID. % Copyright (c) Charles Karney (2012) <[email protected]>. % % This file was distributed with GeographicLib 1.29. if nargin < 4, error('Too few input arguments'), end if nargin < 5, ellipsoid = defaultellipsoid; end try Z = lat0 + lon0 + lat + lon; Z = zeros(size(Z)); catch err error('lat0, lon0, lat, lon have incompatible sizes') end if length(ellipsoid(:)) ~= 2 error('ellipsoid must be a vector of size 2') end degree = pi/180; maxpow = 6; a = ellipsoid(1); f = ecc2flat(ellipsoid(2)); e2 = f * (2 - f); e2m = 1 - e2; cc = sqrt(e2m) * exp(e2 * atanhee(1, e2)); n = f / (2 -f); alp = alpf(n); b1 = (1 - f) * (A1m1f(n) + 1); a1 = b1 * a; lon = AngDiff(AngNormalize(lon0), AngNormalize(lon)); latsign = 1 - 2 * (lat < 0); lonsign = 1 - 2 * (lon < 0); lon = lon .* lonsign; lat = lat .* latsign; backside = lon > 90; latsign(backside & lat == 0) = -1; lon(backside) = 180 - lon(backside); phi = lat * degree; lam = lon * degree; c = max(0, cos(lam)); tau = tan(phi); taup = taupf(tau, e2); xip = atan2(taup, c); etap = asinh(sin(lam) ./ hypot(taup, c)); gam = atan(tan(lam) .* taup ./ hypot(1, taup)); k = sqrt(e2m + e2 * cos(phi).^2) .* hypot(1, tau) ./ hypot(taup, c); c = ~(lat ~= 90); if any(c) xip(c) = pi/2; etap(c) = 0; gam(c) = lam; k = cc; end c0 = cos(2 * xip); ch0 = cosh(2 * etap); s0 = sin(2 * xip); sh0 = sinh(2 * etap); ar = 2 * c0 .* ch0; ai = -2 * s0 .* sh0; j = maxpow; xi0 = Z; yr0 = Z; if mod(j, 2) xi0 = xi0 + alp(j); yr0 = yr0 + 2 * maxpow * alp(j); j = j - 1; end xi1 = Z; eta0 = Z; eta1 = Z; yi0 = Z; yr1 = Z; yi1 = Z; for j = j : -2 : 1 xi1 = ar .* xi0 - ai .* eta0 - xi1 + alp(j); eta1 = ai .* xi0 + ar .* eta0 - eta1; yr1 = ar .* yr0 - ai .* yi0 - yr1 + 2 * j * alp(j); yi1 = ai .* yr0 + ar .* yi0 - yi1; xi0 = ar .* xi1 - ai .* eta1 - xi0 + alp(j-1); eta0 = ai .* xi1 + ar .* eta1 - eta0; yr0 = ar .* yr1 - ai .* yi1 - yr0 + 2 * (j-1) * alp(j-1); yi0 = ai .* yr1 + ar .* yi1 - yi0; end ar = ar/2; ai = ai/2; yr1 = 1 - yr1 + ar .* yr0 - ai .* yi0; yi1 = - yi1 + ai .* yr0 + ar .* yi0; ar = s0 .* ch0; ai = c0 .* sh0; xi = xip + ar .* xi0 - ai .* eta0; eta = etap + ai .* xi0 + ar .* eta0; gam = gam - atan2(yi1, yr1); k = k .* (b1 * hypot(yr1, yi1)); gam = gam / degree; xi(backside) = pi - xi(backside); y = a1 * xi .* latsign; x = a1 * eta .* lonsign; gam(backside) = 180 - gam(backside); gam = gam .* latsign .* lonsign; if isscalar(lat0) && lat0 == 0 y0 = 0; else [sbet0, cbet0] = SinCosNorm((1-f) * sind(lat0), cosd(lat0)); y0 = a1 * (atan2(sbet0, cbet0) + ... SinCosSeries(true, sbet0, cbet0, C1f(n))); end y = y - y0; end function alp = alpf(n) alp = zeros(1,6); nx = n^2; alp(1) = n*(n*(n*(n*(n*(31564*n-66675)+34440)+47250)-100800)+ ... 75600)/151200; alp(2) = nx*(n*(n*((863232-1983433*n)*n+748608)-1161216)+524160)/ ... 1935360; nx = nx * n; alp(3) = nx*(n*(n*(670412*n+406647)-533952)+184464)/725760; nx = nx * n; alp(4) = nx*(n*(6601661*n-7732800)+2230245)/7257600; nx = nx * n; alp(5) = (3438171-13675556*n)*nx/7983360; nx = nx * n; alp(6) = 212378941*nx/319334400; end function taup = taupf(tau, e2) tau1 = hypot(1, tau); sig = sinh( e2 * atanhee(tau ./ tau1, e2) ); taup = hypot(1, sig) .* tau - sig .* tau1; overflow = 1/eps^2; c = ~(abs(tau) < overflow); taup(c) = tau(c); end
github
wvu-navLab/RobustGNSS-master
tranmerc_inv.m
.m
RobustGNSS-master/gtsam/gtsam/3rdparty/GeographicLib/matlab/tranmerc_inv.m
5,994
utf_8
3ccf6b37ca13daed68a0ae8f166151ce
function [lat, lon, gam, k] = tranmerc_inv(lat0, lon0, x, y, ellipsoid) %TRANMERC_INV Inverse transverse Mercator projection % % [LAT, LON] = TRANMERC_INV(LAT0, LON0, X, Y) % [LAT, LON, GAM, K] = TRANMERC_INV(LAT0, LON0, X, Y, ELLIPSOID) % % performs the inverse transverse Mercator projection of points (X,Y) to % (LAT,LON) using (LAT0,LON0) as the center of projection. These input % arguments can be scalars or arrays of equal size. The ELLIPSOID vector % is of the form [a, e], where a is the equatorial radius in meters, e is % the eccentricity. If ellipsoid is omitted, the WGS84 ellipsoid (more % precisely, the value returned by DEFAULTELLIPSOID) is used. GEODPROJ % defines the projection and gives the restrictions on the allowed ranges % of the arguments. The forward projection is given by TRANMERC_FWD. % % GAM and K give metric properties of the projection at (LAT,LON); GAM is % the meridian convergence at the point and K is the scale. % % LAT0, LON0, LAT, LON, GAM are in degrees. The projected coordinates X, % Y are in meters (more precisely the units used for the equatorial % radius). K is dimensionless. % % This implementation of the projection is based on the series method % described in % % C. F. F. Karney, Transverse Mercator with an accuracy of a few % nanometers, J. Geodesy 85(8), 475-485 (Aug. 2011); % Addenda: http://geographiclib.sf.net/tm-addenda.html % % This extends the series given by Krueger (1912) to sixth order in the % flattening. This is a substantially better series than that used by % the MATLAB mapping toolbox. In particular the errors in the projection % are less than 5 nanometers withing 3900 km of the central meridian (and % less than 1 mm within 7600 km of the central meridian). The mapping % can be continued accurately over the poles to the opposite meridian. % % This routine depends on the MATLAB File Exchange package "Geodesics on % an ellipsoid of revolution": % % http://www.mathworks.com/matlabcentral/fileexchange/39108 % % See also GEODPROJ, TRANMERC_FWD, GEODRECKON, DEFAULTELLIPSOID. % Copyright (c) Charles Karney (2012) <[email protected]>. % % This file was distributed with GeographicLib 1.29. if nargin < 4, error('Too few input arguments'), end if nargin < 5, ellipsoid = defaultellipsoid; end try Z = lat0 + lon0 + x + y; Z = zeros(size(Z)); catch err error('lat0, lon0, x, y have incompatible sizes') end if length(ellipsoid(:)) ~= 2 error('ellipsoid must be a vector of size 2') end degree = pi/180; maxpow = 6; a = ellipsoid(1); f = ecc2flat(ellipsoid(2)); e2 = f * (2 - f); e2m = 1 - e2; cc = sqrt(e2m) * exp(e2 * atanhee(1, e2)); n = f / (2 -f); bet = betf(n); b1 = (1 - f) * (A1m1f(n) + 1); a1 = b1 * a; if isscalar(lat0) && lat0 == 0 y0 = 0; else [sbet0, cbet0] = SinCosNorm((1-f) * sind(lat0), cosd(lat0)); y0 = a1 * (atan2(sbet0, cbet0) + ... SinCosSeries(true, sbet0, cbet0, C1f(n))); end y = y + y0; xi = y / a1; eta = x / a1; xisign = 1 - 2 * (xi < 0 ); etasign = 1 - 2 * (eta < 0 ); xi = xi .* xisign; eta = eta .* etasign; backside = xi > pi/2; xi(backside) = pi - xi(backside); c0 = cos(2 * xi); ch0 = cosh(2 * eta); s0 = sin(2 * xi); sh0 = sinh(2 * eta); ar = 2 * c0 .* ch0; ai = -2 * s0 .* sh0; j = maxpow; xip0 = Z; yr0 = Z; if mod(j, 2) xip0 = xip0 + bet(j); yr0 = yr0 - 2 * maxpow * bet(j); j = j - 1; end xip1 = Z; etap0 = Z; etap1 = Z; yi0 = Z; yr1 = Z; yi1 = Z; for j = j : -2 : 1 xip1 = ar .* xip0 - ai .* etap0 - xip1 - bet(j); etap1 = ai .* xip0 + ar .* etap0 - etap1; yr1 = ar .* yr0 - ai .* yi0 - yr1 - 2 * j * bet(j); yi1 = ai .* yr0 + ar .* yi0 - yi1; xip0 = ar .* xip1 - ai .* etap1 - xip0 - bet(j-1); etap0 = ai .* xip1 + ar .* etap1 - etap0; yr0 = ar .* yr1 - ai .* yi1 - yr0 - 2 * (j-1) * bet(j-1); yi0 = ai .* yr1 + ar .* yi1 - yi0; end ar = ar/2; ai = ai/2; yr1 = 1 - yr1 + ar .* yr0 - ai .* yi0; yi1 = - yi1 + ai .* yr0 + ar .* yi0; ar = s0 .* ch0; ai = c0 .* sh0; xip = xi + ar .* xip0 - ai .* etap0; etap = eta + ai .* xip0 + ar .* etap0; gam = atan2(yi1, yr1); k = b1 ./ hypot(yr1, yi1); s = sinh(etap); c = max(0, cos(xip)); r = hypot(s, c); lam = atan2(s, c); taup = sin(xip)./r; tau = tauf(taup, e2); phi = atan(tau); gam = gam + atan(tan(xip) .* tanh(etap)); c = r ~= 0; k(c) = k(c) .* sqrt(e2m + e2 * cos(phi(c)).^2) .* ... hypot(1, tau(c)) .* r(c); c = ~c; if any(c) phi(c) = pi/2; lam(c) = 0; k(c) = k(c) * cc; end lat = phi / degree .* xisign; lon = lam / degree; lon(backside) = 180 - lon(backside); lon = lon .* etasign; lon = AngNormalize(lon + AngNormalize(lon0)); gam = gam/degree; gam(backside) = 180 - gam(backside); gam = gam .* xisign .* etasign; end function bet = betf(n) bet = zeros(1,6); nx = n^2; bet(1) = n*(n*(n*(n*(n*(384796*n-382725)-6720)+932400)-1612800)+ ... 1209600)/2419200; bet(2) = nx*(n*(n*((1695744-1118711*n)*n-1174656)+258048)+80640)/ ... 3870720; nx = nx * n; bet(3) = nx*(n*(n*(22276*n-16929)-15984)+12852)/362880; nx = nx * n; bet(4) = nx*((-830251*n-158400)*n+197865)/7257600; nx = nx * n; bet(5) = (453717-435388*n)*nx/15966720; nx = nx * n; bet(6) = 20648693*nx/638668800; end function tau = tauf(taup, e2) overflow = 1/eps^2; tol = 0.1 * sqrt(eps); numit = 5; e2m = 1 - e2; tau = taup / e2m; stol = tol * max(1, abs(taup)); g = ~(abs(taup) < overflow); tau(g) = taup(g); g = ~g; for i = 1 : numit if ~any(g), break, end tau1 = hypot(1, tau); sig = sinh(e2 * atanhee( tau ./ tau1, e2 ) ); taupa = hypot(1, sig) .* tau - sig .* tau1; dtau = (taup - taupa) .* (1 + e2m .* tau.^2) ./ ... (e2m * tau1 .* hypot(1, taupa)); tau(g) = tau(g) + dtau(g); g = g & abs(dtau) >= stol; end end
github
jhalakpatel/AI-ML-DL-master
submit.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex2/ex2/submit.m
1,605
utf_8
9b63d386e9bd7bcca66b1a3d2fa37579
function submit() addpath('./lib'); conf.assignmentSlug = 'logistic-regression'; conf.itemName = 'Logistic Regression'; conf.partArrays = { ... { ... '1', ... { 'sigmoid.m' }, ... 'Sigmoid Function', ... }, ... { ... '2', ... { 'costFunction.m' }, ... 'Logistic Regression Cost', ... }, ... { ... '3', ... { 'costFunction.m' }, ... 'Logistic Regression Gradient', ... }, ... { ... '4', ... { 'predict.m' }, ... 'Predict', ... }, ... { ... '5', ... { 'costFunctionReg.m' }, ... 'Regularized Logistic Regression Cost', ... }, ... { ... '6', ... { 'costFunctionReg.m' }, ... 'Regularized Logistic Regression Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))']; y = sin(X(:,1) + X(:,2)) > 0; if partId == '1' out = sprintf('%0.5f ', sigmoid(X)); elseif partId == '2' out = sprintf('%0.5f ', costFunction([0.25 0.5 -0.5]', X, y)); elseif partId == '3' [cost, grad] = costFunction([0.25 0.5 -0.5]', X, y); out = sprintf('%0.5f ', grad); elseif partId == '4' out = sprintf('%0.5f ', predict([0.25 0.5 -0.5]', X)); elseif partId == '5' out = sprintf('%0.5f ', costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1)); elseif partId == '6' [cost, grad] = costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1); out = sprintf('%0.5f ', grad); end end
github
jhalakpatel/AI-ML-DL-master
submitWithConfiguration.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex2/ex2/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
jhalakpatel/AI-ML-DL-master
savejson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex2/ex2/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
jhalakpatel/AI-ML-DL-master
loadjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex2/ex2/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
jhalakpatel/AI-ML-DL-master
loadubjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex2/ex2/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
jhalakpatel/AI-ML-DL-master
saveubjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex2/ex2/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
jhalakpatel/AI-ML-DL-master
submit.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex4/ex4/submit.m
1,635
utf_8
ae9c236c78f9b5b09db8fbc2052990fc
function submit() addpath('./lib'); conf.assignmentSlug = 'neural-network-learning'; conf.itemName = 'Neural Networks Learning'; conf.partArrays = { ... { ... '1', ... { 'nnCostFunction.m' }, ... 'Feedforward and Cost Function', ... }, ... { ... '2', ... { 'nnCostFunction.m' }, ... 'Regularized Cost Function', ... }, ... { ... '3', ... { 'sigmoidGradient.m' }, ... 'Sigmoid Gradient', ... }, ... { ... '4', ... { 'nnCostFunction.m' }, ... 'Neural Network Gradient (Backpropagation)', ... }, ... { ... '5', ... { 'nnCostFunction.m' }, ... 'Regularized Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = reshape(3 * sin(1:1:30), 3, 10); Xm = reshape(sin(1:32), 16, 2) / 5; ym = 1 + mod(1:16,4)'; t1 = sin(reshape(1:2:24, 4, 3)); t2 = cos(reshape(1:2:40, 4, 5)); t = [t1(:) ; t2(:)]; if partId == '1' [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0); out = sprintf('%0.5f ', J); elseif partId == '2' [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5); out = sprintf('%0.5f ', J); elseif partId == '3' out = sprintf('%0.5f ', sigmoidGradient(X)); elseif partId == '4' [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; elseif partId == '5' [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; end end
github
jhalakpatel/AI-ML-DL-master
submitWithConfiguration.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex4/ex4/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
jhalakpatel/AI-ML-DL-master
savejson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex4/ex4/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
jhalakpatel/AI-ML-DL-master
loadjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex4/ex4/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
jhalakpatel/AI-ML-DL-master
loadubjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex4/ex4/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
jhalakpatel/AI-ML-DL-master
saveubjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex4/ex4/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
jhalakpatel/AI-ML-DL-master
submit.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex6/ex6/submit.m
1,318
utf_8
bfa0b4ffb8a7854d8e84276e91818107
function submit() addpath('./lib'); conf.assignmentSlug = 'support-vector-machines'; conf.itemName = 'Support Vector Machines'; conf.partArrays = { ... { ... '1', ... { 'gaussianKernel.m' }, ... 'Gaussian Kernel', ... }, ... { ... '2', ... { 'dataset3Params.m' }, ... 'Parameters (C, sigma) for Dataset 3', ... }, ... { ... '3', ... { 'processEmail.m' }, ... 'Email Preprocessing', ... }, ... { ... '4', ... { 'emailFeatures.m' }, ... 'Email Feature Extraction', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases x1 = sin(1:10)'; x2 = cos(1:10)'; ec = 'the quick brown fox jumped over the lazy dog'; wi = 1 + abs(round(x1 * 1863)); wi = [wi ; wi]; if partId == '1' sim = gaussianKernel(x1, x2, 2); out = sprintf('%0.5f ', sim); elseif partId == '2' load('ex6data3.mat'); [C, sigma] = dataset3Params(X, y, Xval, yval); out = sprintf('%0.5f ', C); out = [out sprintf('%0.5f ', sigma)]; elseif partId == '3' word_indices = processEmail(ec); out = sprintf('%d ', word_indices); elseif partId == '4' x = emailFeatures(wi); out = sprintf('%d ', x); end end
github
jhalakpatel/AI-ML-DL-master
porterStemmer.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex6/ex6/porterStemmer.m
9,902
utf_8
7ed5acd925808fde342fc72bd62ebc4d
function stem = porterStemmer(inString) % Applies the Porter Stemming algorithm as presented in the following % paper: % Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14, % no. 3, pp 130-137 % Original code modeled after the C version provided at: % http://www.tartarus.org/~martin/PorterStemmer/c.txt % The main part of the stemming algorithm starts here. b is an array of % characters, holding the word to be stemmed. The letters are in b[k0], % b[k0+1] ending at b[k]. In fact k0 = 1 in this demo program (since % matlab begins indexing by 1 instead of 0). k is readjusted downwards as % the stemming progresses. Zero termination is not in fact used in the % algorithm. % To call this function, use the string to be stemmed as the input % argument. This function returns the stemmed word as a string. % Lower-case string inString = lower(inString); global j; b = inString; k = length(b); k0 = 1; j = k; % With this if statement, strings of length 1 or 2 don't go through the % stemming process. Remove this conditional to match the published % algorithm. stem = b; if k > 2 % Output displays per step are commented out. %disp(sprintf('Word to stem: %s', b)); x = step1ab(b, k, k0); %disp(sprintf('Steps 1A and B yield: %s', x{1})); x = step1c(x{1}, x{2}, k0); %disp(sprintf('Step 1C yields: %s', x{1})); x = step2(x{1}, x{2}, k0); %disp(sprintf('Step 2 yields: %s', x{1})); x = step3(x{1}, x{2}, k0); %disp(sprintf('Step 3 yields: %s', x{1})); x = step4(x{1}, x{2}, k0); %disp(sprintf('Step 4 yields: %s', x{1})); x = step5(x{1}, x{2}, k0); %disp(sprintf('Step 5 yields: %s', x{1})); stem = x{1}; end % cons(j) is TRUE <=> b[j] is a consonant. function c = cons(i, b, k0) c = true; switch(b(i)) case {'a', 'e', 'i', 'o', 'u'} c = false; case 'y' if i == k0 c = true; else c = ~cons(i - 1, b, k0); end end % mseq() measures the number of consonant sequences between k0 and j. If % c is a consonant sequence and v a vowel sequence, and <..> indicates % arbitrary presence, % <c><v> gives 0 % <c>vc<v> gives 1 % <c>vcvc<v> gives 2 % <c>vcvcvc<v> gives 3 % .... function n = measure(b, k0) global j; n = 0; i = k0; while true if i > j return end if ~cons(i, b, k0) break; end i = i + 1; end i = i + 1; while true while true if i > j return end if cons(i, b, k0) break; end i = i + 1; end i = i + 1; n = n + 1; while true if i > j return end if ~cons(i, b, k0) break; end i = i + 1; end i = i + 1; end % vowelinstem() is TRUE <=> k0,...j contains a vowel function vis = vowelinstem(b, k0) global j; for i = k0:j, if ~cons(i, b, k0) vis = true; return end end vis = false; %doublec(i) is TRUE <=> i,(i-1) contain a double consonant. function dc = doublec(i, b, k0) if i < k0+1 dc = false; return end if b(i) ~= b(i-1) dc = false; return end dc = cons(i, b, k0); % cvc(j) is TRUE <=> j-2,j-1,j has the form consonant - vowel - consonant % and also if the second c is not w,x or y. this is used when trying to % restore an e at the end of a short word. e.g. % % cav(e), lov(e), hop(e), crim(e), but % snow, box, tray. function c1 = cvc(i, b, k0) if ((i < (k0+2)) || ~cons(i, b, k0) || cons(i-1, b, k0) || ~cons(i-2, b, k0)) c1 = false; else if (b(i) == 'w' || b(i) == 'x' || b(i) == 'y') c1 = false; return end c1 = true; end % ends(s) is TRUE <=> k0,...k ends with the string s. function s = ends(str, b, k) global j; if (str(length(str)) ~= b(k)) s = false; return end % tiny speed-up if (length(str) > k) s = false; return end if strcmp(b(k-length(str)+1:k), str) s = true; j = k - length(str); return else s = false; end % setto(s) sets (j+1),...k to the characters in the string s, readjusting % k accordingly. function so = setto(s, b, k) global j; for i = j+1:(j+length(s)) b(i) = s(i-j); end if k > j+length(s) b((j+length(s)+1):k) = ''; end k = length(b); so = {b, k}; % rs(s) is used further down. % [Note: possible null/value for r if rs is called] function r = rs(str, b, k, k0) r = {b, k}; if measure(b, k0) > 0 r = setto(str, b, k); end % step1ab() gets rid of plurals and -ed or -ing. e.g. % caresses -> caress % ponies -> poni % ties -> ti % caress -> caress % cats -> cat % feed -> feed % agreed -> agree % disabled -> disable % matting -> mat % mating -> mate % meeting -> meet % milling -> mill % messing -> mess % meetings -> meet function s1ab = step1ab(b, k, k0) global j; if b(k) == 's' if ends('sses', b, k) k = k-2; elseif ends('ies', b, k) retVal = setto('i', b, k); b = retVal{1}; k = retVal{2}; elseif (b(k-1) ~= 's') k = k-1; end end if ends('eed', b, k) if measure(b, k0) > 0; k = k-1; end elseif (ends('ed', b, k) || ends('ing', b, k)) && vowelinstem(b, k0) k = j; retVal = {b, k}; if ends('at', b, k) retVal = setto('ate', b(k0:k), k); elseif ends('bl', b, k) retVal = setto('ble', b(k0:k), k); elseif ends('iz', b, k) retVal = setto('ize', b(k0:k), k); elseif doublec(k, b, k0) retVal = {b, k-1}; if b(retVal{2}) == 'l' || b(retVal{2}) == 's' || ... b(retVal{2}) == 'z' retVal = {retVal{1}, retVal{2}+1}; end elseif measure(b, k0) == 1 && cvc(k, b, k0) retVal = setto('e', b(k0:k), k); end k = retVal{2}; b = retVal{1}(k0:k); end j = k; s1ab = {b(k0:k), k}; % step1c() turns terminal y to i when there is another vowel in the stem. function s1c = step1c(b, k, k0) global j; if ends('y', b, k) && vowelinstem(b, k0) b(k) = 'i'; end j = k; s1c = {b, k}; % step2() maps double suffices to single ones. so -ization ( = -ize plus % -ation) maps to -ize etc. note that the string before the suffix must give % m() > 0. function s2 = step2(b, k, k0) global j; s2 = {b, k}; switch b(k-1) case {'a'} if ends('ational', b, k) s2 = rs('ate', b, k, k0); elseif ends('tional', b, k) s2 = rs('tion', b, k, k0); end; case {'c'} if ends('enci', b, k) s2 = rs('ence', b, k, k0); elseif ends('anci', b, k) s2 = rs('ance', b, k, k0); end; case {'e'} if ends('izer', b, k) s2 = rs('ize', b, k, k0); end; case {'l'} if ends('bli', b, k) s2 = rs('ble', b, k, k0); elseif ends('alli', b, k) s2 = rs('al', b, k, k0); elseif ends('entli', b, k) s2 = rs('ent', b, k, k0); elseif ends('eli', b, k) s2 = rs('e', b, k, k0); elseif ends('ousli', b, k) s2 = rs('ous', b, k, k0); end; case {'o'} if ends('ization', b, k) s2 = rs('ize', b, k, k0); elseif ends('ation', b, k) s2 = rs('ate', b, k, k0); elseif ends('ator', b, k) s2 = rs('ate', b, k, k0); end; case {'s'} if ends('alism', b, k) s2 = rs('al', b, k, k0); elseif ends('iveness', b, k) s2 = rs('ive', b, k, k0); elseif ends('fulness', b, k) s2 = rs('ful', b, k, k0); elseif ends('ousness', b, k) s2 = rs('ous', b, k, k0); end; case {'t'} if ends('aliti', b, k) s2 = rs('al', b, k, k0); elseif ends('iviti', b, k) s2 = rs('ive', b, k, k0); elseif ends('biliti', b, k) s2 = rs('ble', b, k, k0); end; case {'g'} if ends('logi', b, k) s2 = rs('log', b, k, k0); end; end j = s2{2}; % step3() deals with -ic-, -full, -ness etc. similar strategy to step2. function s3 = step3(b, k, k0) global j; s3 = {b, k}; switch b(k) case {'e'} if ends('icate', b, k) s3 = rs('ic', b, k, k0); elseif ends('ative', b, k) s3 = rs('', b, k, k0); elseif ends('alize', b, k) s3 = rs('al', b, k, k0); end; case {'i'} if ends('iciti', b, k) s3 = rs('ic', b, k, k0); end; case {'l'} if ends('ical', b, k) s3 = rs('ic', b, k, k0); elseif ends('ful', b, k) s3 = rs('', b, k, k0); end; case {'s'} if ends('ness', b, k) s3 = rs('', b, k, k0); end; end j = s3{2}; % step4() takes off -ant, -ence etc., in context <c>vcvc<v>. function s4 = step4(b, k, k0) global j; switch b(k-1) case {'a'} if ends('al', b, k) end; case {'c'} if ends('ance', b, k) elseif ends('ence', b, k) end; case {'e'} if ends('er', b, k) end; case {'i'} if ends('ic', b, k) end; case {'l'} if ends('able', b, k) elseif ends('ible', b, k) end; case {'n'} if ends('ant', b, k) elseif ends('ement', b, k) elseif ends('ment', b, k) elseif ends('ent', b, k) end; case {'o'} if ends('ion', b, k) if j == 0 elseif ~(strcmp(b(j),'s') || strcmp(b(j),'t')) j = k; end elseif ends('ou', b, k) end; case {'s'} if ends('ism', b, k) end; case {'t'} if ends('ate', b, k) elseif ends('iti', b, k) end; case {'u'} if ends('ous', b, k) end; case {'v'} if ends('ive', b, k) end; case {'z'} if ends('ize', b, k) end; end if measure(b, k0) > 1 s4 = {b(k0:j), j}; else s4 = {b(k0:k), k}; end % step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. function s5 = step5(b, k, k0) global j; j = k; if b(k) == 'e' a = measure(b, k0); if (a > 1) || ((a == 1) && ~cvc(k-1, b, k0)) k = k-1; end end if (b(k) == 'l') && doublec(k, b, k0) && (measure(b, k0) > 1) k = k-1; end s5 = {b(k0:k), k};
github
jhalakpatel/AI-ML-DL-master
submitWithConfiguration.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex6/ex6/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
jhalakpatel/AI-ML-DL-master
savejson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex6/ex6/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
jhalakpatel/AI-ML-DL-master
loadjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex6/ex6/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
jhalakpatel/AI-ML-DL-master
loadubjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex6/ex6/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
jhalakpatel/AI-ML-DL-master
saveubjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex6/ex6/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
jhalakpatel/AI-ML-DL-master
submit.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex5/ex5/submit.m
1,765
utf_8
b1804fe5854d9744dca981d250eda251
function submit() addpath('./lib'); conf.assignmentSlug = 'regularized-linear-regression-and-bias-variance'; conf.itemName = 'Regularized Linear Regression and Bias/Variance'; conf.partArrays = { ... { ... '1', ... { 'linearRegCostFunction.m' }, ... 'Regularized Linear Regression Cost Function', ... }, ... { ... '2', ... { 'linearRegCostFunction.m' }, ... 'Regularized Linear Regression Gradient', ... }, ... { ... '3', ... { 'learningCurve.m' }, ... 'Learning Curve', ... }, ... { ... '4', ... { 'polyFeatures.m' }, ... 'Polynomial Feature Mapping', ... }, ... { ... '5', ... { 'validationCurve.m' }, ... 'Validation Curve', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = [ones(10,1) sin(1:1.5:15)' cos(1:1.5:15)']; y = sin(1:3:30)'; Xval = [ones(10,1) sin(0:1.5:14)' cos(0:1.5:14)']; yval = sin(1:10)'; if partId == '1' [J] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5); out = sprintf('%0.5f ', J); elseif partId == '2' [J, grad] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5); out = sprintf('%0.5f ', grad); elseif partId == '3' [error_train, error_val] = ... learningCurve(X, y, Xval, yval, 1); out = sprintf('%0.5f ', [error_train(:); error_val(:)]); elseif partId == '4' [X_poly] = polyFeatures(X(2,:)', 8); out = sprintf('%0.5f ', X_poly); elseif partId == '5' [lambda_vec, error_train, error_val] = ... validationCurve(X, y, Xval, yval); out = sprintf('%0.5f ', ... [lambda_vec(:); error_train(:); error_val(:)]); end end
github
jhalakpatel/AI-ML-DL-master
submitWithConfiguration.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex5/ex5/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
jhalakpatel/AI-ML-DL-master
savejson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex5/ex5/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
jhalakpatel/AI-ML-DL-master
loadjson.m
.m
AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex5/ex5/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end