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
oiwic/QOS-master
tracking.m
.m
QOS-master/qos/+uix/tracking.m
5,760
utf_8
8b7417c20b8797c89c9253973d4c9f49
function varargout = tracking( varargin ) %tracking Track anonymized usage data % % tracking(p,v,id) tracks usage to the property p for the product version % v and identifier id. No personally identifiable information is tracked. % % r = tracking(...) returns the server response r, for debugging purposes. % % tracking('on') turns tracking on. tracking('off') turns tracking off. % tracking('query') returns the tracking state. % tracking('spoof') sets the tracking settings -- domain, language, % client, MATLAB version, operating system version -- to spoof values. % tracking('reset') sets the tracking settings to normal values. % % [t,s] = tracking('query') returns the tracking state t and settings s. % Copyright 2016 The MathWorks, Inc. % $Revision: 1262 $ $Date: 2016-02-25 01:13:37 +0000 (Thu, 25 Feb 2016) $ persistent STATE USERNAME DOMAIN LANGUAGE CLIENT MATLAB OS if isempty( STATE ) STATE = getpref( 'Tracking', 'State', 'on' ); if strcmp( STATE, 'snooze' ) % deprecated setpref( 'Tracking', 'State', 'on' ) STATE = 'on'; end if ispref( 'Tracking', 'Date' ) % deprecated rmpref( 'Tracking', 'Date' ) end USERNAME = getenv( 'USERNAME' ); reset() end % initialize switch nargin case 1 switch varargin{1} case {'on','off'} STATE = varargin{1}; setpref( 'Tracking', 'State', varargin{1} ) % persist case 'spoof' spoof() case 'reset' reset() case 'query' varargout{1} = STATE; varargout{2} = query(); otherwise error( 'tracking:InvalidArgument', ... 'Valid options are ''on'', ''off'' and ''query''.' ) end case 3 switch nargout case 0 if strcmp( STATE, 'off' ), return, end uri = 'https://www.google-analytics.com/collect'; track( uri, varargin{:} ); case 1 uri = 'https://www.google-analytics.com/debug/collect'; varargout{1} = track( uri, varargin{:} ); otherwise nargoutchk( 0, 1 ) end otherwise narginchk( 3, 3 ) end % switch function reset() %reset Set normal settings DOMAIN = lower( getenv( 'USERDOMAIN' ) ); LANGUAGE = char( java.util.Locale.getDefault() ); CLIENT = getpref( 'Tracking', 'Client', uuid() ); MATLAB = matlab(); OS = os(); end % reset function spoof() %spoof Set spoof settings DOMAIN = randomDomain(); LANGUAGE = randomLanguage(); CLIENT = randomClient(); MATLAB = randomMatlab(); OS = randomOs(); end % spoof function s = query() %query Return settings s.Username = USERNAME; s.Domain = DOMAIN; s.Language = LANGUAGE; s.Client = CLIENT; s.Matlab = MATLAB; s.Os = OS; end % query function varargout = track( uri, p, v, s ) %track Do tracking a = sprintf( '%s/%s (%s)', MATLAB, v, OS ); if isdeployed() ds = 'deployed'; elseif strcmp( DOMAIN, 'mathworks' ) ds = DOMAIN; else ds = 'unknown'; end pv = {'v', '1', 'tid', p, 'ua', escape( a ), 'ul', LANGUAGE, ... 'cid', CLIENT, 'ht', 'pageview', ... 'dp', sprintf( '/%s', s ), 'ds', ds}; [varargout{1:nargout}] = urlread( uri, 'Post', pv ); end % track end % tracking function s = randomDomain() %randomDomain Random domain string switch randi( 4 ) case 1 s = 'mathworks'; otherwise s = hash( uuid() ); end end % randomDomain function s = randomLanguage() %randomLanguage Random language string lo = java.util.Locale.getAvailableLocales(); s = char( lo(randi( numel( lo ) )) ); end % randomLanguage function s = randomClient() %randomClient Random client identifier s = uuid(); end % randomClient function s = matlab() %matlab MATLAB version string v = ver( 'MATLAB' ); s = v.Release; s(s=='('|s==')') = []; end % matlab function s = randomMatlab() %randomMatlab Random MATLAB version string releases = {'R2014b' 'R2015a' 'R2015b' 'R2016a' 'R2016b'}; s = releases{randi( numel( releases ) )}; end % randomMatlab function s = os() %os Operating system string if ispc() s = sprintf( 'Windows NT %s', ... char( java.lang.System.getProperty( 'os.version' ) ) ); elseif isunix() s = 'Linux x86_64'; elseif ismac() s = sprintf( 'Macintosh; Intel OS X %s', ... strrep( char( java.lang.System.getProperty( 'os.version' ) ), ' ', '_' ) ); else s = 'unknown'; end end % os function s = randomOs() %randomOs Random operating system string switch randi( 3 ) case 1 versions = [5.1 5.2 6 6.1 6.2 6.3 10]; s = sprintf( 'Windows NT %.1f', ... versions(randi( numel( versions ) )) ); case 2 s = 'Linux x86_64'; case 3 s = sprintf( 'Macintosh; Intel OS X 10_%d', ... randi( [10 12] ) ); end end % randomOs function s = escape( s ) %escape Escape string s = char( java.net.URLEncoder.encode( s, 'UTF-8' ) ); end % escape function h = hash( s ) %hash Hash string % % See also: rptgen.hash persistent MD5 if isempty( MD5 ) MD5 = java.security.MessageDigest.getInstance( 'MD5' ); end MD5.update( uint8( s(:) ) ); h = typecast( MD5.digest, 'uint8' ); h = dec2hex( h )'; h = lower( h(:) )'; end % hash function s = uuid() %uuid Unique identifier s = char( java.util.UUID.randomUUID() ); end % uuid
github
oiwic/QOS-master
Text.m
.m
QOS-master/qos/+uix/Text.m
14,906
utf_8
76ee07c6fdddfe7c9dac8afc63ba2af5
classdef Text < matlab.mixin.SetGet %uix.Text Text control % % t = uix.Text(p1,v1,p2,v2,...) constructs a text control and sets % parameter p1 to value v1, etc. % % A text control adds functionality to a uicontrol of Style text: % * Set VerticalAlignment to 'top', 'middle' or 'bottom' % * Fire a Callback when the user clicks on the text % % See also: uicontrol % Copyright 2009-2015 The MathWorks, Inc. % $Revision: 1165 $ $Date: 2015-12-06 03:09:17 -0500 (Sun, 06 Dec 2015) $ properties( Dependent ) BackgroundColor end properties( Dependent, SetAccess = private ) BeingDeleted end properties( Dependent ) Callback DeleteFcn Enable end properties( Dependent, SetAccess = private ) Extent end properties( Dependent ) FontAngle FontName FontSize FontUnits FontWeight ForegroundColor HandleVisibility HorizontalAlignment Parent Position String Tag TooltipString end properties( Dependent, SetAccess = private ) Type end properties( Dependent ) UIContextMenu Units UserData VerticalAlignment Visible end properties( Access = private ) Container % container Checkbox % checkbox, used for label Screen % text, used for covering checkbox VerticalAlignment_ = 'top' % backing for VerticalAlignment Dirty = false % flag FigureObserver % observer FigureListener % listener end properties( Constant, Access = private ) Margin = checkBoxLabelOffset() % checkbox size end methods function obj = Text( varargin ) %uix.Text Text control % % t = uix.Text(p1,v1,p2,v2,...) constructs a text control and % sets parameter p1 to value v1, etc. % Create graphics container = uicontainer( 'Parent', [], ... 'Units', get( 0, 'DefaultUicontrolUnits' ), ... 'Position', get( 0, 'DefaultUicontrolPosition' ), ... 'SizeChangedFcn', @obj.onResized ); checkbox = uicontrol( 'Parent', container, ... 'HandleVisibility', 'off', ... 'Style', 'checkbox', 'Units', 'pixels', ... 'HorizontalAlignment', 'center', ... 'Enable', 'inactive' ); screen = uicontrol( 'Parent', container, ... 'HandleVisibility', 'off', ... 'Style', 'text', 'Units', 'pixels' ); % Create observers and listeners figureObserver = uix.FigureObserver( container ); figureListener = event.listener( figureObserver, ... 'FigureChanged', @obj.onFigureChanged ); % Store properties obj.Container = container; obj.Checkbox = checkbox; obj.Screen = screen; obj.FigureObserver = figureObserver; obj.FigureListener = figureListener; % Set properties if nargin > 0 try assert( rem( nargin, 2 ) == 0, 'uix:InvalidArgument', ... 'Parameters and values must be provided in pairs.' ) set( obj, varargin{:} ) catch e delete( obj ) e.throwAsCaller() end end end % constructor function delete( obj ) %delete Destructor delete( obj.Container ) end % destructor end % structors methods function value = get.BackgroundColor( obj ) value = obj.Checkbox.BackgroundColor; end % get.BackgroundColor function set.BackgroundColor( obj, value ) obj.Container.BackgroundColor = value; obj.Checkbox.BackgroundColor = value; obj.Screen.BackgroundColor = value; end % set.BackgroundColor function value = get.BeingDeleted( obj ) value = obj.Checkbox.BeingDeleted; end % get.BeingDeleted function value = get.Callback( obj ) value = obj.Checkbox.Callback; end % get.Callback function set.Callback( obj, value ) obj.Checkbox.Callback = value; end % set.Callback function value = get.DeleteFcn( obj ) value = obj.Checkbox.DeleteFcn; end % get.DeleteFcn function set.DeleteFcn( obj, value ) obj.Checkbox.DeleteFcn = value; end % set.DeleteFcn function value = get.Enable( obj ) value = obj.Checkbox.Enable; end % get.Enable function set.Enable( obj, value ) obj.Checkbox.Enable = value; end % set.Enable function value = get.Extent( obj ) value = obj.Checkbox.Extent; end % get.Extent function value = get.FontAngle( obj ) value = obj.Checkbox.FontAngle; end % get.FontAngle function set.FontAngle( obj, value ) % Set obj.Checkbox.FontAngle = value; % Mark as dirty obj.setDirty() end % set.FontAngle function value = get.FontName( obj ) value = obj.Checkbox.FontName; end % get.FontName function set.FontName( obj, value ) % Set obj.Checkbox.FontName = value; % Mark as dirty obj.setDirty() end % set.FontName function value = get.FontSize( obj ) value = obj.Checkbox.FontSize; end % get.FontSize function set.FontSize( obj, value ) % Set obj.Checkbox.FontSize = value; % Mark as dirty obj.setDirty() end % set.FontSize function value = get.FontUnits( obj ) value = obj.Checkbox.FontUnits; end % get.FontUnits function set.FontUnits( obj, value ) obj.Checkbox.FontUnits = value; end % set.FontUnits function value = get.FontWeight( obj ) value = obj.Checkbox.FontWeight; end % get.FontWeight function set.FontWeight( obj, value ) % Set obj.Checkbox.FontWeight = value; % Mark as dirty obj.setDirty() end % set.FontWeight function value = get.ForegroundColor( obj ) value = obj.Checkbox.ForegroundColor; end % get.ForegroundColor function set.ForegroundColor( obj, value ) obj.Checkbox.ForegroundColor = value; end % set.ForegroundColor function value = get.HandleVisibility( obj ) value = obj.Container.HandleVisibility; end % get.HandleVisibility function set.HandleVisibility( obj, value ) obj.Container.HandleVisibility = value; end % set.HandleVisibility function value = get.HorizontalAlignment( obj ) value = obj.Checkbox.HorizontalAlignment; end % get.HorizontalAlignment function set.HorizontalAlignment( obj, value ) % Set obj.Checkbox.HorizontalAlignment = value; % Mark as dirty obj.setDirty() end % set.HorizontalAlignment function value = get.Parent( obj ) value = obj.Container.Parent; end % get.Parent function set.Parent( obj, value ) obj.Container.Parent = value; end % set.Parent function value = get.Position( obj ) value = obj.Container.Position; end % get.Position function set.Position( obj, value ) obj.Container.Position = value; end % set.Position function value = get.String( obj ) value = obj.Checkbox.String; end % get.String function set.String( obj, value ) % Set obj.Checkbox.String = value; % Mark as dirty obj.setDirty() end % set.String function value = get.Tag( obj ) value = obj.Checkbox.Tag; end % get.Tag function set.Tag( obj, value ) obj.Checkbox.Tag = value; end % set.Tag function value = get.TooltipString( obj ) value = obj.Checkbox.TooltipString; end % get.TooltipString function set.TooltipString( obj, value ) obj.Checkbox.TooltipString = value; end % set.TooltipString function value = get.Type( obj ) value = obj.Checkbox.Type; end % get.Type function value = get.UIContextMenu( obj ) value = obj.Checkbox.UIContextMenu; end % get.UIContextMenu function set.UIContextMenu( obj, value ) obj.Checkbox.UIContextMenu = value; end % set.UIContextMenu function value = get.Units( obj ) value = obj.Container.Units; end % get.Units function set.Units( obj, value ) obj.Container.Units = value; end % set.Units function value = get.UserData( obj ) value = obj.Checkbox.UserData; end % get.UserData function set.UserData( obj, value ) obj.Checkbox.UserData = value; end % set.UserData function value = get.VerticalAlignment( obj ) value = obj.VerticalAlignment_; end % get.VerticalAlignment function set.VerticalAlignment( obj, value ) % Check assert( ischar( value ) && ... any( strcmp( value, {'top','middle','bottom'} ) ), ... 'uix:InvalidPropertyValue', ... 'Property ''VerticalAlignment'' must be ''top'', ''middle'' or ''bottom''.' ) % Set obj.VerticalAlignment_ = value; % Mark as dirty obj.setDirty() end % set.VerticalAlignment function value = get.Visible( obj ) value = obj.Container.Visible; end % get.Visible function set.Visible( obj, value ) obj.Container.Visible = value; end % set.Visible end % accessors methods( Access = private ) function onResized( obj, ~, ~ ) %onResized Event handler % Rooted, so redraw obj.redraw() end % onResized function onFigureChanged( obj, ~, eventData ) % If rooted, redraw if isempty( eventData.OldFigure ) && ... ~isempty( eventData.NewFigure ) && obj.Dirty obj.redraw() end end % onFigureChanged end % event handlers methods( Access = private ) function setDirty( obj ) %setDirty Mark as dirty % % t.setDirty() marks the text control t as dirty. If the text % control is rooted then it is redrawn immediately. If not % then the redraw is queued for when it is next rooted. if isempty( obj.FigureObserver.Figure ) obj.Dirty = true; % set flag else obj.Dirty = false; % unset flag obj.redraw() % redraw end end % setDirty function redraw( obj ) %redraw Redraw % % t.redraw() redraws the text control t. Note that this % requires the text control to be rooted. Methods should % request redraws using setDirty, rather than calling redraw % directly. c = obj.Container; b = obj.Checkbox; s = obj.Screen; bo = hgconvertunits( ancestor( obj, 'figure' ), ... [0 0 1 1], 'normalized', 'pixels', c ); % bounds m = obj.Margin; e = b.Extent; switch b.HorizontalAlignment case 'left' x = 1 - m; case 'center' x = 1 + bo(3)/2 - e(3)/2 - m; case 'right' x = 1 + bo(3) - e(3) - m; end w = e(3) + m; switch obj.VerticalAlignment_ case 'top' y = 1 + bo(4) - e(4); case 'middle' y = 1 + bo(4)/2 - e(4)/2; case 'bottom' y = 1; end h = e(4); b.Position = [x y w h]; s.Position = [x y m h]; end % redraw end % helpers end % classdef function o = checkBoxLabelOffset() %checkBoxLabelOffset Horizontal offset to checkbox label if verLessThan( 'MATLAB', '8.6' ) % R2015b o = 18; else o = 16; end end % margin
github
oiwic/QOS-master
loadIcon.m
.m
QOS-master/qos/+uix/loadIcon.m
3,127
utf_8
f8f5bf086b84150ff304ff497a22a246
function cdata = loadIcon( filename, bgcol ) %loadIcon Load an icon and set the transparent color % % cdata = uix.loadIcon(filename) loads the icon from the specified % filename. For PNG files with transparency, the transparent pixels are % set to NaN. For other files, pixels that are pure green are set to % transparent (i.e., "green screen"). The resulting cdata is an RGB % double array. % % cdata = uix.loadIcon(filename,bgcol) tries to merge the color data with % the specified background colour bgcol. Fully transparent pixels are % still set to NaN, but partially transparent pixels are merged with the % background. % % See also: imread % Copyright 2009-2015 The MathWorks, Inc. % $Revision: 1256 $ $Date: 2016-02-24 17:30:18 +0000 (Wed, 24 Feb 2016) $ % Check inputs narginchk( 1, 2 ) if nargin < 2 bgcol = get( 0, 'DefaultUIControlBackgroundColor' ); end % First try normally thisDir = fileparts( mfilename( 'fullpath' ) ); iconDir = fullfile( thisDir, 'Resources' ); if exist( filename, 'file' ) [cdata, map, alpha] = imread( filename ); elseif exist( fullfile( iconDir, filename ), 'file' ) [cdata, map, alpha] = imread( fullfile( iconDir, filename ) ); else error( 'uix:FileNotFound', 'Cannot open file ''%s''.', filename ) end % Convert indexed images to RGB if ~isempty( map ) cdata = ind2rgb( cdata, map ); end % Convert to double before applying transparency cdata = convertToDouble( cdata ); % Handle transparency [rows, cols, ~] = size( cdata ); if ~isempty( alpha ) % Transparency specified alpha = convertToDouble( alpha ); f = find( alpha==0 ); if ~isempty( f ) cdata(f) = NaN; cdata(f + rows*cols) = NaN; cdata(f + 2*rows*cols) = NaN; end % Now blend partial alphas f = find( alpha(:)>0 & alpha(:)<1 ); if ~isempty(f) cdata(f) = cdata(f).*alpha(f) + bgcol(1)*(1-alpha(f)); cdata(f + rows*cols) = cdata(f + rows*cols).*alpha(f) + bgcol(2)*(1-alpha(f)); cdata(f + 2*rows*cols) = cdata(f + 2*rows*cols).*alpha(f) + bgcol(3)*(1-alpha(f)); end else % Do a "green screen", treating anything pure-green as transparent f = find( cdata(:,:,1)==0 & cdata(:,:,2)==1 & cdata(:,:,3)==0 ); cdata(f) = NaN; cdata(f + rows*cols) = NaN; cdata(f + 2*rows*cols) = NaN; end end % uix.loadIcon % ------------------------------------------------------------------------- function cdata = convertToDouble( cdata ) %convertToDouble Convert image data to double in the range [0,1] % % cdata = convertToDouble(cData) switch lower( class( cdata ) ) case 'double' % do nothing case 'single' cdata = double( cdata ); case 'uint8' cdata = double( cdata ) / 255; case 'uint16' cdata = double( cdata ) / 65535; case 'int8' cdata = ( double( cdata ) + 128 ) / 255; case 'int16' cdata = ( double( cdata ) + 32768 ) / 65535; otherwise error( 'uix:InvalidArgument', ... 'Image data of type ''%s'' is not supported.', class( cdata ) ) end end % convertToDouble
github
oiwic/QOS-master
ChildObserver.m
.m
QOS-master/qos/+uix/ChildObserver.m
8,831
utf_8
d8bd8928f6e84a50d8060fa72735e107
classdef ( Hidden, Sealed ) ChildObserver < handle %uix.ChildObserver Child observer % % co = uix.ChildObserver(o) creates a child observer for the graphics % object o. A child observer raises events when objects are added to % and removed from the property Children of o. % % See also: uix.Node % Copyright 2009-2015 The MathWorks, Inc. % $Revision: 1310 $ $Date: 2016-06-28 13:34:38 +0100 (Tue, 28 Jun 2016) $ properties( Access = private ) Root % root node end events( NotifyAccess = private ) ChildAdded % child added ChildRemoved % child removed end methods function obj = ChildObserver( oRoot ) %uix.ChildObserver Child observer % % co = uix.ChildObserver(o) creates a child observer for the % graphics object o. A child observer raises events when % objects are added to and removed from the property Children % of o. % Check assert( iscontent( oRoot ) && ... isequal( size( oRoot ), [1 1] ), 'uix.InvalidArgument', ... 'Object must be a graphics object.' ) % Create root node nRoot = uix.Node( oRoot ); childAddedListener = event.listener( oRoot, ... 'ObjectChildAdded', ... @(~,e)obj.addChild(nRoot,e.Child) ); childAddedListener.Recursive = true; nRoot.addprop( 'ChildAddedListener' ); nRoot.ChildAddedListener = childAddedListener; childRemovedListener = event.listener( oRoot, ... 'ObjectChildRemoved', ... @(~,e)obj.removeChild(nRoot,e.Child) ); childRemovedListener.Recursive = true; nRoot.addprop( 'ChildRemovedListener' ); nRoot.ChildRemovedListener = childRemovedListener; % Add children oChildren = hgGetTrueChildren( oRoot ); for ii = 1:numel( oChildren ) obj.addChild( nRoot, oChildren(ii) ) end % Store properties obj.Root = nRoot; end % constructor end % structors methods( Access = private ) function addChild( obj, nParent, oChild ) %addChild Add child object to parent node % % co.addChild(np,oc) adds the child object oc to the parent % node np, either as part of construction of the child % observer co, or in response to an ObjectChildAdded event on % an object of interest to co. This may lead to ChildAdded % events being raised on co. % Create child node nChild = uix.Node( oChild ); nParent.addChild( nChild ) if iscontent( oChild ) % Add Internal PreSet property listener internalPreSetListener = event.proplistener( oChild, ... findprop( oChild, 'Internal' ), 'PreSet', ... @(~,~)obj.preSetInternal(nChild) ); nChild.addprop( 'InternalPreSetListener' ); nChild.InternalPreSetListener = internalPreSetListener; % Add Internal PostSet property listener internalPostSetListener = event.proplistener( oChild, ... findprop( oChild, 'Internal' ), 'PostSet', ... @(~,~)obj.postSetInternal(nChild) ); nChild.addprop( 'InternalPostSetListener' ); nChild.InternalPostSetListener = internalPostSetListener; else % Add ObjectChildAdded listener childAddedListener = event.listener( oChild, ... 'ObjectChildAdded', ... @(~,e)obj.addChild(nChild,e.Child) ); nChild.addprop( 'ChildAddedListener' ); nChild.ChildAddedListener = childAddedListener; % Add ObjectChildRemoved listener childRemovedListener = event.listener( oChild, ... 'ObjectChildRemoved', ... @(~,e)obj.removeChild(nChild,e.Child) ); nChild.addprop( 'ChildRemovedListener' ); nChild.ChildRemovedListener = childRemovedListener; end % Raise ChildAdded event if iscontent( oChild ) && oChild.Internal == false notify( obj, 'ChildAdded', uix.ChildEvent( oChild ) ) end % Add grandchildren if ~iscontent( oChild ) oGrandchildren = hgGetTrueChildren( oChild ); for ii = 1:numel( oGrandchildren ) obj.addChild( nChild, oGrandchildren(ii) ) end end end % addChild function removeChild( obj, nParent, oChild ) %removeChild Remove child object from parent node % % co.removeChild(np,oc) removes the child object oc from the % parent node np, in response to an ObjectChildRemoved event % on an object of interest to co. This may lead to % ChildRemoved events being raised on co. % Get child node nChildren = nParent.Children; tf = oChild == [nChildren.Object]; nChild = nChildren(tf); % Raise ChildRemoved event(s) notifyChildRemoved( nChild ) % Delete child node delete( nChild ) function notifyChildRemoved( nc ) % Process child nodes ngc = nc.Children; for ii = 1:numel( ngc ) notifyChildRemoved( ngc(ii) ) end % Process this node oc = nc.Object; if iscontent( oc ) && oc.Internal == false notify( obj, 'ChildRemoved', uix.ChildEvent( oc ) ) end end % notifyChildRemoved end % removeChild function preSetInternal( ~, nChild ) %preSetInternal Perform property PreSet tasks % % co.preSetInternal(n) caches the previous value of the % property Internal of the object referenced by the node n, to % enable PostSet tasks to identify whether the value changed. % This is necessary since Internal AbortSet is false. oldInternal = nChild.Object.Internal; nChild.addprop( 'OldInternal' ); nChild.OldInternal = oldInternal; end % preSetInternal function postSetInternal( obj, nChild ) %postSetInternal Perform property PostSet tasks % % co.postSetInternal(n) raises a ChildAdded or ChildRemoved % event on the child observer co in response to a change of % the value of the property Internal of the object referenced % by the node n. % Retrieve old and new values oChild = nChild.Object; newInternal = oChild.Internal; oldInternal = nChild.OldInternal; % Clean up node delete( findprop( nChild, 'OldInternal' ) ) % Raise event switch newInternal case oldInternal % no change % no event case true % false to true notify( obj, 'ChildRemoved', uix.ChildEvent( oChild ) ) case false % true to false notify( obj, 'ChildAdded', uix.ChildEvent( oChild ) ) end end % postSetInternal end % event handlers end % classdef function tf = iscontent( o ) %iscontent True for graphics that can be Contents (and can be Children) % % uix.ChildObserver needs to determine which objects can be Contents, % which is equivalent to can be Children if HandleVisibility is 'on' and % Internal is false. Prior to R2016a, this condition could be checked % using isgraphics. From R2016a, isgraphics returns true for a wider % range of objects, including some that can never by Contents, e.g., % JavaCanvas. Therefore this function checks whether an object is of type % matlab.graphics.internal.GraphicsBaseFunctions, which is what isgraphics % did prior to R2016a. tf = isa( o, 'matlab.graphics.internal.GraphicsBaseFunctions' ) &&... isprop( o, 'Position' ); end % iscontent
github
oiwic/QOS-master
Empty.m
.m
QOS-master/qos/+uix/Empty.m
2,628
utf_8
3f36c752763a9a98d04ad7f56d5df829
function obj = Empty( varargin ) %uix.Empty Create an empty space % % obj = uix.Empty() creates an empty space that can be used to add gaps % between elements in layouts. % % obj = uix.Empty(param,value,...) also sets one or more property % values. % % See the <a href="matlab:doc uix.Empty">documentation</a> for more detail and the list of properties. % % Examples: % >> f = figure(); % >> box = uix.HBox( 'Parent', f ); % >> uicontrol( 'Parent', box, 'Background', 'r' ) % >> uix.Empty( 'Parent', box ) % >> uicontrol( 'Parent', box, 'Background', 'b' ) % Copyright 2009-2015 The MathWorks, Inc. % $Revision: 919 $ $Date: 2014-06-03 11:05:38 +0100 (Tue, 03 Jun 2014) $ % Create uicontainer obj = matlab.ui.container.internal.UIContainer( 'Tag', 'empty', varargin{:} ); % Create property for Parent listener p = addprop( obj, 'ParentListener' ); p.Hidden = true; % Create Parent listener obj.ParentListener = event.proplistener( obj, ... findprop( obj, 'Parent' ), 'PostSet', @(~,~)onParentChanged(obj) ); % Create property for Parent color listener p = addprop( obj, 'ParentColorListener' ); p.Hidden = true; % Initialize color and listener updateColor( obj ) updateListener( obj ) end % uix.Empty function onParentChanged( obj ) %onParentColorChanged Event handler % Update color and listener updateColor( obj ) updateListener( obj ) end % onParentChanged function onParentColorChanged( obj ) %onParentColorChanged Event handler % Update color updateColor( obj ) end % onParentColorChanged function name = getColorProperty( obj ) %getColorProperty Get color property names = {'Color','BackgroundColor'}; % possible names for ii = 1:numel( names ) % loop over possible names name = names{ii}; if isprop( obj, name ) return end end error( 'Cannot find color property for %s.', class( obj ) ) end % getColorProperty function updateColor( obj ) %updateColor Set uicontainer BackgroundColor to match Parent parent = obj.Parent; if isempty( parent ), return, end property = getColorProperty( parent ); color = parent.( property ); try obj.BackgroundColor = color; catch e warning( e.identifier, e.message ) % rethrow as warning end end % updateColor function updateListener( obj ) %updateListener Create listener to parent color property parent = obj.Parent; if isempty( parent ) obj.ParentColorListener = []; else property = getColorProperty( parent ); obj.ParentColorListener = event.proplistener( parent, ... findprop( parent, property ), 'PostSet', ... @(~,~)onParentColorChanged(obj) ); end end % updateListener
github
oiwic/QOS-master
resetQSettings.m
.m
QOS-master/qos/+sqc/+util/resetQSettings.m
4,227
utf_8
125a7f5a751a9af780ad012d7496cad6
function resetQSettings() % Copyright 2017 Yulin Wu, University of Science and Technology of China % [email protected]/[email protected] choice = questdlg('Reset all qubit settings?','Reset all qubit settings?',... 'Yes','No','No'); if isempty(choice) || strcmp(choice, 'No') return; end qubits = []; try S = qes.qSettings.GetInstance(); catch throw(MException('QOS_resetQSettings:qSettingsNotCreated',... 'qSettings not created: create the qSettings object, set user and select session first.')); end s = S.loadSSettings(); if isempty(s) return; end fnames = fieldnames(s); num_fields = numel(fnames); for ii = 1:num_fields if ismember(fnames{ii},{'public','data_path'}) ||... ~isstruct(s.(fnames{ii})) continue; end qs = s.(fnames{ii}); if ~isfield(qs,'type') || ~strcmp(qs.type,'qubit') continue; end % doTheReset(fnames{ii}); try doTheReset(fnames{ii}); catch end end end function doTheReset(qName) % todo: fail when one key value is empty import sqc.util.setQSettings; setQSettings('f01',6e9,qName); setQSettings('f02',11.5e9,qName); setQSettings('g_I_ln',0,qName); setQSettings('g_X_amp','',qName); setQSettings('g_X2m_amp','',qName); setQSettings('g_X2p_amp','',qName); setQSettings('g_X4m_amp','',qName); setQSettings('g_X4p_amp','',qName); setQSettings('g_XY_4m_amp','',qName); setQSettings('g_XY_4p_amp','',qName); setQSettings('g_XY_ln','',qName); setQSettings('g_XY_phaseOffset',0,qName); setQSettings('g_XY2_ln','',qName); setQSettings('g_XY4_ln','',qName); setQSettings('g_XY12_amp','',qName); setQSettings('g_XY12_ln','',qName); setQSettings('g_Y_amp','',qName); setQSettings('g_Y2m_amp','',qName); setQSettings('g_Y2p_amp','',qName); setQSettings('g_Y4m_amp','',qName); setQSettings('g_Y4p_amp','',qName); setQSettings('g_Z_amp','',qName); setQSettings('g_Z_z_ln','',qName); setQSettings('g_Z2_z_ln','',qName); setQSettings('g_Z2m_z_amp','',qName); setQSettings('g_Z2p_z_amp','',qName); setQSettings('notes','',qName); setQSettings('qr_xy_dragAlpha',0,qName); setQSettings('qr_xy_dragPulse',true,qName); setQSettings('qr_xy_fc','',qName); setQSettings('qr_xy_uSrcPower',0,qName); setQSettings('qr_z_amp2f01','',qName); setQSettings('qr_z_amp2f02','',qName); setQSettings('r_amp','',qName); setQSettings('r_avg',500,qName); setQSettings('r_fc','',qName); setQSettings('r_fr','',qName); setQSettings('r_freq','',qName); setQSettings('r_jpa','',qName); setQSettings('r_jpa_biasAmp',0,qName); setQSettings('r_jpa_delay',0,qName); setQSettings('r_jpa_longer',0,qName); setQSettings('r_jpa_pumpAmp','',qName); setQSettings('r_jpa_pumpFreq','',qName); setQSettings('r_jpa_pumpPower','',qName); setQSettings('r_ln','',qName); setQSettings('r_truncatePts',[0,0],qName); setQSettings('r_uSrcPower',0,qName); setQSettings('r_iq2prob_center0',0,qName); setQSettings('r_iq2prob_center1',0,qName); setQSettings('r_iq2prob_center2',0,qName); setQSettings('r_iq2prob_fidelity',[1,1],qName); setQSettings('r_iq2prob_intrinsic',true,qName); setQSettings('spc_biasRise',1,qName); setQSettings('spc_driveAmp','',qName); setQSettings('spc_driveLn','',qName); setQSettings('spc_driveRise',1,qName); setQSettings('spc_sbFreq','',qName); setQSettings('syncDelay_r',[0,0],qName); setQSettings('syncDelay_xy',[0,0],qName); setQSettings('syncDelay_z',0,qName); setQSettings('t_rrDipFWHM_est','',qName); setQSettings('t_spcFWHM_est','',qName); setQSettings('t_zAmp2freqFreqSrchRng','',qName); setQSettings('t_zAmp2freqFreqStep','',qName); setQSettings('zdc_amp',0,qName); setQSettings('zdc_amp2f01','',qName); setQSettings('zdc_amp2f02','',qName); setQSettings('zdc_amp2fFreqRng','',qName); setQSettings('zdc_ampCorrection','',qName); setQSettings('zdc_settlingTime',0,qName); setQSettings('zpls_amp2f01Df','',qName); setQSettings('zpls_amp2f02Df','',qName); setQSettings('zpls_amp2fFreqRng','',qName); setQSettings('T1','',qName); setQSettings('T2','',qName); end
github
oiwic/QOS-master
PlotCPB.m
.m
QOS-master/qos/+sqc/+simulation/+ctx/PlotCPB.m
6,347
utf_8
c889d2ae188b78ea47467f205c52eaf3
% plots the lowest energy levels and the % average charge of a Cooper Pair Box (CPB), both single junction % CPB and split CPB. % A function call plots two figures, one is the energy levels and % and the other is the average charge. The calculated data is % saved to the current directory thus a later function call with % the same parameters can skip the calculation procedure. % Single Junction CPB: % PlotCPB(Ec,Ej,'s'); PlotCPB(Ec,Ej,'s',N); % PlotCPB(Ec,Ej,'s',N,NgLim); PlotCPB(Ec,Ej,'s',N,NgLim,nP); % Split CPB: % PlotCPB(Ec,Ej); PlotCPB(Ec,Ej,dEj); % PlotCPB(Ec,Ej,dEj,N); PlotCPB(Ec,Ej,dEj,N,NgLim); % PlotCPB(Ec,Ej,dEj,N,NgLim,phiLim); % PlotCPB(Ec,Ej,dEj,N,NgLim,phiLim,nP); % Ec=(2e)^2/C_\sigma, the Cooper Pair Coulomb energy; % Ej, Josephson Energy for single junction CPB, % Ej=Ej1+Ej2 for split CPB; % 's' could be any string, [single Junction CPB] % dEj=Ej1-Ej2 [split CPB]; % N, plot N energy level(s). % NgLim, phiLim define plotting range for Ng and \delta, % Ng=CgVg/2e is the charge bias, \detta=2*\pi*FluxBias/FluxQuantum % is the phase bias [single Junction CPB]; % nP, for single junction CPB: calculate 50 points to plot the % energy level curve(s), for split CPB: calculate 50*50 points to % plot the energy level surface(s); % dEj,NgLim,phiLim,nP,N are not neccesary in the function call, if % not specified, their default values will be assigned to them. % Example: % single junction CPB: PlotCPB(1,0.5,'s'); % PlotCPB(1,0.5,'s',4); % PlotCPB(1,0.5,'s',4,[-0.21 1.25],200); % split CPB with no asymmetry: PlotCPB(1,1); % split CPB with asymmetry: PlotCPB(1,1,0.1), dEj=0.05; % PlotCPB(1,1,0.1,3). % PlotCPB(1,1,0.1,3,[-0.21 1.5],[-0.21 1.5],60). % Author: Yulin Wu % Date: 2009/7/14 % Email: [email protected] function PlotCPB(Ec,Ej,varargin) dEj=0; % By default,assume split CPB and No asymmetry, NgLim=[-0.25 1.25]; % ploting range: Ng, [-0.25 1.25], phiLim=[-1.25 1.25]*pi; % \delta, [-1.25*pi 1.25*pi], nP=50; % 50*50 points for each energy level surface and N=2; % plot 2 energy levels. if nargin<2 errot('Not enough input arguments !'); elseif nargin>7 || (ischar(dEj) && nargin>6) error('Too many input arguments !'); elseif nargin>2 dEj=varargin{1}; if nargin>3 N=varargin{2}; end if nargin>4 NgLim=varargin{3}; end if nargin>5 phiLim=varargin{4}*pi; end if nargin>6 nP=varargin{5}; end if NgLim(2)<=NgLim(1) || phiLim(2)<=phiLim(1) || nP <3 || N>20 || N<2 || (~ischar(dEj) && nP>500) error('Bad input argument value !'); end end tmp=size(dir('Output')); if tmp(1)==0 || ~isdir('Output') % If folder Output do not exit, make one. mkdir('Output'); end if ~ischar(dEj) % split CPB phi=linspace(phiLim(1),phiLim(2),nP); OutputDataName=['Output\sCPB-Ec' num2str(Ec) 'Ej' num2str(Ej) 'dEj' num2str(dEj) 'NgLim' num2str(NgLim(1)) '-' num2str(NgLim(2)) 'deltaLim' num2str(phiLim(1)/pi) 'pi-' num2str(phiLim(2)/pi) 'pi_' num2str(N) '-' num2str(nP) '.mat']; else % CPB nP=500; % By default, calculate 500 points for the energy curve of single junction CPB. OutputDataName=['Output\CPB-Ec' num2str(Ec) 'Ej' num2str(Ej) 'NgLim' num2str(NgLim(1)) '-' num2str(NgLim(2)) '_' num2str(N) '-' num2str(nP) '.mat']; end Ng=linspace(NgLim(1),NgLim(2),nP); if size(dir(OutputDataName),1)==0 % Check if the data already exits. EnergyLevel=cell(1,N); for ii=1:nP if ischar(dEj) % CPB [EL, EigV]=CPBEL(Ec,Ej,Ng(ii),0); tmp1=size(EigV,1); for kk=1:N EnergyLevel{kk}(ii)=EL(kk); AverCharge{kk}(ii)=0; for ll=1:tmp1 AverCharge{kk}(ii)=AverCharge{kk}(ii)+(abs(EigV(ll,kk)))^2*(ll-1-(tmp1(1)-1)/2); end end else % split CPB for jj=1:nP [EL EigV]=CPBEL(Ec,Ej,Ng(ii),phi(jj),dEj); tmp1=size(EigV,1); for kk=1:N EnergyLevel{kk}(jj,ii)=EL(kk); AverCharge{kk}(jj,ii)=0; for ll=1:tmp1 AverCharge{kk}(jj,ii)=AverCharge{kk}(jj,ii)+(abs(EigV(ll,kk)))^2*(ll-1-(tmp1(1)-1)/2); end end end end end save(OutputDataName,'EnergyLevel','AverCharge'); else load(OutputDataName); end fg=int32(1e5*rand()); figure(fg); for ii=1:N if ischar(dEj) % CPB plot(Ng,EnergyLevel{ii}/Ec); else % split CPB surf(Ng,phi/pi,EnergyLevel{ii}/Ec); end hold on; end xlim([Ng(1),Ng(nP)]); if ~ischar(dEj) % split CPB ylim([phi(1)/pi,phi(nP)/pi]); end xlabel('$N_g$','interpreter','latex','Fontsize',16); if ischar(dEj) % CPB ylabel('$\frac{E}{E_c}$','interpreter','latex','Fontsize',16); title(['$E_c: ' num2str(Ec) '\quad E_{J}: ' num2str(Ej) '$'],'interpreter','latex','Fontsize',16); else % split CPB ylabel('$\delta (\pi)$','interpreter','latex','Fontsize',16); zlabel('$\frac{E}{E_c}$','interpreter','latex','Fontsize',16); title(['$E_c: ' num2str(Ec) '\quad E_{J1}+E_{J2}: ' num2str(Ej) '\quad E_{J1}-E_{J2}: ' num2str(dEj) '$'],'interpreter','latex','Fontsize',16); box on; end figure(fg+1); for ii=1:N if ischar(dEj) % CPB plot(Ng,AverCharge{ii}); else % split CPB surf(Ng,phi/pi,AverCharge{ii}); end hold on; end xlim([Ng(1),Ng(nP)]); if ~ischar(dEj) % split CPB ylim([phi(1)/pi,phi(nP)/pi]); end xlabel('$N_g$','interpreter','latex','Fontsize',16); if ischar(dEj) % CPB ylabel('$<N>$','interpreter','latex','Fontsize',16); title(['$E_c: ' num2str(Ec) '\quad E_{J}: ' num2str(Ej) '$'],'interpreter','latex','Fontsize',16); else % split CPB ylabel('$\delta (\pi)$','interpreter','latex','Fontsize',16); zlabel('$<N>$','interpreter','latex','Fontsize',16); title(['$E_c: ' num2str(Ec) '\quad E_{J1}+E_{J2}: ' num2str(Ej) '\quad E_{J1}-E_{J2}: ' num2str(dEj) '$'],'interpreter','latex','Fontsize',16); box on; end
github
oiwic/QOS-master
CPBEL.m
.m
QOS-master/qos/+sqc/+simulation/+ctx/CPBEL.m
1,922
utf_8
8ad0bebc3de4f2910f7077866e708cd5
% CPBEL calculats the lowest energy levels of a % Cooper Pair Box (CPB), Transmon and Xmon. CPBEL returns the lowest M energy level % values as an array EL and eigen vectors as an Matrix (the nth % column is the eign vecotr of eign value EL(n)). % EnergyLevel=CPBEL(Ec,Ej,Ng); EnergyLevel=CPBEL(Ec,Ej,Ng,phi); % EnergyLevel=CPBEL(Ec,Ej,Ng,phi,dEj); % EnergyLevel=CPBEL(Ec,Ej,Ng,phi,dEj,M). % [EnergyLevel EignV]=CPBEL(Ec,Ej,Ng); % Ec=(2e)^2/(2C), the Cooper Pair Coulomb energy; % Ej, Josephson Energy, Ej=Ej1+Ej2 for split CPB(junction substituted by a SQUID); % Ng=CgVg/2e, Charge Bias, for Transmon and Xmon, energy level is charge % insensative, Ng can be any value. % dEj=Ej1-Ej2, dEj=0 for single junction CPB; % M, expand to 2*M+1 terms in the charge basis, M>=2 ! % phi,M are not neccesary in the function call, if not specified, % default values will be used. % Example: % EnergyLevel=CPBEL(1,0.5,0.5) % Author: Yulin Wu % Date: 2009/7/14 % Email: [email protected] function [EL, varargout]=CPBEL(Ec,Ej,Ng,varargin) % Hamiltonian % H = Ec*(N-Ng)^2 + Ej*cos(phi) phi=0; % By default,assume No flux bias (CPB or zero flux for split CPB), dEj=0; % No asymmetry, M=25; % and expand to 51 terms in the charge basis. if nargin == 2 % Transmon or Xmon, charge insensative Ng = 0; end if nargin>6 error('Too many input arguments !'); elseif nargout>2 error('Too many output arguments !'); elseif nargin>3 phi=varargin{1}; if nargin>4 dEj=varargin{2}; end if nargin>5 M=varargin{3}; if M<2 error('Bad input argument value !'); end end end H=zeros(2*M+1); for N=-M:M n=N+M+1; H(n,n)=Ec*(N-Ng)^2; if N<M H(n,n+1)=-(Ej*cos(phi/2)-1i*dEj*sin(phi/2))/2; H(n+1,n)=-(Ej*cos(phi/2)+1i*dEj*sin(phi/2))/2; end end [EigV, E]=eig(H); EL=E*ones(2*M+1,1); EL(M+1:2*M+1)=[]; EigV(:,M+1:2*M+1)=[]; varargout{1}=EigV(:,1:M);
github
oiwic/QOS-master
PlotCPBEL.m
.m
QOS-master/qos/+sqc/+simulation/+ctx/PlotCPBEL.m
5,014
utf_8
67d7e6933fc8fceab84b9dd2e5162fde
% This MATLAB function plots the lowest energy levels of a % Cooper Pair Box (CPB), both single junction CPB and split CPB. % A function call plots a figure of the energy levels and the % calculated data is saved to the current directory (a later % function call with the same parameters can thus skip the % calculation procedure). % Single Junction CPB: % PlotCPBEL(Ec,Ej,'s'); PlotCPBEL(Ec,Ej,'s',N); % PlotCPBEL(Ec,Ej,'s',N,NgLim); PlotCPBEL(Ec,Ej,'s',N,NgLim,nP); % Split CPB: % PlotCPBEL(Ec,Ej); PlotCPBEL(Ec,Ej,dEj); % PlotCPBEL(Ec,Ej,dEj,N); PlotCPBEL(Ec,Ej,dEj,N,NgLim); % PlotCPBEL(Ec,Ej,dEj,N,NgLim,phiLim); % PlotCPBEL(Ec,Ej,dEj,N,NgLim,phiLim,nP); % Ec=(2e)^2/C_\sigma, the Cooper Pair Coulomb energy; % Ej, Josephson Energy for single junction CPB, % Ej=Ej1+Ej2 for split CPB; % 's' could be any string. [single Junction CPB] % dEj=Ej1-Ej2 [split CPB]; % N, plot N energy level(s). % NgLim, phiLim define plotting range for Ng and \delta, % Ng=CgVg/2e is the charge bias, \detta=2*\pi*FluxBias/FluxQuantum % is the phase bias [single Junction CPB]; % nP, for single junction CPB: calculate 50 points to plot the % energy level curve(s), for split CPB: calculate 50*50 points to % plot the energy level surface(s); % dEj,NgLim,phiLim,nP,N are not neccesary in the function call, if % not specified, their default values will be assigned to them. % Example: % single junction CPB: PlotCPBEL(1,0.5,'s'); % PlotCPBEL(1,0.5,'s',4); % PlotCPBEL(1,0.5,'s',4,[-0.21 1.25],200); % split CPB no asymmetry: PlotCPBEL(1,1); % split CPB with asymmetry: PlotCPBEL(1,1,0.1), dEj=0.05; % PlotCPBEL(1,1,0.1,3). % PlotCPBEL(1,1,0.1,3,[-0.21 1.5],[-0.21 1.5],60). % Author: Yulin Wu % Date: 2009/7/14 % Email: [email protected] function PlotCPBEL(Ec,Ej,varargin) dEj=0; % By default,assume split CPB and No asymmetry, NgLim=[-0.25 1.25]; % ploting range: Ng, [-0.25 1.25], phiLim=[-1.25 1.25]*pi; % \delta, [-1.25*pi 1.25*pi], nP=50; % 50*50 points for each energy level surface and N=2; % plot 2 energy levels. if nargin<2 error('Not enough input arguments !'); elseif nargin>7 || (ischar(dEj) && nargin>6) error('Too many input arguments !'); elseif nargin>2 dEj=varargin{1}; if nargin>3 N=varargin{2}; end if nargin>4 NgLim=varargin{3}; end if nargin>5 if ischar(dEj) nP=varargin{4}; else phiLim=varargin{4}*pi; end end if nargin>6 nP=varargin{5}; end if NgLim(2)<=NgLim(1) || phiLim(2)<=phiLim(1) || nP <3 || N>20 || (~ischar(dEj) && nP>500) error('Bad input argument value !'); end end tmp=size(dir('Output')); if tmp(1)==0 || ~isdir('Output') % If folder Output do not exit, make one. mkdir('Output'); end if ~ischar(dEj) % split CPB phi=linspace(phiLim(1),phiLim(2),nP); OutputDataName=['Output\sCPBEL-Ec' num2str(Ec) 'Ej' num2str(Ej) 'dEj' num2str(dEj) 'NgLim' num2str(NgLim(1)) '-' num2str(NgLim(2)) 'deltaLim' num2str(phiLim(1)/pi) 'pi-' num2str(phiLim(2)/pi) 'pi_' num2str(N) '-' num2str(nP) '.mat']; else % CPB nP=500; % By default, calculate 500 points for the energy curve of single junction CPB. OutputDataName=['Output\CPBEL-Ec' num2str(Ec) 'Ej' num2str(Ej) 'NgLim' num2str(NgLim(1)) '-' num2str(NgLim(2)) '_' num2str(N) '-' num2str(nP) '.mat']; end Ng=linspace(NgLim(1),NgLim(2),nP); if size(dir(OutputDataName),1)==0 % Check if the data already exits. EnergyLevel=cell(1,N); for ii=1:nP if ischar(dEj) % CPB EL=CPBEL(Ec,Ej,Ng(ii),0); for kk=1:N EnergyLevel{kk}(ii)=EL(kk); end else % split CPB for jj=1:nP EL=CPBEL(Ec,Ej,Ng(ii),phi(jj),dEj); for kk=1:N EnergyLevel{kk}(jj,ii)=EL(kk); end end end end save(OutputDataName,'EnergyLevel'); else load(OutputDataName); end figure(int32(1e5*rand())); for ii=1:N if ischar(dEj) % CPB plot(Ng,EnergyLevel{ii}/Ec); else % split CPB surf(Ng,phi/pi,EnergyLevel{ii}/Ec); end hold on; end xlim([Ng(1),Ng(nP)]); if ~ischar(dEj) % split CPB ylim([phi(1)/pi,phi(nP)/pi]); end xlabel('$N_g$','interpreter','latex','Fontsize',16); if ischar(dEj) % CPB ylabel('$\frac{E}{E_c}$','interpreter','latex','Fontsize',16); title(['$E_c: ' num2str(Ec) '\quad E_{J}: ' num2str(Ej) '$'],'interpreter','latex','Fontsize',16); else % split CPB ylabel('$\delta (\pi)$','interpreter','latex','Fontsize',16); zlabel('$\frac{E}{E_c}$','interpreter','latex','Fontsize',16); title(['$E_c: ' num2str(Ec) '\quad E_{J1}+E_{J2}: ' num2str(Ej) '\quad E_{J1}-E_{J2}: ' num2str(dEj) '$'],'interpreter','latex','Fontsize',16); box on; end
github
oiwic/QOS-master
TCPBEL4.m
.m
QOS-master/qos/+sqc/+simulation/+ctx/+twoBits/TCPBEL4.m
899
utf_8
62987cbd6351801cd9f92d478ac5f94d
% TCPBEL4 calculates the eigen values and eigen states of two % capacitively coupled charge qubits by expanding to the basis: % { |00> |10> |01> |11> }. % See TCPBEL for detailed description. % Example: % EnergyLevel=TCPBEL(1,1,0.2,0.2,0.3,0.5,0.01); % Author: Yulin Wu % Date: 2009/8/14 % Email: [email protected] function [EL, varargout]=TCPBEL4(Ec1,Ec2,Em,Ej1,Ej2,Ng1,Ng2) if nargout>2 error('Too many output arguments !'); elseif nargin>7 error('Too many input arguments !'); end H=zeros(4); for n=1:4 N1=ceil(n/2)-1; N2=rem(n,2)-1; if N2 == -1 N2=1; end H(n,n)=Ec1*(N1-Ng1)^2+Ec2*(N2-Ng2)^2+Em*(N1-Ng1)*(N2-Ng2); % -Em*N1*N2; end for n1=1:2 n2=n1+2; H(n1,n2)=-Ej1/2; H(n2,n1)=-Ej1/2; end for n1=1:4 if mod(n1,2)~=0 n2=n1+1; H(n1,n2)=-Ej2/2; H(n2,n1)=-Ej2/2; end end [varargout{1} E]=eig(H); EL=E*ones(4,1);
github
oiwic/QOS-master
PlotTCPBELs.m
.m
QOS-master/qos/+sqc/+simulation/+ctx/+twoBits/PlotTCPBELs.m
4,156
utf_8
736aab4176f5dc5f2204ec8b4472f2a1
% PlotTCPBELs is a slice-plot version of PlotTCPBEL. % Author: Yulin Wu % Date: 2009/8/13 % Email: [email protected] function PlotTCPBELs(Ec1,Ec2,Em,Ej1,Ej2,varargin) NgLim=[0.25 0.8]; % Default ploting range: Ng, [-0.25 0.8], nP=400; % 400 points for each energy level and N=4; % plot 4 energy levels. if nargin<5 error('Not enough input arguments !'); elseif nargin>8 error('Too many input arguments !'); elseif nargin>5 NgLim=varargin{1}; if nargin>6 N=varargin{2}; if nargin>7 nP=varargin{3}; end end end if N>10 N=10; end Ng=linspace(NgLim(1),NgLim(2),nP); if size(dir('Output'),1)==0 || ~isdir('Output') % If folder Output do not exit, make one. mkdir('Output'); end OutputDataName=['Output/TCPBELs-Ec' num2str(Ec1) '_' num2str(Ec2) 'Em' num2str(Em) 'Ej' num2str(Ej1) '_' num2str(Ej2) 'NgLim' num2str(NgLim(1)) '-' num2str(NgLim(2)) 'nP' num2str(nP) '.mat']; tmp=size(dir(OutputDataName)); Flag=true; if tmp(1)~=0 % Check if the data already exits. for ii=1:1000 clc; disp('Data for the current parameters have already been calculated previously. '); disp('If this is not the case, Enter N or n to ignore the exist data.'); disp('======================================'); user_entry=input('Accept the exist data? Y/N [Y] ','s'); if isempty(user_entry) || user_entry=='Y' || user_entry=='y' load(OutputDataName); Flag=false; break; elseif user_entry=='N' || user_entry=='n' delete(OutputDataName); break; end end end if Flag==true % Flag==true : Previously caculated data for the current parameters do tic; % no exist or being ignored. EnergyLevel1=zeros(N,nP); for jj=1:nP EL=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng(1),Ng(jj)); EL(N+1:end)=[]; EnergyLevel1(:,jj)=EL; Time1=toc/60; Time2=Time1*3*(nP)/jj - Time1; clc; disp(['Time elapsed: ' num2str(Time1) ' min.']); disp(['Estimated time remaining: ' num2str(Time2) ' min.']); end EnergyLevel2=zeros(N,nP); for jj=1:nP EL=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng(jj),Ng(1)); EL(N+1:end)=[]; EnergyLevel2(:,jj)=EL; Time1=toc/60; Time2=Time1*3*(nP)/(jj+nP) - Time1; clc; disp(['Time elapsed: ' num2str(Time1) ' min.']); disp(['Estimated time remaining: ' num2str(Time2) ' min.']); end EnergyLevel3=zeros(N,nP); for jj=1:nP EL=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng(jj),Ng(jj)); EL(N+1:end)=[]; EnergyLevel3(:,jj)=EL; Time1=toc/60; Time2=Time1*3*nP/(jj+2*nP) - Time1; clc; disp(['Time elapsed: ' num2str(Time1) ' min.']); disp(['Estimated time remaining: ' num2str(Time2) ' min.']); end save(OutputDataName,'EnergyLevel1','EnergyLevel2','EnergyLevel3'); end figure(int32(1e5*rand())); for ii=1:N plot3(Ng(1)*ones(1,nP),Ng,EnergyLevel1(ii,:)/((Ec1+Ec2)/2)); hold on; plot3(Ng,Ng(1)*ones(1,nP),EnergyLevel2(ii,:)/((Ec1+Ec2)/2)); hold on; % plot3(Ng,Ng,EnergyLevel3(ii,:)/((Ec1+Ec2)/2)); % hold on; end grid on; xlim([Ng(1),Ng(nP)]); ylim([Ng(1),Ng(nP)]); xlabel('$N_{g1}$','interpreter','latex','Fontsize',16); ylabel('$$N_{g2}$','interpreter','latex','Fontsize',16); zlabel('$\frac{E}{(E_{c1}+E_{c2})/2}$','interpreter','latex','Fontsize',16); title(['$E_{c1}: ' num2str(Ec1) '\quad E_{c2}: ' num2str(Ec2) '\quad E_{m}: ' num2str(Em) '\quad E_{J1}: ' num2str(Ej1) '\quad E_{J2}: ' num2str(Ej2) '$'],'interpreter','latex','Fontsize',16); view(120,17); figure(int32(1e5*rand())); for ii=1:N plot(Ng,EnergyLevel3(ii,:)/((Ec1+Ec2)/2)); hold on; end grid on; xlim([Ng(1),Ng(nP)]); xlabel('$N_{g1}=N_{g2}$','interpreter','latex','Fontsize',16); ylabel('$\frac{E}{(E_{c1}+E_{c2})/2}$','interpreter','latex','Fontsize',16); title(['$E_{c1}: ' num2str(Ec1) '\quad E_{c2}: ' num2str(Ec2) '\quad E_{m}: ' num2str(Em) '\quad E_{J1}: ' num2str(Ej1) '\quad E_{J2}: ' num2str(Ej2) '$'],'interpreter','latex','Fontsize',16);
github
oiwic/QOS-master
PlotTCPBEL.m
.m
QOS-master/qos/+sqc/+simulation/+ctx/+twoBits/PlotTCPBEL.m
4,016
utf_8
533461691ff66e550d64e5afcbb86e82
% This MATLAB function plots the lowest energy levels of two % capacitively coupled Cooper Pair Boxes (CPBs). A function call % plots a figure of the energy levels. The calculated data is % saved to the directory $/Output (a later function call with the % same parameters can thus skip the calculation procedure). % Function call and Meaning of arguments: % Single Junction CPB: % PlotTCPBEL(Ec1,Ec2,Em,Ej1,Ej2); % PlotTCPBEL(Ec1,Ec2,Em,Ej1,Ej2,NgLim); % PlotTCPBEL(Ec1,Ec2,Em,Ej1,Ej2,NgLim,N); % PlotTCPBEL(Ec1,Ec2,Em,Ej1,Ej2,NgLim,N,nP); % Ec1=(2e)^2/C_{1\sigma}, Ec1=(2e)^2/C_{2\sigma}, the Cooper Pair % Coulomb energys of the two CPBs; % Em=4e^{2}Cm/(C_{1\sigma}C_{2\sigma}-C_{M}^{2}), the coupling % energy. Cm is the coupling capacitor; % Ej1, Ej2, the Josephson Energys; % NgLim defines plotting range for Ng1 and Ng2, Ng1=Cg1Vg1/2e, % Ng2=Cg2Vg2/2e, are the Charge Biases; % N, plot N energy level(s). % nP calculate nP*nP points to plot the energy level surface(s); % NgLim,N,nP are not neccesary in the function call, if % not specified, their default values will be assigned to them. % Example: % PlotTCPBEL(1,1,0.2,0.15,0.15); % PlotTCPBEL(1,1,0.2,0.15,0.15,[0 1]); % PlotTCPBEL(1,1,0.2,0.15,0.15,[0 1],5); % PlotTCPBEL(1,1,0.2,0.15,0.15,[0 1],5,30); % Author: Yulin Wu % Date: 2009/8/10 % Email: [email protected] function PlotTCPBEL(Ec1,Ec2,Em,Ej1,Ej2,varargin) NgLim=[0.25 0.8]; % Default ploting range: Ng, [-0.25 0.8], nP=50; % 50*50 points for each energy level surface and N=4; % plot 4 energy levels. if nargin<5 error('Not enough input arguments !'); elseif nargin>8 error('Too many input arguments !'); elseif nargin>5 NgLim=varargin{1}; if nargin>6 N=varargin{2}; if nargin>7 nP=varargin{3}; end end end if N>10 N=10; end tmp=size(dir('Output')); if tmp(1)==0 || ~isdir('Output') % If folder Output do not exit, make one. mkdir('Output'); end OutputDataName=['Output/TCPBEL-Ec' num2str(Ec1) '_' num2str(Ec2) 'Em' num2str(Em) 'Ej' num2str(Ej1) '_' num2str(Ej2) 'NgLim' num2str(NgLim(1)) '-' num2str(NgLim(2)) 'nP' num2str(nP) '.mat']; Ng1=linspace(NgLim(1),NgLim(2),nP); Ng2=Ng1; Flag=true; if size(dir(OutputDataName),1)~=0 % Check if the data already exits. for ii=1:1000 clc; disp('Data for the current parameters have already been calculated previously. '); disp('If this is not the case, press N or n to ignore the exist data.'); disp('======================================'); user_entry=input('Accept the exist data? Y/N [Y] ','s'); if isempty(user_entry) || user_entry=='Y' || user_entry=='y' load(OutputDataName); Flag=false; break; elseif user_entry=='N' || user_entry=='n' delete(OutputDataName); break; end end end if Flag==true % Flag==true : Previously caculated data for the current parameters do tic; % no exist or being ignored. EnergyLevel=cell(1,N); for ii=1:nP for jj=1:nP EL=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng1(ii),Ng2(jj)); for kk=1:N EnergyLevel{kk}(jj,ii)=EL(kk); end end Time1=toc/60; Time2=Time1*(nP)/ii - Time1; clc; disp(['Time elapsed: ' num2str(Time1) ' min.']); disp(['Estimated time remaining: ' num2str(Time2) ' min.']); end save(OutputDataName,'EnergyLevel'); end figure(int32(1e5*rand())); for ii=1:N surf(Ng1,Ng2,EnergyLevel{ii}/((Ec1+Ec2)/2)); hold on; end xlim([Ng1(1),Ng1(nP)]); ylim([Ng2(1),Ng2(nP)]); xlabel('$N_{g1}$','interpreter','latex','Fontsize',16); ylabel('$$N_{g2}$','interpreter','latex','Fontsize',16); zlabel('$\frac{E}{(E_{c1}+E_{c2})/2}$','interpreter','latex','Fontsize',16); title(['$E_{c1}: ' num2str(Ec1) '\quad E_{c2}: ' num2str(Ec2) '\quad E_{J1}: ' num2str(Ej1) '\quad E_{J2}: ' num2str(Ej2) '$'],'interpreter','latex','Fontsize',16);
github
oiwic/QOS-master
PlotTCPBELsP.m
.m
QOS-master/qos/+sqc/+simulation/+ctx/+twoBits/PlotTCPBELsP.m
3,675
utf_8
efa6473671483e49b50d1235e02dccfd
% PlotTCPBELsP is a parallel computing version of PlotTCPBELs. % make sure parallel computing enabled. % Author: Yulin Wu % Date: 2009/8/13 % Email: [email protected] function PlotTCPBELsP(Ec1,Ec2,Em,Ej1,Ej2,varargin) NgLim=[0.25 0.8]; % Default ploting range: Ng, [-0.25 0.8], nP=400; % 400 points for each energy level and N=4; % plot 4 energy levels. if nargin<5 error('Not enough input arguments !'); elseif nargin>8 error('Too many input arguments !'); elseif nargin>5 NgLim=varargin{1}; if nargin>6 N=varargin{2}; if nargin>7 nP=varargin{3}; end end end if N>10 N=10; end tmp=size(dir('Output')); if tmp(1)==0 || ~isdir('Output') % If folder Output do not exit, make one. mkdir('Output'); end OutputDataName=['Output/TCPBELs-Ec' num2str(Ec1) '_' num2str(Ec2) 'Em' num2str(Em) 'Ej' num2str(Ej1) '_' num2str(Ej2) 'NgLim' num2str(NgLim(1)) '-' num2str(NgLim(2)) 'nP' num2str(nP) '.mat']; Ng=linspace(NgLim(1),NgLim(2),nP); Ng0=Ng(1); Flag=true; if size(dir(OutputDataName),1)~=0 % Check if the data already exits. for ii=1:1000 clc; disp('Data for the current parameters have already been calculated previously. '); disp('If this is not the case, Enter N or n to ignore the exist data.'); disp('======================================'); user_entry=input('Accept the exist data? Y/N [Y] ','s'); if isempty(user_entry) || user_entry=='Y' || user_entry=='y' load(OutputDataName); Flag=false; break; elseif user_entry=='N' || user_entry=='n' delete(OutputDataName); break; end end end if Flag==true % Flag==true : Previously caculated data for the current parameters do tic; % no exist or being ignored. EnergyLevel1=zeros(N,nP); parfor jj=1:nP EL=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng0,Ng(jj)); EL(N+1:end)=[]; EnergyLevel1(:,jj)=EL; end EnergyLevel2=zeros(N,nP); parfor jj=1:nP EL=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng(jj),Ng0); EL(N+1:end)=[]; EnergyLevel2(:,jj)=EL; end EnergyLevel3=zeros(N,nP); parfor jj=1:nP EL=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng(jj),Ng(jj)); EL(N+1:end)=[]; EnergyLevel3(:,jj)=EL; end save(OutputDataName,'EnergyLevel1','EnergyLevel2','EnergyLevel3'); time = toc; disp(['Time consumed: ' num2str(time/60)]); end figure(int32(1e5*rand())); for ii=1:N plot3(Ng(1)*ones(1,nP),Ng,EnergyLevel1(ii,:)/((Ec1+Ec2)/2)); hold on; plot3(Ng,Ng(1)*ones(1,nP),EnergyLevel2(ii,:)/((Ec1+Ec2)/2)); hold on; % plot3(Ng,Ng,EnergyLevel3(ii,:)/((Ec1+Ec2)/2)); % hold on; end grid on; xlim([Ng(1),Ng(nP)]); ylim([Ng(1),Ng(nP)]); xlabel('$N_{g1}$','interpreter','latex','Fontsize',16); ylabel('$$N_{g2}$','interpreter','latex','Fontsize',16); zlabel('$\frac{E}{(E_{c1}+E_{c2})/2}$','interpreter','latex','Fontsize',16); title(['$E_{c1}: ' num2str(Ec1) '\quad E_{c2}: ' num2str(Ec2) '\quad E_{m}: ' num2str(Em) '\quad E_{J1}: ' num2str(Ej1) '\quad E_{J2}: ' num2str(Ej2) '$'],'interpreter','latex','Fontsize',16); view(120,17); figure(int32(1e5*rand())); for ii=1:N plot(Ng,EnergyLevel3(ii,:)/((Ec1+Ec2)/2)); hold on; end grid on; xlim([Ng(1),Ng(nP)]); xlabel('$N_{g1}=N_{g2}$','interpreter','latex','Fontsize',16); ylabel('$\frac{E}{(E_{c1}+E_{c2})/2}$','interpreter','latex','Fontsize',16); title(['$E_{c1}: ' num2str(Ec1) '\quad E_{c2}: ' num2str(Ec2) '\quad E_{m}: ' num2str(Em) '\quad E_{J1}: ' num2str(Ej1) '\quad E_{J2}: ' num2str(Ej2) '$'],'interpreter','latex','Fontsize',16);
github
oiwic/QOS-master
PlotTCPBEL4s.m
.m
QOS-master/qos/+sqc/+simulation/+ctx/+twoBits/PlotTCPBEL4s.m
2,077
utf_8
0337e8ae09b6839f6d54847d6fa82518
% PlotTCPBEL4s is a slice-plot version of PlotTCPBEL expand % to the basis { |00> |10> |01> |11> }. % Author: Yulin Wu % Date: 2009/8/14 % Email: [email protected] function PlotTCPBEL4s(Ec1,Ec2,Em,Ej1,Ej2,varargin) NgLim=[0.25 0.8]; % Default ploting range: Ng, [-0.25 0.8], nP=400; % 400 points for each energy level if nargin<5 error('Not enough input arguments !'); elseif nargin>6 error('Too many input arguments !'); elseif nargin>5 NgLim=varargin{1}; end Ng=linspace(NgLim(1),NgLim(2),nP); EnergyLevel1=zeros(4,nP); for jj=1:nP EL=TCPBEL4(Ec1,Ec2,Em,Ej1,Ej2,Ng(1),Ng(jj)); EnergyLevel1(:,jj)=EL; end EnergyLevel2=zeros(4,nP); for jj=1:nP EL=TCPBEL4(Ec1,Ec2,Em,Ej1,Ej2,Ng(jj),Ng(1)); EnergyLevel2(:,jj)=EL; end EnergyLevel3=zeros(4,nP); for jj=1:nP EL=TCPBEL4(Ec1,Ec2,Em,Ej1,Ej2,Ng(jj),Ng(jj)); EnergyLevel3(:,jj)=EL; end figure(int32(1e5*rand())); for ii=1:4 plot3(Ng(1)*ones(1,nP),Ng,EnergyLevel1(ii,:)/((Ec1+Ec2)/2)); hold on; plot3(Ng,Ng(1)*ones(1,nP),EnergyLevel2(ii,:)/((Ec1+Ec2)/2)); hold on; % plot3(Ng,Ng,EnergyLevel3(ii,:)/((Ec1+Ec2)/2)); % hold on; end grid on; xlim([Ng(1),Ng(nP)]); ylim([Ng(1),Ng(nP)]); xlabel('$N_{g1}$','interpreter','latex','Fontsize',16); ylabel('$$N_{g2}$','interpreter','latex','Fontsize',16); zlabel('$\frac{E}{(E_{c1}+E_{c2})/2}$','interpreter','latex','Fontsize',16); title(['$E_{c1}: ' num2str(Ec1) '\quad E_{c2}: ' num2str(Ec2) '\quad E_{m}: ' num2str(Em) '\quad E_{J1}: ' num2str(Ej1) '\quad E_{J2}: ' num2str(Ej2) '$'],'interpreter','latex','Fontsize',16); view(120,17); figure(int32(1e5*rand())); for ii=1:4 plot(Ng,EnergyLevel3(ii,:)/((Ec1+Ec2)/2)); hold on; end grid on; xlim([Ng(1),Ng(nP)]); xlabel('$N_{g1}=N_{g2}$','interpreter','latex','Fontsize',16); ylabel('$\frac{E}{(E_{c1}+E_{c2})/2}$','interpreter','latex','Fontsize',16); title(['$E_{c1}: ' num2str(Ec1) '\quad E_{c2}: ' num2str(Ec2) '\quad E_{m}: ' num2str(Em) '\quad E_{J1}: ' num2str(Ej1) '\quad E_{J2}: ' num2str(Ej2) '$'],'interpreter','latex','Fontsize',16);
github
oiwic/QOS-master
TCPBEL.m
.m
QOS-master/qos/+sqc/+simulation/+ctx/+twoBits/TCPBEL.m
1,964
utf_8
526a2eb30f37b91ac11654472ea07e45
% This MATLAB function calculats the lowest energy levels of two % capacitively coupled Cooper Pair Boxes (CPBs). TCPBEL returns % the lowest M energy level values as an array EL an eigen vectors % as an Matrix (the nth column is the eign vecotr of eign value % EL(n)). % Function call and Meaning of arguments: % EnergyLevel=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng1,Ng2); % EnergyLevel=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng1,Ng2,M); % [EnergyLevel EignV]=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng1,Ng2); % Ec1=(2e)^2/C_{1\sigma}, Ec1=(2e)^2/C_{2\sigma}, the Cooper Pair % Coulomb energys of the two CPBs; % Ej1, Ej2, the Josephson Energys; % Em=4e^{2}Cm/(C_{1\sigma}C_{2\sigma}-C_{M}^{2}), the coupling % energy. Cm is the coupling capacitor; % Ng1=Cg1Vg1/2e, Ng2=Cg2Vg2/2e, the Charge Biases; % M, expand to (2*M+1)*(2*M+1) terms in the charge basis, M>=2 ! % M is not neccesary in the function call, if not specified, % the default value (10) will be assigned to M. % Example: % EnergyLevel=TCPBEL(1,1,0.2,0.2,0.3,0.5,0.01); % Author: Yulin Wu % Date: 2009/8/14 % Email: [email protected] function [EL, varargout]=TCPBEL(Ec1,Ec2,Em,Ej1,Ej2,Ng1,Ng2,varargin) M=10; % Expand to 21*21 terms in the charge basis by default. if nargout>2 error('Too many output arguments !'); elseif nargin>8 error('Too many input arguments !'); elseif nargin>7 M=varargin; if M<2 error('Bad input argument value !'); end end NBV=2*M+1; MtrxDim=NBV^2; H=zeros(MtrxDim); for n=1:MtrxDim N1=ceil(n/NBV)-M-1; N2=rem(n,NBV)-M-1; if N2 == -M-1 N2=M; end H(n,n)=Ec1*(N1-Ng1)^2+Ec2*(N2-Ng2)^2+Em*(N1-Ng1)*(N2-Ng2); % -Em*N1*N2; end for n1=1:MtrxDim-NBV n2=n1+NBV; H(n1,n2)=-Ej1/2; H(n2,n1)=-Ej1/2; end for n1=1:MtrxDim if mod(n1,NBV)~=0 n2=n1+1; H(n1,n2)=-Ej2/2; H(n2,n1)=-Ej2/2; end end [EigV E]=eig(H); EL=E*ones(MtrxDim,1); EL(M+1:MtrxDim)=[]; EigV(:,M+1:MtrxDim)=[]; varargout{1}=EigV(:,1:M);
github
oiwic/QOS-master
TriJFlxQbtdE.m
.m
QOS-master/qos/+sqc/+simulation/fluxQubit/3JJ/Fitting/TriJFlxQbtdE.m
770
utf_8
e322b6267f212553e2c54421d78e3650
function [E01,E02] = TriJFlxQbtdE(Jc,Cc,S,L,alpha,kappa,sigma,FluxBias,nk,nl,nm) [Ej, Ec, beta] = EjEcBetaCalc(Jc,Cc,S,L,alpha); EL = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,FluxBias,nk,nl,nm,6); E01 = (EL(3) + EL(4) - EL(1) - EL(2))/2; E02 = (EL(5) + EL(6) - EL(1) - EL(2))/2; end function [Ej, Ec, beta] = EjEcBetaCalc(Jc,Cc,S,L,alpha) % % Jc 1kA/cm^2 % Cc fA/um^2 % S um^2 % L pH % alpha Ic = Jc*10*S; % 1kA/cm^2 = 10 muA/mum^2 C = Cc*S; FluxQuantum = 2.067833636e-15; PlanksConst = 6.626068e-34; ee = 1.602176e-19; Ej = Ic*1e-6*FluxQuantum/(2*pi)/PlanksConst/1e9; % Unit: GHz. Ec = ee^2./(2*C*1e-15)/PlanksConst/1e9; % Unit: GHz. beta = (2*pi/(2+1/alpha))*Ic*1e-6*L*1e-12/FluxQuantum; end
github
oiwic/QOS-master
SpectrumLineErrorFcn_Jc_Cc_S_Alpaha_high.m
.m
QOS-master/qos/+sqc/+simulation/fluxQubit/3JJ/Fitting/SpectrumLineErrorFcn_Jc_Cc_S_Alpaha_high.m
2,058
utf_8
2d30be5f073da3099b6de0e619dde816
function Err = SpectrumLineErrorFcn_Jc_Cc_S_Alpaha_high(p) % x = [0 -3.0400 -6.0800 -9.1200 -12.1600 -15.2000]; % % y1 = [1.0712 5.2182 10.2069 15.1502 19.9511 24.2124]; % % y2 = [20.4903 22.3517 24.1392 25.7463 26.9363]; % x = [0 -3.0400 -6.0800 -9.1200 -12.1600 -15.2000]; % y = [1.0712 5.2182 10.2069 15.1502 19.9511 24.2124,... % 20.4903 22.3517 24.1392 25.7463 26.9363]; x = [0 -6.0800 -12.1600 -15.2000]*1e-3+0.5; % Phi_0 y = [1.0712 10.2069 19.9511 24.2124,... 20.4903 24.1392 26.9363]; % GHz Jc = p(1); % kA/cm^2 Cc = p(2); % fF/um^2 S = p(3); % um^2 alpha = p(4); % L = 30; % pH kappa = 0; sigma = 0; FluxBias = x; nk = 10; nl = 20; nm = 4; N = length(x); ycalc1 = zeros(1,N); ycalc2 = zeros(1,N); for ii = 1:N [E01,E02] = TriJFlxQbtdE(Jc,Cc,S,L,alpha,kappa,sigma,FluxBias(ii),nk,nl,nm); ycalc1(ii) = E01; ycalc2(ii) = E02; end ycalc = [ycalc1,ycalc2(1:end-1)]; dy = ycalc-y; Err = sqrt(sum(dy.^2)); % figure(); % plot([x, x(1:end-1)],y,'xb',[x, x(1:end-1)],ycalc,'+r'); end function [E01,E02] = TriJFlxQbtdE(Jc,Cc,S,L,alpha,kappa,sigma,FluxBias,nk,nl,nm) [Ej, Ec, beta] = EjEcBetaCalc(Jc,Cc,S,L,alpha); EL = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,FluxBias,nk,nl,nm,6); E01 = (EL(3) + EL(4) - EL(1) - EL(2))/2; E02 = (EL(5) + EL(6) - EL(1) - EL(2))/2; end function [Ej, Ec, beta] = EjEcBetaCalc(Jc,Cc,S,L,alpha) % % Jc 1kA/cm^2 % Cc fA/um^2 % S um^2 % L pH % alpha Ic = Jc*10*S; % 1kA/cm^2 = 10 muA/mum^2 C = Cc*S; FluxQuantum = 2.067833636e-15; PlanksConst = 6.626068e-34; ee = 1.602176e-19; Ej = Ic*1e-6*FluxQuantum/(2*pi)/PlanksConst/1e9; % Unit: GHz. Ec = ee^2./(2*C*1e-15)/PlanksConst/1e9; % Unit: GHz. beta = (2*pi/(2+1/alpha))*Ic*1e-6*L*1e-12/FluxQuantum; end
github
oiwic/QOS-master
SpectrumLineErrorFcn_Jc_Cc_S_Alpaha_low.m
.m
QOS-master/qos/+sqc/+simulation/fluxQubit/3JJ/Fitting/SpectrumLineErrorFcn_Jc_Cc_S_Alpaha_low.m
2,056
utf_8
0c13251b4d4e82bb4853524e8c177ca6
function Err = SpectrumLineErrorFcn_Jc_Cc_S_Alpaha_low(p) % x = [0 -3.0400 -6.0800 -9.1200 -12.1600 -15.2000]; % % y1 = [1.0712 5.2182 10.2069 15.1502 19.9511 24.2124]; % % y2 = [20.4903 22.3517 24.1392 25.7463 26.9363]; % x = [0 -3.0400 -6.0800 -9.1200 -12.1600 -15.2000]; % y = [1.0712 5.2182 10.2069 15.1502 19.9511 24.2124,... % 20.4903 22.3517 24.1392 25.7463 26.9363]; x = [0 -6.0800 -12.1600 -15.2000]*1e-3+0.5; % Phi_0 y = [1.0712 10.2069 19.9511 24.2124,... 20.4903 24.1392 26.9363]; % GHz Jc = p(1); % kA/cm^2 Cc = p(2); % fF/um^2 S = p(3); % um^2 alpha = p(4); % L = 30; % pH kappa = 0; sigma = 0; FluxBias = x; nk = 5; nl = 10; nm = 3; N = length(x); ycalc1 = zeros(1,N); ycalc2 = zeros(1,N); for ii = 1:N [E01,E02] = TriJFlxQbtdE(Jc,Cc,S,L,alpha,kappa,sigma,FluxBias(ii),nk,nl,nm); ycalc1(ii) = E01; ycalc2(ii) = E02; end ycalc = [ycalc1,ycalc2(1:end-1)]; dy = ycalc-y; Err = sqrt(sum(dy.^2)); % figure(); % plot([x, x(1:end-1)],y,'xb',[x, x(1:end-1)],ycalc,'+r'); end function [E01,E02] = TriJFlxQbtdE(Jc,Cc,S,L,alpha,kappa,sigma,FluxBias,nk,nl,nm) [Ej, Ec, beta] = EjEcBetaCalc(Jc,Cc,S,L,alpha); EL = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,FluxBias,nk,nl,nm,6); E01 = (EL(3) + EL(4) - EL(1) - EL(2))/2; E02 = (EL(5) + EL(6) - EL(1) - EL(2))/2; end function [Ej, Ec, beta] = EjEcBetaCalc(Jc,Cc,S,L,alpha) % % Jc 1kA/cm^2 % Cc fA/um^2 % S um^2 % L pH % alpha Ic = Jc*10*S; % 1kA/cm^2 = 10 muA/mum^2 C = Cc*S; FluxQuantum = 2.067833636e-15; PlanksConst = 6.626068e-34; ee = 1.602176e-19; Ej = Ic*1e-6*FluxQuantum/(2*pi)/PlanksConst/1e9; % Unit: GHz. Ec = ee^2./(2*C*1e-15)/PlanksConst/1e9; % Unit: GHz. beta = (2*pi/(2+1/alpha))*Ic*1e-6*L*1e-12/FluxQuantum; end
github
oiwic/QOS-master
TriJFlxQbtEL.m
.m
QOS-master/qos/+sqc/+simulation/fluxQubit/3JJ/Fitting/TriJFlxQbtEL.m
4,355
utf_8
eea0c43da523c4ca69b4dc8e04e4b756
function EL = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,FluxBias,nk,nl,nm,nlevels) % 'TriJFlxQbtEL' calculates the three-junction flux qubit energy levels. % Based on the papar: Robertson et al., Phys. Rev. Letts. B 73, 174526 (2006). % Syntax % Energy Level values = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,FluxBias,nk,nl,nm,nlevels) % Example: % EL = TriJFlxQbtEL(50,1,0.63,0.15,0,0,0.5,5,10,2,20) % Energy unit: The same as Ej and Ec. % FluxBias unit:FluxQuantum % nlevels: return the energy values of the lowest n energy levels. % Author: Yulin Wu <[email protected]> % Date: 2009/5/6 % Revision: % 2011/4/30 if nlevels > nk*nl*nm EL = 'ERROR: nlevels > nk*nl*nm !'; return; end if beta == 0 beta = 1e-6; % beta can not be zero ! end hbar=1.054560652926899e-034; PhiQ=2*pi*FluxBias; M=zeros(3,3); % M here is invert M in Phys. Rev. B 73, 174526 (2006), Eq.16. tmp=1+2*alpha; M(1,1)=1+sigma; M(1,2)=kappa/tmp; M(1,3)=2*alpha*kappa/tmp; M(2,1)=M(1,2); M(2,2)=((sigma+alpha)*(1+sigma)+2*alpha^2*(1-kappa^2+2*sigma+sigma^2))/(tmp^2*(alpha+sigma)); M(2,3)=2*alpha*(sigma+sigma^2+alpha*(kappa^2-sigma-sigma^2))/(tmp^2*(alpha+sigma)); M(3,1)=M(1,3); M(3,2)=M(2,3); M(3,3)=2*alpha^2*(2*alpha*(1+sigma)+1+4*sigma+3*sigma^2-kappa^2)/(tmp^2*(alpha+sigma)); M=4*Ec/(hbar^2*((1+sigma)^2-kappa^2))*M; tmp1=2*Ej*alpha*(1-kappa^2)*((1+sigma)*(1+2*alpha+3*sigma)-kappa^2); tmp2=Ec*beta*(1+2*alpha-kappa^2)*(alpha+sigma)*((1+sigma)^2-kappa^2); omega_t=2*Ec/hbar*sqrt(tmp1/tmp2); tmp1=hbar^2*(alpha+sigma)*((1+sigma^2)-kappa^2)*(1+2*alpha)^2; tmp2=8*Ec*alpha^2*((1+sigma)*(1+2*alpha+3*sigma)-kappa^2); m_t=tmp1/tmp2; U{1,1}=[0 0]; U{1,2}=[(1-kappa)/2 i]; U{1,3}=[0 0]; U{1,4}=[(1+kappa)/2 -i]; U{1,5}=[0 0]; %#ok<*IJCL> U{2,2}=[0 0]; U{2,3}=[0 0]; U{2,4}=[0 0]; U{3,1}=[0 0]; U{3,2}=[(1+kappa)/2 i]; U{3,3}=[0 0]; U{3,4}=[(1-kappa)/2 -i]; U{3,5}=[0 0]; U{2,1}=[alpha*exp(i*PhiQ)/2 -i/alpha]; U{2,5}=[alpha*exp(-i*PhiQ)/2 i/alpha]; H=zeros((2*nk+1)*(2*nl+1)*(nm+1)); for k1=-nk:nk kk1=k1+nk+1; for l1=-nl:nl ll1=l1+nl+1; for m1=0:nm mm1=m1+1; for k2=-nk:nk kk2=k2+nk+1; for l2=-nl:nl ll2=l2+nl+1; for m2=0:nm mm2=m2+1; n1=(kk1-1)*(2*nl+1)*(nm+1)+(ll1-1)*(nm+1)+mm1; n2=(kk2-1)*(2*nl+1)*(nm+1)+(ll2-1)*(nm+1)+mm2; if n2<n1 H(n1,n2)=conj(H(n2,n1)); else H1=hbar^2*(k1^2*M(1,1)/2+k1*l1*M(1,2)+l1^2*M(2,2)/2)*Kdelta(k1,k2)*Kdelta(l1,l2)*Kdelta(m1,m2); H2=-i*sqrt((m_t*omega_t*hbar^3)/2)*(M(1,3)*k1+M(2,3)*l1)*Kdelta(k1,k2)*Kdelta(l1,l2)*(sqrt(m2+1)*Kdelta(m2+1,m1)-sqrt(m2)*Kdelta(m2-1,m1)); tmp1=0; for p=-1:1 row=p+2; for q=-2:2 cln=q+3; if k1==p+k2 && l1==q+l2 && U{row,cln}(1)~=0 cc=U{row,cln}(2); tmp=0; tmp2=sqrt(hbar/(2*m_t*omega_t))*cc; for jj=0:min(m1,m2) tmp=tmp+factorial(jj)*nchoosek(m1,jj)*nchoosek(m2,jj)*(tmp2)^(m1+m2-2*jj); end tmp=tmp*(factorial(m1)*factorial(m2))^(-0.5)*exp(tmp2^2/2); tmp1=tmp1+U{row,cln}(1)*tmp; end end end H3=-Ej*tmp1; H4=(m1+0.5)*hbar*omega_t*Kdelta(k1,k2)*Kdelta(l1,l2)*Kdelta(m1,m2); H(n1,n2)=H1+H2+H3+H4; end end end end end end end EL=eig(H); EL(nlevels+1:end)=[]; end function f=Kdelta(x1,x2) if x1==x2 f=1; else f=0; end end
github
oiwic/QOS-master
ThreeJJQbtES.m
.m
QOS-master/qos/+sqc/+simulation/fluxQubit/3JJ/GUIver/ThreeJJQbtES.m
76,488
utf_8
3510ee242c623625d8177c1ef818317e
function varargout = ThreeJJQbtES(varargin) % THREEJJQBTES M-file for ThreeJJQbtES.fig % THREEJJQBTES, by itself, creates a new THREEJJQBTES or raises the existing % singleton*. % % H = THREEJJQBTES returns the handle to a new THREEJJQBTES or the handle to % the existing singleton*. % % THREEJJQBTES('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in THREEJJQBTES.M with the given input arguments. % % THREEJJQBTES('Property','Value',...) creates a new THREEJJQBTES or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before ThreeJJQbtES_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to ThreeJJQbtES_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Last Modified by GUIDE v2.5 15-Mar-2012 19:32:52 gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @ThreeJJQbtES_OpeningFcn, ... 'gui_OutputFcn', @ThreeJJQbtES_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before ThreeJJQbtES is made visible. function ThreeJJQbtES_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 ThreeJJQbtES (see VARARGIN) % Choose default command line output for ThreeJJQbtES handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes ThreeJJQbtES wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = ThreeJJQbtES_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function alpha_value_Callback(hObject, eventdata, handles) % hObject handle to alpha_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_alpha str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.alpha_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_alpha = false; elseif isnan(temp) set(handles.alpha_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_alpha = false; elseif temp<=0 set(handles.alpha_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_alpha = false; elseif temp <0.4 || temp >=1 set(handles.alpha_status,'String','Improper value!','ForegroundColor',[0 0 0]); Check_alpha = true; set(handles.info_enteralpha,'Visible','off'); else set(handles.alpha_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_alpha = true; set(handles.info_enteralpha,'Visible','off'); end % Hints: get(hObject,'String') returns contents of alpha_value as text % str2double(get(hObject,'String')) returns contents of alpha_value as a double % --- Executes during object creation, after setting all properties. function alpha_value_CreateFcn(hObject, eventdata, handles) % hObject handle to alpha_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_alpha Check_alpha = false; % alpha has no default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function alpha_title_CreateFcn(hObject, eventdata, handles) % hObject handle to alpha_title (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called function beta_value_Callback(hObject, eventdata, handles) % hObject handle to beta_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_beta str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.beta_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_beta = false; elseif isnan(temp) set(handles.beta_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_beta = false; elseif temp<0 set(handles.beta_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_beta = false; elseif temp >=1 set(handles.beta_status,'String','Improper value!','ForegroundColor',[0 0 0]); Check_beta = true; elseif temp == 0 set(handles.beta_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_beta = true; else set(handles.beta_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_beta = true; end % Hints: get(hObject,'String') returns contents of beta_value as text % str2double(get(hObject,'String')) returns contents of beta_value as a double % --- Executes during object creation, after setting all properties. function beta_value_CreateFcn(hObject, eventdata, handles) % hObject handle to beta_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_beta Check_beta = true; % beta has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function kappa_value_Callback(hObject, eventdata, handles) % hObject handle to kappa_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_kappa str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.kappa_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_kappa = false; elseif isnan(temp) set(handles.kappa_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_kappa = false; elseif abs(temp)>=1 set(handles.kappa_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_kappa = false; elseif abs(temp)>=0.4 set(handles.kappa_status,'String','Improper value!','ForegroundColor',[0 0 0]); Check_kappa = true; elseif temp == 0 set(handles.kappa_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_kappa=true; else set(handles.kappa_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_kappa=true; end % Hints: get(hObject,'String') returns contents of kappa_value as text % str2double(get(hObject,'String')) returns contents of kappa_value as a double % --- Executes during object creation, after setting all properties. function kappa_value_CreateFcn(hObject, eventdata, handles) % hObject handle to kappa_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_kappa Check_kappa=true; % kappa has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function sigma_value_Callback(hObject, eventdata, handles) % hObject handle to sigma_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_sigma str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.sigma_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_sigma = false; elseif isnan(temp) set(handles.sigma_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_sigma = false; elseif temp<0 set(handles.sigma_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_sigma = false; elseif temp>=0.5 set(handles.sigma_status,'String','Improper value!','ForegroundColor',[0 0 0]); Check_sigma = true; elseif temp == 0 set(handles.sigma_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_sigma = true; else set(handles.sigma_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_sigma = true; end % Hints: get(hObject,'String') returns contents of sigma_value as text % str2double(get(hObject,'String')) returns contents of sigma_value as a double % --- Executes during object creation, after setting all properties. function sigma_value_CreateFcn(hObject, eventdata, handles) % hObject handle to sigma_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_sigma Check_sigma = true; % sigma has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Ej_value_Callback(hObject, eventdata, handles) % hObject handle to Ej_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_Ej str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.Ej_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_Ej = false; elseif isnan(temp) set(handles.Ej_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_Ej = false; elseif temp<=0 set(handles.Ej_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_Ej = false; elseif temp>500 || temp<20 set(handles.Ej_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_Ej = true; else set(handles.Ej_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_Ej = true; end % Hints: get(hObject,'String') returns contents of Ej_value as text % str2double(get(hObject,'String')) returns contents of Ej_value as a double % --- Executes during object creation, after setting all properties. function Ej_value_CreateFcn(hObject, eventdata, handles) % hObject handle to Ej_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_Ej Check_Ej = false; % Ej has no default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Ec_value_Callback(hObject, eventdata, handles) % hObject handle to Ec_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_Ec str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.Ec_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_Ec = false; elseif isnan(temp) set(handles.Ec_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_Ec = false; elseif temp<=0 set(handles.Ec_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_Ec = false; elseif temp>50 || temp<0.5 set(handles.Ec_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_Ec = true; else set(handles.Ec_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_Ec = true; end % Hints: get(hObject,'String') returns contents of Ec_value as text % str2double(get(hObject,'String')) returns contents of Ec_value as a double % --- Executes during object creation, after setting all properties. function Ec_value_CreateFcn(hObject, eventdata, handles) % hObject handle to Ec_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_Ec Check_Ec = false; % Ec has no default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function calc_range_value_Callback(hObject, eventdata, handles) % hObject handle to calc_range (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_range str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.calc_range_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_range = false; elseif isnan(temp) set(handles.calc_range_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_range = false; elseif temp>=0.5 set(handles.calc_range_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_range = false; elseif temp<-1 set(handles.calc_range_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); set(handles.calc_range_end,'String',num2str(1-temp),'ForegroundColor',[0 0 0]); Check_range = true; elseif temp == 0 set(handles.calc_range_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); set(handles.calc_range_end,'String',num2str(1-temp),'ForegroundColor',[0 0 0]); Check_range = true; else set(handles.calc_range_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); set(handles.calc_range_end,'String',num2str(1-temp),'ForegroundColor',[0 0 0]); Check_range = true; end % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function calc_range_value_CreateFcn(hObject, eventdata, handles) % hObject handle to calc_range (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_range Check_range = true; % calc_range has a default value % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function calc_n_points_Callback(hObject, eventdata, handles) % hObject handle to calc_n_points (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_calc_n_points str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.calc_n_points_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_calc_n_points = false; elseif isnan(temp) set(handles.calc_n_points_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_calc_n_points = false; elseif temp<=2 set(handles.calc_n_points_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_calc_n_points = false; elseif temp>500 set(handles.calc_n_points_status,'String','Too many points, the computation process may take a long time!','ForegroundColor',[1 0 0]); Check_calc_n_points = true; elseif temp<=8 || temp>5e3 set(handles.calc_n_points_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_calc_n_points = true; elseif temp == 100 set(handles.calc_n_points_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_calc_n_points = true; else set(handles.calc_n_points_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_calc_n_points = true; end % Hints: get(hObject,'String') returns contents of calc_n_points as text % str2double(get(hObject,'String')) returns contents of calc_n_points as a double % --- Executes during object creation, after setting all properties. function calc_n_points_CreateFcn(hObject, eventdata, handles) % hObject handle to calc_n_points (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_calc_n_points Check_calc_n_points = true; % calc_n_points has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function calc_range_end_CreateFcn(hObject, eventdata, handles) % hObject handle to calc_range_end (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called function nlevels_value_Callback(hObject, eventdata, handles) % hObject handle to nlevels_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_nlevels_value str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.nlevels_value_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_nlevels_value = false; elseif isnan(temp) set(handles.nlevels_value_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_nlevels_value = false; elseif temp<1 set(handles.nlevels_value_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_nlevels_value = false; elseif temp<3 || temp>500 set(handles.nlevels_value_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); elseif temp==4 set(handles.nlevels_value_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_nlevels_value = true; else set(handles.nlevels_value_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_nlevels_value = true; end % Hints: get(hObject,'String') returns contents of nlevels_value as text % str2double(get(hObject,'String')) returns contents of nlevels_value as a double % --- Executes during object creation, after setting all properties. function nlevels_value_CreateFcn(hObject, eventdata, handles) % hObject handle to nlevels_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_nlevels_value Check_nlevels_value = true; % nlevels_value has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function nk_value_Callback(hObject, eventdata, handles) % hObject handle to nk_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_nk_value str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.nk_value_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_nk_value = false; elseif isnan(temp) set(handles.nk_value_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_nk_value = false; elseif temp<1 set(handles.nk_value_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_nk_value = false; elseif temp > 20 || temp < 3 set(handles.nk_value_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_nk_value = true; elseif temp == 5 set(handles.nk_value_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_nk_value = true; else set(handles.nk_value_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_nk_value = true; end % Hints: get(hObject,'String') returns contents of nk_value as text % str2double(get(hObject,'String')) returns contents of nk_value as a double % --- Executes during object creation, after setting all properties. function nk_value_CreateFcn(hObject, eventdata, handles) % hObject handle to nk_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_nk_value Check_nk_value = true; % nk_value has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function nl_value_Callback(hObject, eventdata, handles) % hObject handle to nl_title (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_nl_value str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.nl_value_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_nl_value = false; elseif isnan(temp) set(handles.nl_value_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_nl_value = false; elseif temp<1 set(handles.nl_value_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_nl_value = false; elseif temp > 40 || temp < 5 set(handles.nl_value_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_nl_value = true; elseif temp == 10 set(handles.nl_value_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_nl_value = true; else set(handles.nl_value_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_nl_value = true; end % Hints: get(hObject,'String') returns contents of nl_title as text % str2double(get(hObject,'String')) returns contents of nl_title as a double % --- Executes during object creation, after setting all properties. function nl_value_CreateFcn(hObject, eventdata, handles) % hObject handle to nk_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_nl_value Check_nl_value = true; % nl_value has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function nl_title_CreateFcn(hObject, eventdata, handles) % hObject handle to nl_title (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function nm_value_Callback(hObject, eventdata, handles) % hObject handle to nm_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_nm_value str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.nm_value_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_nm_value = false; elseif isnan(temp) set(handles.nm_value_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_nm_value = false; elseif temp<1 set(handles.nm_value_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_nm_value = false; elseif temp > 8 set(handles.nm_value_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_nm_value = true; elseif temp == 2 set(handles.nm_value_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_nm_value = true; else set(handles.nm_value_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_nm_value = true; end % Hints: get(hObject,'String') returns contents of nm_value as text % str2double(get(hObject,'String')) returns contents of nm_value as a double % --- Executes during object creation, after setting all properties. function nm_value_CreateFcn(hObject, eventdata, handles) % hObject handle to nm_value (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_nm_value Check_nm_value = true; % nm_value has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Jc_Callback(hObject, eventdata, handles) % hObject handle to Jc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_Jc str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.Jc_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_Jc = false; elseif isnan(temp) set(handles.Jc_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_Jc = false; elseif temp<=0 set(handles.Jc_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_Jc = false; elseif temp > 5 || temp<0.05 set(handles.Jc_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_Jc = true; else set(handles.Jc_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_Jc = true; end % Hints: get(hObject,'String') returns contents of Jc as text % str2double(get(hObject,'String')) returns contents of Jc as a double % --- Executes during object creation, after setting all properties. function Jc_CreateFcn(hObject, eventdata, handles) % hObject handle to Jc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_Jc Check_Jc = false; % Jc has no default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Cc_Callback(hObject, eventdata, handles) % hObject handle to Cc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_Cc str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.Cc_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_Cc = false; elseif isnan(temp) set(handles.Cc_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_Cc = false; elseif temp<=0 set(handles.Cc_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_Cc = false; elseif temp > 200 || temp<10 set(handles.Cc_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_Cc = true; elseif temp == 100 set(handles.Cc_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_Cc = true; else set(handles.Cc_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_Cc = true; end % Hints: get(hObject,'String') returns contents of Cc as text % str2double(get(hObject,'String')) returns contents of Cc as a double % --- Executes during object creation, after setting all properties. function Cc_CreateFcn(hObject, eventdata, handles) % hObject handle to Cc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_Cc Check_Cc = true; % Cc has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function junction_area_Callback(hObject, eventdata, handles) % hObject handle to junction_area (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_junction_area str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.junction_area_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_junction_area = false; elseif isnan(temp) set(handles.junction_area_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_junction_area = false; elseif temp<=0 set(handles.junction_area_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_junction_area = false; elseif temp > 0.3 || temp<0.01 set(handles.junction_area_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_junction_area = true; else set(handles.junction_area_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_junction_area = true; end % Hints: get(hObject,'String') returns contents of junction_area as text % str2double(get(hObject,'String')) returns contents of junction_area as a double % --- Executes during object creation, after setting all properties. function junction_area_CreateFcn(hObject, eventdata, handles) % hObject handle to junction_area (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_junction_area Check_junction_area = false; % junction_area has no default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Inductance_Callback(hObject, eventdata, handles) % hObject handle to Inductance (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_Inductance str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.Inductance_status,'String','Empty!','ForegroundColor',[1 0 0]); Check_Inductance = false; elseif isnan(temp) set(handles.Inductance_status,'String','Must be numeric!','ForegroundColor',[1 0 0]); Check_Inductance = false; elseif temp>1e4 || temp <0 set(handles.Inductance_status,'String','Incorrect value!','ForegroundColor',[1 0 0]); Check_Inductance = false; elseif temp > 500 set(handles.Inductance_status,'String','Improper value!','ForegroundColor',[0.502 0.502 0.502]); Check_Inductance = true; elseif temp == 0 set(handles.Inductance_status,'String','Default','ForegroundColor',[0.502 0.502 0.502]); Check_Inductance = true; else set(handles.Inductance_status,'String','OK!','ForegroundColor',[0.502 0.502 0.502]); Check_Inductance = true; end % Hints: get(hObject,'String') returns contents of Inductance as text % str2double(get(hObject,'String')) returns contents of Inductance as a double % --- Executes during object creation, after setting all properties. function Inductance_CreateFcn(hObject, eventdata, handles) % hObject handle to Inductance (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_Inductance Check_Inductance = true; % Inductance has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in UserConfirm_Continue. function UserConfirm_Continue_Callback(hObject, eventdata, handles) % hObject handle to UserConfirm_Continue (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.UserConfirm_Continue,'Enable','off','Visible','off'); CoreFcn(handles); % --- Executes on button press in Calc_EjEc. function Calc_EjEc_Callback(hObject, eventdata, handles) % hObject handle to Calc_EjEc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_Jc global Check_Cc global Check_Ej global Check_Ec global Check_junction_area global Check_Inductance global Check_alpha if Check_alpha set(handles.info_enteralpha,'Visible','off'); if Check_Jc && Check_Cc && Check_junction_area && Check_Inductance Jc = str2double(get(handles.Jc,'String')); Cc = str2double(get(handles.Cc,'String')); S = str2double(get(handles.junction_area,'String')); L = str2double(get(handles.Inductance,'String')); alpha = str2double(get(handles.alpha_value,'String')); Ic = Jc*10*S; % 1kA/cm^2 = 10 muA/mum^2 C = Cc*S; FluxQuantum = 2.067833636e-15; PlanksConst = 6.626068e-34; ee = 1.602176e-19; Ej = Ic*1e-6*FluxQuantum/(2*pi)/PlanksConst/1e9; % Unit: GHz. Ec = ee^2./(2*C*1e-15)/PlanksConst/1e9; % Unit: GHz. beta = (2*pi/(2+1/alpha))*Ic*1e-6*L*1e-12/FluxQuantum; Check_Ej = true; Check_Ec = true; Check_beta = true; set(handles.Ej_value,'String',num2str(Ej),'ForegroundColor',[0 0 1]); set(handles.Ej_status,'String','Calculated','ForegroundColor',[0.502 0.502 0.502]); set(handles.Ec_value,'String',num2str(Ec),'ForegroundColor',[0 0 1]); set(handles.Ec_status,'String','Calculated','ForegroundColor',[0.502 0.502 0.502]); set(handles.beta_value,'String',num2str(beta),'ForegroundColor',[0 0 1]); set(handles.beta_status,'String','Calculated','ForegroundColor',[0.502 0.502 0.502]); set(handles.info_Info_disp,'String',['Ic = ', num2str(Ic,'%10.3f'), ' muA (avg.)', char([10 13]),... 'Ej/Ec = ', num2str(Ej/Ec,'%10.1f')],'ForegroundColor',[0.502 0.502 0.502],'Visible','on'); end else set(handles.info_enteralpha,'Visible','on'); end function Parallel_labs_Callback(hObject, eventdata, handles) % hObject handle to Parallel_labs (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_Parallel_labs str=get(hObject,'String'); temp = str2double(str); if isempty(str) set(handles.Parallel_labs_status,'String','Empty! Suggestion: equal to the number of CPU cores','ForegroundColor',[1 0 0]); Check_Parallel_labs = false; elseif isnan(temp) set(handles.Parallel_labs_status,'String','Must be numeric! Suggestion: equal to the number of CPU cores','ForegroundColor',[1 0 0]); Check_Parallel_labs = false; elseif temp<1 set(handles.Parallel_labs_status,'String','Incorrect value! Suggestion: equal to the number of CPU cores','ForegroundColor',[1 0 0]); Check_Parallel_labs = false; elseif floor(temp)<temp set(handles.Parallel_labs_status,'String','Must be integer! Suggestion: equal to the number of CPU cores','ForegroundColor',[1 0 0]); Check_Parallel_labs = false; elseif temp==1 set(handles.Parallel_labs_status,'String','Parallel computing disabled','ForegroundColor',[0.502 0.502 0.502]); Check_Parallel_labs = true; elseif temp>1000 set(handles.Parallel_labs_status,'String','Improper value! Suggestion: equal to the number of CPU cores','ForegroundColor',[0.502 0.502 0.502]); Check_Parallel_labs = true; elseif temp>100 set(handles.Parallel_labs_status,'String','Too many labs! Suggestion: equal to the number of CPU cores','ForegroundColor',[0.502 0.502 0.502]); Check_Parallel_labs = true; else set(handles.Parallel_labs_status,'String','(Suggestion: equal to the number of CPU cores)','ForegroundColor',[0.502 0.502 0.502]); Check_Parallel_labs = true; end % Hints: get(hObject,'String') returns contents of Parallel_labs as text % str2double(get(hObject,'String')) returns contents of Parallel_labs as a double % --- Executes during object creation, after setting all properties. function Parallel_labs_CreateFcn(hObject, eventdata, handles) % hObject handle to Parallel_labs (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_Parallel_labs Check_Parallel_labs = true; % Parallel_labs has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in Exit_button. function Exit_button_Callback(hObject, eventdata, handles) % hObject handle to Exit_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) nParallel_labs = str2double(get(handles.Parallel_labs,'String')); if nParallel_labs > 1 matlabpool close; end exit; function datafilename_Callback(hObject, eventdata, handles) % hObject handle to datafilename (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_datafilename str=get(hObject,'String'); if isempty(str) set(handles.datafilename,'BackgroundColor',[1 0 0]); Check_datafilename = false; else k1 = isempty(strfind(str,'\')) + ... isempty(strfind(str,'/')) + ... isempty(strfind(str,':')) + ... isempty(strfind(str,'*')) + ... isempty(strfind(str,'?')) + ... isempty(strfind(str,'"')) + ... isempty(strfind(str,'<')) + ... isempty(strfind(str,'>')) + ... isempty(strfind(str,'|')); if k1 ~= 9 set(handles.datafilename,'String','Bad filename!','BackgroundColor',[1 0 0]); Check_datafilename = false; else Check_datafilename = true; set(handles.datafilename,'BackgroundColor',[1 1 1]); end end % Hints: get(hObject,'String') returns contents of datafilename as text % str2double(get(hObject,'String')) returns contents of datafilename as a double % --- Executes during object creation, after setting all properties. function datafilename_CreateFcn(hObject, eventdata, handles) % hObject handle to datafilename (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_datafilename Check_datafilename = true; % Check_datafilename has a default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function save_dir_CreateFcn(hObject, eventdata, handles) % hObject handle to save_dir (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called global Check_dir Check_dir = false; % Check_datafilename has no default value % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in browse4dir. function browse4dir_Callback(hObject, eventdata, handles) % hObject handle to browse4dir (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global Check_dir filename=get(handles.datafilename,'String'); [file,path] = uiputfile([filename,'.dat'],'Save data to:'); if path == 0 Check_dir = false; else set(handles.save_dir,'String',path); set(handles.save_dir,'BackgroundColor',[1 1 1]); Check_dir = true; set(handles.datafilename,'String',file(1:end-4),'BackgroundColor',[1 1 1]); Check_datafilename = true; end % --- Executes on button press in StartCalc. function StartCalc_Callback(hObject, eventdata, handles) % hObject handle to StartCalc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Plot3JJQbtEL(Ej,Ec,alpha,beta,kappa,sigma,StartPoint,dFluxBias,nlevels,nk,nl,nm,NMatlabpools) global Check_alpha; global Check_beta; global Check_kappa; global Check_sigma; global Check_Ej; global Check_Ec; global Check_range; global Check_calc_n_points; global Check_nlevels_value; global Check_nk_value; global Check_nl_value; global Check_nm_value; global Check_Parallel_labs % Check input parameters: if ... Check_alpha && ... Check_beta && ... Check_kappa && ... Check_sigma && ... Check_Ej && ... Check_Ec && ... Check_range && ... Check_calc_n_points && ... Check_nlevels_value && ... Check_nk_value && ... Check_nl_value && ... Check_nm_value && ... Check_Parallel_labs PlotNLevels = str2double(get(handles.nlevels_value,'String')); nk = str2double(get(handles.nk_value,'String')); nl = str2double(get(handles.nl_value,'String')); nm = str2double(get(handles.nm_value,'String')); set(handles.Warnning_Para,'Visible','off'); matrixdim = nk*nl*nm; if PlotNLevels>matrixdim set(handles.matrix_dim_check,'String',... 'Matrix dimension nk*nl*nm smaller than the number of levels to be plotted!',... 'ForegroundColor',[1 0 0]); set(handles.Warnning_Para,'Visible','on'); set(handles.StartCalc,'ForegroundColor',[0.502 0.502 0.502]); else if nm>10 || matrixdim>1000 set(handles.matrix_dim_check,'String',... 'Matrix dimension too big, the computation process may take a long time!',... 'ForegroundColor',[1 0 0]); set(handles.UserConfirm_Continue,'Enable','on','Visible','on'); else set(handles.matrix_dim_check,'String','Matrix dimension check: OK!',... 'ForegroundColor',[0.502 0.502 0.502]); set(handles.UserConfirm_Continue,'Enable','off','Visible','off'); CoreFcn(handles); end end else set(handles.Warnning_Para,'Visible','on'); set(handles.StartCalc,'ForegroundColor',[0.502 0.502 0.502]); end % --- Executes during object creation, after setting all properties. function info_Info_disp_CreateFcn(hObject, eventdata, handles) % hObject handle to info_Info_disp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function Elapsed_time_CreateFcn(hObject, eventdata, handles) % hObject handle to Elapsed_time (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function Remaining_time_CreateFcn(hObject, eventdata, handles) % hObject handle to Remaining_time (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function datafilename_title_CreateFcn(hObject, eventdata, handles) % hObject handle to datafilename_title (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function info_save_location_CreateFcn(hObject, eventdata, handles) % hObject handle to info_save_location (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function Author_Info_CreateFcn(hObject, eventdata, handles) % hObject handle to Author_Info (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function Warnning_Para_CreateFcn(hObject, eventdata, handles) % hObject handle to Warnning_Para (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function info_UsrCnfrm_CreateFcn(hObject, eventdata, handles) % hObject handle to info_UsrCnfrm (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function Exit_button_CreateFcn(hObject, eventdata, handles) % hObject handle to Exit_button (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function Parallel_labs_status_CreateFcn(hObject, eventdata, handles) % hObject handle to Parallel_labs_status (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function info_Parallel_labs_CreateFcn(hObject, eventdata, handles) % hObject handle to info_Parallel_labs (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes during object creation, after setting all properties. function Parallel_labs_title_CreateFcn(hObject, eventdata, handles) % hObject handle to Parallel_labs_title (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes on button press in SaveScreenshot. function SaveScreenshot_Callback(hObject, eventdata, handles) % hObject handle to SaveScreenshot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of SaveScreenshot % --- Executes on button press in DoInterp. function DoInterp_Callback(hObject, eventdata, handles) % hObject handle to DoInterp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of DoInterp % --- Executes on button press in UnitChoice. function UnitChoice_Callback(hObject, eventdata, handles) % hObject handle to UnitChoice (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) button_state = get(hObject,'Value'); if button_state == get(hObject,'Max') set(handles.UnitChoice,'String','micro eV'); elseif button_state == get(hObject,'Min') set(handles.UnitChoice,'String','h*GHz'); end function CoreFcn(handles) global Check_datafilename global Check_dir set(handles.Warnning_Para,'Visible','off'); set(handles.StartCalc,'String','BUSY', 'ForegroundColor',[1 0 0],'Enable','inactive'); set(handles.info_Info_disp,'String',['Start time:', datestr(now),char(13),char(10),'Calculating...'],'Visible','on'); alpha = str2double(get(handles.alpha_value,'String')); beta = str2double(get(handles.beta_value,'String')); kappa = str2double(get(handles.kappa_value,'String')); sigma = str2double(get(handles.sigma_value,'String')); Ej = str2double(get(handles.Ej_value,'String')); Ec = str2double(get(handles.Ec_value,'String')); CalcRange = str2double(get(handles.calc_range_value,'String')); CalcNPoints = str2double(get(handles.calc_n_points,'String')); PlotNLevels = str2double(get(handles.nlevels_value,'String')); nk = str2double(get(handles.nk_value,'String')); nl = str2double(get(handles.nl_value,'String')); nm = str2double(get(handles.nm_value,'String')); nParallel_labs = str2double(get(handles.Parallel_labs,'String')); FluxBias=linspace(CalcRange,0.5,ceil(CalcNPoints/2)); Npoints=length(FluxBias); NPperSection = nParallel_labs*3; ContinuePoint = 1; OutputDataName=['Data\3JJQbtEL-Ej' num2str(Ej,'%10.2f') 'Ec' num2str(Ec,'%10.3f') 'a' num2str(alpha) 'b' num2str(beta,'%10.3f') 'k' num2str(kappa) 's' num2str(sigma)]; OutputDataName=[OutputDataName 'S' num2str(CalcRange) 'np' num2str(CalcNPoints) '[' num2str(nk), ',', num2str(nl), ',', num2str(nm), ']', '.mat']; needwait=false; Convert2microeV=false; % do not convert energy unit to micro-eV or not buy user choice if get(handles.UnitChoice,'Value') == get(handles.UnitChoice,'Max') Convert2microeV=true; % convert energy unit to micro-eV or not buy user choice end if isempty(dir('Data')) mkdir('Data'); elseif ~isempty(dir(OutputDataName)) load(OutputDataName); end if ischar(ContinuePoint) set(handles.info_Info_disp,'String',... ['Calculation for the present set of paramenters has been done before, energy levels will be ploted directly by loading the saved data file: ',... OutputDataName],'Visible','on'); needwait=true; else if ContinuePoint >1 set(handles.info_Info_disp,'String','Continue a previous unfinished process for the present set of parameters','Visible','on'); end Nsections = floor(Npoints/NPperSection); NPFinal = NPperSection; tmp = mod(Npoints,NPperSection); if tmp > 0 Nsections = Nsections +1; NPFinal = tmp; end set(handles.Exit_button,'Visible','on','Enable','on'); set(handles.info_UsrCnfrm,'Visible','on'); set(handles.Elapsed_time,'String','Elapsed time: not known yet','Visible','on'); set(handles.Remaining_time,'String','Remaining time: not known yet','Visible','on'); LastFinished = (ContinuePoint-1)*NPperSection; pause(0.5); % pause needed for panel display refresh to take effect! mpool = gcp('nocreate'); if nParallel_labs >1 && (isempty(mpool) || mpool.NumWorkers ~= nParallel_labs) delete(gcp('nocreate')); parpool(nParallel_labs); end tic; for dd = ContinuePoint:Nsections if dd == Nsections NPSection = NPFinal; else NPSection = NPperSection; end SliceH = (dd-1)*NPperSection+1; SliceE = (dd-1)*NPperSection+NPSection; BiasSlice = FluxBias(SliceH:SliceE); parfor ee=1:NPSection EL = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,BiasSlice(ee),nk,nl,nm,nk*nl*nm); if ischar(EL) error(EL); end el(ee,:) = EL; end if ContinuePoint == 1 EnergyLevel = el; else EnergyLevel = [EnergyLevel; el]; end ContinuePoint = dd + 1; save(OutputDataName,'FluxBias','EnergyLevel','ContinuePoint','NPperSection'); time = toc/60; remainingtime = time*(Npoints-SliceE)/(SliceE-LastFinished); disp(['Elapsed time: ',num2str(time)]); pause(0.8); % pause needed, otherwise STOP & EXIT... button press on panel will not be effective! set(handles.Elapsed_time,'String',['Elapsed time: ',num2str(time,'%10.1f'),' min.'],'Visible','on'); set(handles.Remaining_time,'String',['Remaining time: ',num2str(remainingtime,'%10.1f'),' min.'],'Visible','on'); pause(0.8); % pause needed, otherwise the above two code line will take no effect! end EnergyLevel=EnergyLevel-EnergyLevel(Npoints,1); % set the ground level of 0.5*FluxQuantum Flux Bias as the zero energy point. dFluxBias = FluxBias(2)-FluxBias(1); for kk=Npoints+1:2*Npoints-1 EnergyLevel(kk,:)=EnergyLevel(2*Npoints-kk,:); FluxBias(kk)=FluxBias(kk-1)+dFluxBias; end ContinuePoint = 'END'; save(OutputDataName,'FluxBias','EnergyLevel','ContinuePoint','NPperSection'); % EnergyLevel(jj,kk) is the kkth energy level value of the fluxbias % condition Fluxbias = FluxBias(jj)*Flux quantum. end Parameters = ['E_J:',num2str(Ej,'%10.2f'),'GHz; E_C:',num2str(Ec,'%10.3f'),'GHz; \alpha:',num2str(alpha,'%10.3f'),'; \beta:',num2str(beta,'%10.4f'),'; \sigma:',num2str(sigma),'; \kappa:',num2str(kappa)]; while 1 if ~Check_datafilename set(handles.datafilename,'String','Enter a name!','BackgroundColor',[1 0 0]); elseif ~Check_dir set(handles.save_dir,'String','Choose a path to save!','BackgroundColor',[1 0 0]); else filename = get(handles.datafilename,'String'); datafilename = [filename,'.dat']; path = get(handles.save_dir,'String'); datfile = fopen([path datafilename],'w'); fwrite(datfile,Parameters); fwrite(datfile,[char(13),char(10)]); fwrite(datfile,['FluxBias/Phi_0',char(9),'EnergyLevel1(GHz)',... char(9),'EnergyLevel2(GHz)',char(9),'EnergyLevel3(GHz)',char(9),'...']); fwrite(datfile,[char(13),char(10)]); break; end end if (get(handles.SaveScreenshot,'Value') == get(handles.SaveScreenshot,'Max')) path = get(handles.save_dir,'String'); imagefilename = [get(handles.datafilename,'String'),'.png']; saveas(get(handles.SaveScreenshot,'Parent'),[path imagefilename]); end for kk=1:length(FluxBias) fwrite(datfile,[num2str(FluxBias(kk), '%0.6f'),char(9)]); for jj =1:PlotNLevels-1 fwrite(datfile,[num2str(EnergyLevel(kk,jj), '%0.4f'),char(9)]); end fwrite(datfile,[num2str(EnergyLevel(kk,PlotNLevels), '%0.4f'),char(9)]); fwrite(datfile,[char(13),char(10)]); end fclose(datfile); set(handles.Elapsed_time,'Visible','off'); set(handles.Remaining_time,'Visible','off'); set(handles.Exit_button,'Visible','off','Enable','off'); set(handles.info_UsrCnfrm,'Visible','off'); pause(0.5); EqGroundLevel2Zero = 0; % No GUI control if EqGroundLevel2Zero % Set the energy value of the ground level to zero temp = size(EnergyLevel); GroundLevel = (EnergyLevel(:,1) + EnergyLevel(:,2))/2; for kk =1:temp(1) EnergyLevel(:,kk) = EnergyLevel(:,kk) - GroundLevel; end EnergyLevel(:,1) = 0; end scrsz = get(0,'ScreenSize'); PlotFigHandle1 = figure('Position',[0, 100, scrsz(3)/3, scrsz(4)-200]); %'Position',[x, y, width, height] %pixels PlotAX1 = axes('parent',PlotFigHandle1); if (get(handles.DoInterp,'Value') == get(handles.DoInterp,'Max')) && length(FluxBias)>=10 % impossible to iterpolate a too short data sequence FluxBiasI = interp(FluxBias,4); % do interpolation to plot more smooth curves EnergyLevelI = zeros(length(FluxBiasI),PlotNLevels); for kk=1:PlotNLevels EnergyLevelI(:,kk) = interp1(FluxBias,EnergyLevel(:,kk),FluxBiasI,'*spline'); if Convert2microeV % convert unit 'micro-eV' plot(PlotAX1,FluxBiasI,4.1356*EnergyLevelI(:,kk)); else plot(PlotAX1,FluxBiasI,EnergyLevelI(:,kk)); end hold on; end else for kk=1:PlotNLevels if Convert2microeV % convert unit 'micro-eV' plot(PlotAX1,FluxBias,4.1356*EnergyLevel(:,kk)); else plot(PlotAX1,FluxBias,EnergyLevel(:,kk)); end hold on; end end xlabel('\Phi_e/\Phi_0','interpreter','tex','fontsize',14); if Convert2microeV % convert unit 'micro-eV' ylabel('E (\mueV)','interpreter','tex','fontsize',14); else ylabel('E (GHz)','interpreter','tex','fontsize',14); end xlim([FluxBias(1),FluxBias(end)]); if Convert2microeV % convert unit 'micro-eV' ylim([4.1356*min(EnergyLevel(:,1)),4.1356*max(EnergyLevel(:,PlotNLevels))]); else ylim([min(EnergyLevel(:,1)),max(EnergyLevel(:,PlotNLevels))]); end title('3JJ Flux Qubit Energy Levels','interpreter','tex','fontsize',14); text((FluxBias(1)+(0.5-FluxBias(1))*0.2), 0.85*EnergyLevel(1),Parameters,'fontsize',12); saveas(PlotFigHandle1,[path, filename,'_1.fig']); if max(FluxBias)<50 PlotFigHandle2 = figure('Position',[scrsz(3)/3, 100, scrsz(3)/3, scrsz(4)-200]); %'Position',[x, y, width, height] %pixels PlotAX2 = axes('parent',PlotFigHandle2); if (get(handles.DoInterp,'Value') == get(handles.DoInterp,'Max')) && length(FluxBias)>=10 % impossible to iterpolate a too short data sequence x = 1000*(FluxBiasI-0.5); if Convert2microeV % convert unit 'micro-eV' plot(PlotAX2,... x,4.1356*(EnergyLevelI(:,3)-EnergyLevelI(:,1)),'-k',... x,4.1356*(EnergyLevelI(:,3)-EnergyLevelI(:,2)),'-k',... x,4.1356*(EnergyLevelI(:,4)-EnergyLevelI(:,1)),'-k',... x,4.1356*(EnergyLevelI(:,4)-EnergyLevelI(:,2)),'-k',... x,4.1356*(EnergyLevelI(:,5)-EnergyLevelI(:,1)),'-b',... x,4.1356*(EnergyLevelI(:,5)-EnergyLevelI(:,2)),'-b',... x,4.1356*(EnergyLevelI(:,6)-EnergyLevelI(:,1)),'-b',... x,4.1356*(EnergyLevelI(:,6)-EnergyLevelI(:,2)),'-b',... x,4.1356*(EnergyLevelI(:,7)-EnergyLevelI(:,1)),'-r',... x,4.1356*(EnergyLevelI(:,7)-EnergyLevelI(:,2)),'-r',... x,4.1356*(EnergyLevelI(:,8)-EnergyLevelI(:,1)),'-r',... x,4.1356*(EnergyLevelI(:,8)-EnergyLevelI(:,2)),'-r'); hold(PlotAX2,'on'); plot(PlotAX2,... x,4.1356*(EnergyLevelI(:,3)-EnergyLevelI(:,1))/2,'--k',... x,4.1356*(EnergyLevelI(:,3)-EnergyLevelI(:,2))/2,'--k',... x,4.1356*(EnergyLevelI(:,4)-EnergyLevelI(:,1))/2,'--k',... x,4.1356*(EnergyLevelI(:,4)-EnergyLevelI(:,2))/2,'--k',... x,4.1356*(EnergyLevelI(:,5)-EnergyLevelI(:,1))/2,'--b',... x,4.1356*(EnergyLevelI(:,5)-EnergyLevelI(:,2))/2,'--b',... x,4.1356*(EnergyLevelI(:,6)-EnergyLevelI(:,1))/2,'--b',... x,4.1356*(EnergyLevelI(:,6)-EnergyLevelI(:,2))/2,'--b',... x,4.1356*(EnergyLevelI(:,7)-EnergyLevelI(:,1))/2,'--r',... x,4.1356*(EnergyLevelI(:,7)-EnergyLevelI(:,2))/2,'--r',... x,4.1356*(EnergyLevelI(:,8)-EnergyLevelI(:,1))/2,'--r',... x,4.1356*(EnergyLevelI(:,8)-EnergyLevelI(:,2))/2,'--r'); plot(PlotAX2,... x,4.1356*(EnergyLevelI(:,3)-EnergyLevelI(:,1))/3,':k',... x,4.1356*(EnergyLevelI(:,3)-EnergyLevelI(:,2))/3,':k',... x,4.1356*(EnergyLevelI(:,4)-EnergyLevelI(:,1))/3,':k',... x,4.1356*(EnergyLevelI(:,4)-EnergyLevelI(:,2))/3,':k',... x,4.1356*(EnergyLevelI(:,5)-EnergyLevelI(:,1))/3,':b',... x,4.1356*(EnergyLevelI(:,5)-EnergyLevelI(:,2))/3,':b',... x,4.1356*(EnergyLevelI(:,6)-EnergyLevelI(:,1))/3,':b',... x,4.1356*(EnergyLevelI(:,6)-EnergyLevelI(:,2))/3,':b',... x,4.1356*(EnergyLevelI(:,7)-EnergyLevelI(:,1))/3,':r',... x,4.1356*(EnergyLevelI(:,7)-EnergyLevelI(:,2))/3,':r',... x,4.1356*(EnergyLevelI(:,8)-EnergyLevelI(:,1))/3,':r',... x,4.1356*(EnergyLevelI(:,8)-EnergyLevelI(:,2))/3,':r'); ylabel('E_{12-34} (\mueV)','interpreter','tex','fontsize',14); else plot(PlotAX2,... x,(EnergyLevelI(:,3)-EnergyLevelI(:,1)),'-k',... x,(EnergyLevelI(:,3)-EnergyLevelI(:,2)),'-k',... x,(EnergyLevelI(:,4)-EnergyLevelI(:,1)),'-k',... x,(EnergyLevelI(:,4)-EnergyLevelI(:,2)),'-k',... x,(EnergyLevelI(:,5)-EnergyLevelI(:,1)),'-b',... x,(EnergyLevelI(:,5)-EnergyLevelI(:,2)),'-b',... x,(EnergyLevelI(:,6)-EnergyLevelI(:,1)),'-b',... x,(EnergyLevelI(:,6)-EnergyLevelI(:,2)),'-b',... x,(EnergyLevelI(:,7)-EnergyLevelI(:,1)),'-r',... x,(EnergyLevelI(:,7)-EnergyLevelI(:,2)),'-r',... x,(EnergyLevelI(:,8)-EnergyLevelI(:,1)),'-r',... x,(EnergyLevelI(:,8)-EnergyLevelI(:,2)),'-r'); hold(PlotAX2,'on'); plot(PlotAX2,... x,(EnergyLevelI(:,3)-EnergyLevelI(:,1))/2,'--k',... x,(EnergyLevelI(:,3)-EnergyLevelI(:,2))/2,'--k',... x,(EnergyLevelI(:,4)-EnergyLevelI(:,1))/2,'--k',... x,(EnergyLevelI(:,4)-EnergyLevelI(:,2))/2,'--k',... x,(EnergyLevelI(:,5)-EnergyLevelI(:,1))/2,'--b',... x,(EnergyLevelI(:,5)-EnergyLevelI(:,2))/2,'--b',... x,(EnergyLevelI(:,6)-EnergyLevelI(:,1))/2,'--b',... x,(EnergyLevelI(:,6)-EnergyLevelI(:,2))/2,'--b',... x,(EnergyLevelI(:,7)-EnergyLevelI(:,1))/2,'--r',... x,(EnergyLevelI(:,7)-EnergyLevelI(:,2))/2,'--r',... x,(EnergyLevelI(:,8)-EnergyLevelI(:,1))/2,'--r',... x,(EnergyLevelI(:,8)-EnergyLevelI(:,2))/2,'--r'); plot(PlotAX2,... x,(EnergyLevelI(:,3)-EnergyLevelI(:,1))/3,':k',... x,(EnergyLevelI(:,3)-EnergyLevelI(:,2))/3,':k',... x,(EnergyLevelI(:,4)-EnergyLevelI(:,1))/3,':k',... x,(EnergyLevelI(:,4)-EnergyLevelI(:,2))/3,':k',... x,(EnergyLevelI(:,5)-EnergyLevelI(:,1))/3,':b',... x,(EnergyLevelI(:,5)-EnergyLevelI(:,2))/3,':b',... x,(EnergyLevelI(:,6)-EnergyLevelI(:,1))/3,':b',... x,(EnergyLevelI(:,6)-EnergyLevelI(:,2))/3,':b',... x,(EnergyLevelI(:,7)-EnergyLevelI(:,1))/3,':r',... x,(EnergyLevelI(:,7)-EnergyLevelI(:,2))/3,':r',... x,(EnergyLevelI(:,8)-EnergyLevelI(:,1))/3,':r',... x,(EnergyLevelI(:,8)-EnergyLevelI(:,2))/3,':r'); ylabel('E_{12-34} (GHz)','interpreter','tex','fontsize',14); end else x = 1000*(FluxBias-0.5); if Convert2microeV % convert unit 'micro-eV' plot(PlotAX2,... x,4.1356*(EnergyLevel(:,3)-EnergyLevel(:,1)),'-k',... x,4.1356*(EnergyLevel(:,3)-EnergyLevel(:,2)),'-k',... x,4.1356*(EnergyLevel(:,4)-EnergyLevel(:,1)),'-k',... x,4.1356*(EnergyLevel(:,4)-EnergyLevel(:,2)),'-k',... x,4.1356*(EnergyLevel(:,5)-EnergyLevel(:,1)),'-b',... x,4.1356*(EnergyLevel(:,5)-EnergyLevel(:,2)),'-b',... x,4.1356*(EnergyLevel(:,6)-EnergyLevel(:,1)),'-b',... x,4.1356*(EnergyLevel(:,6)-EnergyLevel(:,2)),'-b',... x,4.1356*(EnergyLevel(:,7)-EnergyLevel(:,1)),'-r',... x,4.1356*(EnergyLevel(:,7)-EnergyLevel(:,2)),'-r',... x,4.1356*(EnergyLevel(:,8)-EnergyLevel(:,1)),'-r',... x,4.1356*(EnergyLevel(:,8)-EnergyLevel(:,2)),'-r'); hold(PlotAX2,'on'); plot(PlotAX2,... x,4.1356*(EnergyLevel(:,3)-EnergyLevel(:,1))/2,'--k',... x,4.1356*(EnergyLevel(:,3)-EnergyLevel(:,2))/2,'--k',... x,4.1356*(EnergyLevel(:,4)-EnergyLevel(:,1))/2,'--k',... x,4.1356*(EnergyLevel(:,4)-EnergyLevel(:,2))/2,'--k',... x,4.1356*(EnergyLevel(:,5)-EnergyLevel(:,1))/2,'--b',... x,4.1356*(EnergyLevel(:,5)-EnergyLevel(:,2))/2,'--b',... x,4.1356*(EnergyLevel(:,6)-EnergyLevel(:,1))/2,'--b',... x,4.1356*(EnergyLevel(:,6)-EnergyLevel(:,2))/2,'--b',... x,4.1356*(EnergyLevel(:,7)-EnergyLevel(:,1))/2,'--r',... x,4.1356*(EnergyLevel(:,7)-EnergyLevel(:,2))/2,'--r',... x,4.1356*(EnergyLevel(:,8)-EnergyLevel(:,1))/2,'--r',... x,4.1356*(EnergyLevel(:,8)-EnergyLevel(:,2))/2,'--r'); plot(PlotAX2,... x,4.1356*(EnergyLevel(:,3)-EnergyLevel(:,1))/3,':k',... x,4.1356*(EnergyLevel(:,3)-EnergyLevel(:,2))/3,':k',... x,4.1356*(EnergyLevel(:,4)-EnergyLevel(:,1))/3,':k',... x,4.1356*(EnergyLevel(:,4)-EnergyLevel(:,2))/3,':k',... x,4.1356*(EnergyLevel(:,5)-EnergyLevel(:,1))/3,':b',... x,4.1356*(EnergyLevel(:,5)-EnergyLevel(:,2))/3,':b',... x,4.1356*(EnergyLevel(:,6)-EnergyLevel(:,1))/3,':b',... x,4.1356*(EnergyLevel(:,6)-EnergyLevel(:,2))/3,':b',... x,4.1356*(EnergyLevel(:,7)-EnergyLevel(:,1))/3,':r',... x,4.1356*(EnergyLevel(:,7)-EnergyLevel(:,2))/3,':r',... x,4.1356*(EnergyLevel(:,8)-EnergyLevel(:,1))/3,':r',... x,4.1356*(EnergyLevel(:,8)-EnergyLevel(:,2))/3,':r'); ylabel('E_{12-34} (\mueV)','interpreter','tex','fontsize',14); else plot(PlotAX2,... x,(EnergyLevel(:,3)-EnergyLevel(:,1)),'-k',... x,(EnergyLevel(:,3)-EnergyLevel(:,2)),'-k',... x,(EnergyLevel(:,4)-EnergyLevel(:,1)),'-k',... x,(EnergyLevel(:,4)-EnergyLevel(:,2)),'-k',... x,(EnergyLevel(:,5)-EnergyLevel(:,1)),'-b',... x,(EnergyLevel(:,5)-EnergyLevel(:,2)),'-b',... x,(EnergyLevel(:,6)-EnergyLevel(:,1)),'-b',... x,(EnergyLevel(:,6)-EnergyLevel(:,2)),'-b',... x,(EnergyLevel(:,7)-EnergyLevel(:,1)),'-r',... x,(EnergyLevel(:,7)-EnergyLevel(:,2)),'-r',... x,(EnergyLevel(:,8)-EnergyLevel(:,1)),'-r',... x,(EnergyLevel(:,8)-EnergyLevel(:,2)),'-r'); hold(PlotAX2,'on'); plot(PlotAX2,... x,(EnergyLevel(:,3)-EnergyLevel(:,1))/2,'--k',... x,(EnergyLevel(:,3)-EnergyLevel(:,2))/2,'--k',... x,(EnergyLevel(:,4)-EnergyLevel(:,1))/2,'--k',... x,(EnergyLevel(:,4)-EnergyLevel(:,2))/2,'--k',... x,(EnergyLevel(:,5)-EnergyLevel(:,1))/2,'--b',... x,(EnergyLevel(:,5)-EnergyLevel(:,2))/2,'--b',... x,(EnergyLevel(:,6)-EnergyLevel(:,1))/2,'--b',... x,(EnergyLevel(:,6)-EnergyLevel(:,2))/2,'--b',... x,(EnergyLevel(:,7)-EnergyLevel(:,1))/2,'--r',... x,(EnergyLevel(:,7)-EnergyLevel(:,2))/2,'--r',... x,(EnergyLevel(:,8)-EnergyLevel(:,1))/2,'--r',... x,(EnergyLevel(:,8)-EnergyLevel(:,2))/2,'--r'); plot(PlotAX2,... x,(EnergyLevel(:,3)-EnergyLevel(:,1))/3,':k',... x,(EnergyLevel(:,3)-EnergyLevel(:,2))/3,':k',... x,(EnergyLevel(:,4)-EnergyLevel(:,1))/3,':k',... x,(EnergyLevel(:,4)-EnergyLevel(:,2))/3,':k',... x,(EnergyLevel(:,5)-EnergyLevel(:,1))/3,':b',... x,(EnergyLevel(:,5)-EnergyLevel(:,2))/3,':b',... x,(EnergyLevel(:,6)-EnergyLevel(:,1))/3,':b',... x,(EnergyLevel(:,6)-EnergyLevel(:,2))/3,':b',... x,(EnergyLevel(:,7)-EnergyLevel(:,1))/3,':r',... x,(EnergyLevel(:,7)-EnergyLevel(:,2))/3,':r',... x,(EnergyLevel(:,8)-EnergyLevel(:,1))/3,':r',... x,(EnergyLevel(:,8)-EnergyLevel(:,2))/3,':r'); ylabel('E_{12-34} (GHz)','interpreter','tex','fontsize',14); end end xlabel('(\Phi_e-0.5\Phi_0) (m\Phi_0)','interpreter','tex','fontsize',14); xlim([x(1),1000*(FluxBias(end)-0.5)]); if Convert2microeV % convert unit 'micro-eV' ylim([0,4.1356*max(EnergyLevel(:,4)-EnergyLevel(:,1))]); else ylim([0,max(EnergyLevel(:,4)-EnergyLevel(:,1))]); end saveas(PlotFigHandle2,[path, filename,'_2.fig']); PlotFigHandle3 = figure('Position',[scrsz(3)*2/3, 100,scrsz(3)/3, scrsz(4)-200]); PlotAX3 = axes('parent',PlotFigHandle3); if (get(handles.DoInterp,'Value') == get(handles.DoInterp,'Max')) && length(FluxBias)>=10 % impossible to iterpolate a too short data sequence LevelWidthI = ((EnergyLevelI(:,4)-EnergyLevelI(:,1))-(EnergyLevelI(:,3)-EnergyLevelI(:,2)))*1000; % MHz plot(PlotAX3,x,LevelWidthI); else LevelWidth = ((EnergyLevel(:,4)-EnergyLevel(:,1))-(EnergyLevel(:,3)-EnergyLevel(:,2)))*1000; % MHz plot(PlotAX3,x,LevelWidth); end xlabel('(\Phi_e-0.5\Phi_0) (m\Phi_0)','interpreter','tex','fontsize',14); ylabel('Level Width (MHz)','interpreter','tex','fontsize',14); xlim([x(1),1000*(FluxBias(end)-0.5)]); %ylim([0,max(LevelWidth)]); saveas(PlotFigHandle3,[path, filename,'_3.fig']); PlotFigHandle4 = figure('Position',[scrsz(3)*2/3, 100,scrsz(3)/3, scrsz(4)-200]); PlotAX4 = axes('parent',PlotFigHandle4); if (get(handles.DoInterp,'Value') == get(handles.DoInterp,'Max')) && length(FluxBias)>=10 % impossible to iterpolate a too short data sequence % E01 = (EnergyLevelI(:,3)+EnergyLevelI(:,4))/2 - (EnergyLevelI(:,1)+EnergyLevelI(:,2))/2; E01 = (EnergyLevelI(:,1)+EnergyLevelI(:,2))/2; Ip = 160*gradient(E01,1000*(FluxBiasI - 0.5)); % unit: nA else E01 = (EnergyLevel(:,3)+EnergyLevel(:,4))/2 - (EnergyLevel(:,1)+EnergyLevel(:,2))/2; Ip = 160*gradient(E01,1000*(FluxBias - 0.5)); % unit: nA end plot(PlotAX4,x,Ip); xlabel('\Phi_e-0.5\Phi_0 (m\Phi_0)','interpreter','tex','fontsize',14); ylabel('Ip (nA)','interpreter','tex','fontsize',14); xlim([x(1),1000*(FluxBias(end)-0.5)]); %ylim([0,max(LevelWidth)]); saveas(PlotFigHandle4,[path, filename,'_4.fig']); end if needwait pause(8); end set(handles.info_Info_disp,'String',['Done.',char(13),char(10),'Time:',... datestr(now),char(13),char(10),'To show the figures just calculated, just click [Start]'],'Visible','on'); set(handles.StartCalc,'String','Start', 'ForegroundColor',[0 0.749 0.749],'Enable','on'); set(handles.matrix_dim_check,'String','Matrix dimension check: ?',... 'ForegroundColor',[0.502 0.502 0.502]); function EL = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,FluxBias,nk,nl,nm,nlevels) % 'TriJFlxQbtEL' calculates the energy levels of a three-junction flux qubit. % Ref.: Robertson et al., Phys. Rev. Letts. B 73, 174526 (2006). % Energy Level values = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,FluxBias,nk,nl,nm,nlevels) % Example: % EL = TriJFlxQbtEL(50,1,0.63,0.15,0,0,0.5,5,10,2,20) % Energy unit: The same as Ej and Ec. % FluxBias unit:FluxQuantum % nlevels: return the energy values of the lowest n energy levels. % Author: Yulin Wu <[email protected]> % Date: 2009/5/6 % Revision: % 2011/4/30 if beta == 0 beta = 1e-6; % beta can not be zero ! however small, it always not zero in real flux qubit. end hbar=1.054560652926899e-034; PhiQ=2*pi*FluxBias; M=zeros(3,3); % M here is invert M in Phys. Rev. B 73, 174526 (2006), Eq.16. tmp=1+2*alpha; M(1,1)=1+sigma; M(1,2)=kappa/tmp; M(1,3)=2*alpha*kappa/tmp; M(2,1)=M(1,2); M(2,2)=((sigma+alpha)*(1+sigma)+2*alpha^2*(1-kappa^2+2*sigma+sigma^2))/(tmp^2*(alpha+sigma)); M(2,3)=2*alpha*(sigma+sigma^2+alpha*(kappa^2-sigma-sigma^2))/(tmp^2*(alpha+sigma)); M(3,1)=M(1,3); M(3,2)=M(2,3); M(3,3)=2*alpha^2*(2*alpha*(1+sigma)+1+4*sigma+3*sigma^2-kappa^2)/(tmp^2*(alpha+sigma)); M=4*Ec/(hbar^2*((1+sigma)^2-kappa^2))*M; tmp1=2*Ej*alpha*(1-kappa^2)*((1+sigma)*(1+2*alpha+3*sigma)-kappa^2); tmp2=Ec*beta*(1+2*alpha-kappa^2)*(alpha+sigma)*((1+sigma)^2-kappa^2); omega_t=2*Ec/hbar*sqrt(tmp1/tmp2); tmp1=hbar^2*(alpha+sigma)*((1+sigma^2)-kappa^2)*(1+2*alpha)^2; tmp2=8*Ec*alpha^2*((1+sigma)*(1+2*alpha+3*sigma)-kappa^2); m_t=tmp1/tmp2; U{1,1}=[0 0]; U{1,2}=[(1-kappa)/2 1i]; U{1,3}=[0 0]; U{1,4}=[(1+kappa)/2 -1i]; U{1,5}=[0 0]; U{2,2}=[0 0]; U{2,3}=[0 0]; U{2,4}=[0 0]; U{3,1}=[0 0]; U{3,2}=[(1+kappa)/2 1i]; U{3,3}=[0 0]; U{3,4}=[(1-kappa)/2 -1i]; U{3,5}=[0 0]; U{2,1}=[alpha*exp(1i*PhiQ)/2 -1i/alpha]; U{2,5}=[alpha*exp(-1i*PhiQ)/2 1i/alpha]; H=zeros((2*nk+1)*(2*nl+1)*(nm+1)); for k1=-nk:nk kk1=k1+nk+1; for l1=-nl:nl ll1=l1+nl+1; for m1=0:nm mm1=m1+1; for k2=-nk:nk kk2=k2+nk+1; for l2=-nl:nl ll2=l2+nl+1; for m2=0:nm mm2=m2+1; n1=(kk1-1)*(2*nl+1)*(nm+1)+(ll1-1)*(nm+1)+mm1; n2=(kk2-1)*(2*nl+1)*(nm+1)+(ll2-1)*(nm+1)+mm2; if n2<n1 H(n1,n2)=conj(H(n2,n1)); else H1=hbar^2*(k1^2*M(1,1)/2+k1*l1*M(1,2)+l1^2*M(2,2)/2)*... Kdelta(k1,k2)*Kdelta(l1,l2)*Kdelta(m1,m2); H2=-1i*sqrt((m_t*omega_t*hbar^3)/2)*(M(1,3)*k1+M(2,3)*l1)*... Kdelta(k1,k2)*Kdelta(l1,l2)*(sqrt(m2+1)*Kdelta(m2+1,m1)-sqrt(m2)*Kdelta(m2-1,m1)); tmp1=0; for p=-1:1 row=p+2; for q=-2:2 cln=q+3; if k1==p+k2 && l1==q+l2 && U{row,cln}(1)~=0 cc=U{row,cln}(2); tmp=0; tmp2=sqrt(hbar/(2*m_t*omega_t))*cc; for jj=0:min(m1,m2) tmp=tmp+factorial(jj)*nchoosek(m1,jj)*nchoosek(m2,jj)*(tmp2)^(m1+m2-2*jj); end tmp=tmp*(factorial(m1)*factorial(m2))^(-0.5)*exp(tmp2^2/2); tmp1=tmp1+U{row,cln}(1)*tmp; end end end H3=-Ej*tmp1; H4=(m1+0.5)*hbar*omega_t*Kdelta(k1,k2)*Kdelta(l1,l2)*Kdelta(m1,m2); H(n1,n2)=H1+H2+H3+H4; end end end end end end end EL=eig(H); EL(nlevels+1:end)=[]; function f=Kdelta(x1,x2) if x1==x2 f=1; else f=0; end
github
oiwic/QOS-master
TriJFlxQbtEL.m
.m
QOS-master/qos/+sqc/+simulation/fluxQubit/3JJ/NonGUIver/TriJFlxQbtEL.m
3,555
utf_8
efcd5ed209cbd8f77f6368b069b574e6
function EL = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,FluxBias,nk,nl,nm,nlevels) % 'TriJFlxQbtEL' calculates the three-junction flux qubit energy levels. % Based on the papar: Robertson et al., Phys. Rev. Letts. B 73, 174526 (2006). % Syntax % Energy Level values = TriJFlxQbtEL(Ej,Ec,alpha,beta,kappa,sigma,FluxBias,nk,nl,nm,nlevels) % Example: % EL = TriJFlxQbtEL(50,1,0.63,0.15,0,0,0.5,5,10,2,20) % Energy unit: The same as Ej and Ec. % FluxBias unit:FluxQuantum % nlevels: return the energy values of the lowest n energy levels. % Author: Yulin Wu <[email protected]/[email protected]> % Date: 2009/5/6 % Revision: % 2011/4/30 if nlevels > nk*nl*nm EL = 'ERROR: nlevels > nk*nl*nm !'; else if beta == 0 beta = 1e-6; % beta can not be zero ! end hbar=1.054560652926899e-034; PhiQ=2*pi*FluxBias; M=zeros(3,3); % M here is invert M in Phys. Rev. B 73, 174526 (2006), Eq.16. tmp=1+2*alpha; M(1,1)=1+sigma; M(1,2)=kappa/tmp; M(1,3)=2*alpha*kappa/tmp; M(2,1)=M(1,2); M(2,2)=((sigma+alpha)*(1+sigma)+2*alpha^2*(1-kappa^2+2*sigma+sigma^2))/(tmp^2*(alpha+sigma)); M(2,3)=2*alpha*(sigma+sigma^2+alpha*(kappa^2-sigma-sigma^2))/(tmp^2*(alpha+sigma)); M(3,1)=M(1,3); M(3,2)=M(2,3); M(3,3)=2*alpha^2*(2*alpha*(1+sigma)+1+4*sigma+3*sigma^2-kappa^2)/(tmp^2*(alpha+sigma)); M=4*Ec/(hbar^2*((1+sigma)^2-kappa^2))*M; tmp1=2*Ej*alpha*(1-kappa^2)*((1+sigma)*(1+2*alpha+3*sigma)-kappa^2); tmp2=Ec*beta*(1+2*alpha-kappa^2)*(alpha+sigma)*((1+sigma)^2-kappa^2); omega_t=2*Ec/hbar*sqrt(tmp1/tmp2); tmp1=hbar^2*(alpha+sigma)*((1+sigma^2)-kappa^2)*(1+2*alpha)^2; tmp2=8*Ec*alpha^2*((1+sigma)*(1+2*alpha+3*sigma)-kappa^2); m_t=tmp1/tmp2; U{1,1}=[0 0]; U{1,2}=[(1-kappa)/2 1i]; U{1,3}=[0 0]; U{1,4}=[(1+kappa)/2 -1i]; U{1,5}=[0 0]; U{2,2}=[0 0]; U{2,3}=[0 0]; U{2,4}=[0 0]; U{3,1}=[0 0]; U{3,2}=[(1+kappa)/2 1i]; U{3,3}=[0 0]; U{3,4}=[(1-kappa)/2 -1i]; U{3,5}=[0 0]; U{2,1}=[alpha*exp(1i*PhiQ)/2 -1i/alpha]; U{2,5}=[alpha*exp(-1i*PhiQ)/2 1i/alpha]; H=zeros((2*nk+1)*(2*nl+1)*(nm+1)); for k1=-nk:nk kk1=k1+nk+1; for l1=-nl:nl ll1=l1+nl+1; for m1=0:nm mm1=m1+1; for k2=-nk:nk kk2=k2+nk+1; for l2=-nl:nl ll2=l2+nl+1; for m2=0:nm mm2=m2+1; n1=(kk1-1)*(2*nl+1)*(nm+1)+(ll1-1)*(nm+1)+mm1; n2=(kk2-1)*(2*nl+1)*(nm+1)+(ll2-1)*(nm+1)+mm2; if n2<n1 H(n1,n2)=conj(H(n2,n1)); else H1=hbar^2*(k1^2*M(1,1)/2+k1*l1*M(1,2)+l1^2*M(2,2)/2)*Kdelta(k1,k2)*Kdelta(l1,l2)*Kdelta(m1,m2); H2=-1i*sqrt((m_t*omega_t*hbar^3)/2)*(M(1,3)*k1+M(2,3)*l1)*Kdelta(k1,k2)*Kdelta(l1,l2)*(sqrt(m2+1)*Kdelta(m2+1,m1)-sqrt(m2)*Kdelta(m2-1,m1)); tmp1=0; for p=-1:1 row=p+2; for q=-2:2 cln=q+3; if k1==p+k2 && l1==q+l2 && U{row,cln}(1)~=0 cc=U{row,cln}(2); tmp=0; tmp2=sqrt(hbar/(2*m_t*omega_t))*cc; for jj=0:min(m1,m2) tmp=tmp+factorial(jj)*nchoosek(m1,jj)*nchoosek(m2,jj)*(tmp2)^(m1+m2-2*jj); end tmp=tmp*(factorial(m1)*factorial(m2))^(-0.5)*exp(tmp2^2/2); tmp1=tmp1+U{row,cln}(1)*tmp; end end end H3=-Ej*tmp1; H4=(m1+0.5)*hbar*omega_t*Kdelta(k1,k2)*Kdelta(l1,l2)*Kdelta(m1,m2); H(n1,n2)=H1+H2+H3+H4; end end end end end end end EL=eig(H); EL(nlevels+1:end)=[]; end end function f=Kdelta(x1,x2) if x1==x2 f=1; else f=0; end end
github
Jann5s/BasicGDIC-master
basicgdic.m
.m
BasicGDIC-master/basicgdic.m
277,292
utf_8
2047f1c1094adfb98912478c496ff353
function varargout = basicgdic(varargin) % BASICGDIC() is a program with a graphical user interface which can be % used to perform Global Digital Image Correlation. Please see the help % which is embedded in the user interface in the <Info> tab. % % Run this file to start the program, the help is also contained in the % user interface. % % Optional: % - basicgdic(inputfile), where inputfile is a string specifying a GUI % state file as saved in section 9. This file will be loaded after % the GUI starts. % - basicgdic(D), where D is a structure as produced by the % <Guidata to D> button found in section 9. % - basicgdic(inputfile,savefile), which initates the GUI in an % invisible state (for headless computers). The input file will be % loaded, the correlation started, and the state file will be saved % in the file specified by the savefile string. % % Version: 1.0 % % Copyright 2017 Jan Neggers % This program is free software; you can redistribute it and/or modify it % under the terms of the GNU Lesser General Public License as published % by the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program 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 Lesser % General Public License for more details. % % Both the General Public License version 3 (GPLv3), and the Lesser % General Public License (LGPLv3) are supplied with this program and can % be found in the lib_bgdic folder as gpl.txt and lgpl.txt respectively. bgdicversion = 1.0; D.version = bgdicversion; % input testing headlessmode = false; if nargin == 1 inputfile = varargin{1}; elseif nargin == 2 headlessmode = true; inputfile = varargin{1}; outputfile = varargin{2}; end % Add library addpath(fullfile(pwd,'lib_bgdic')); % get the display size in pixels screensize = get(0,'screensize'); % GUI size pos.h = 700 ; % Fig height pos.w = 1200 ; % Fig width pos.x = (screensize(3)-pos.w)/2; % Fig left pos.y = (screensize(4)-pos.h)/2; % Fig bottom % define fontsizes % -------------- fontsize(1) = 9; fontsize(2) = 11; fontsize(3) = 13; fontsize(4) = 18; if ispc fontsize = fontsize - 2; fixwidthfont = 'FixedWidth'; else fontsize = fontsize - 1; fixwidthfont = 'Monospaced'; end % define colors % -------------- color.fg = [1.0, 0.4, 0.0]; color.fg2 = [0.8, 0.0, 0.5]; color.bg = [0.8, 0.8, 0.8]; color.hl = [0.6, 0.7, 1.0]; color.on = [0.0, 0.7, 0.0]; color.init = [0.7, 0.7, 0.7]; color.off = [0.9, 0.7, 0.1]; color.axeshl = [0.0, 0.0, 0.7]; color.axesfg = color.bg; color.waitbar1 = color.hl; color.waitbar2 = color.fg; color.c{1,:} = [0.8 0 0 ]; color.c{2,:} = [0.8 0 0 ]; color.c{3,:} = [0 0 0.8]; % colormaps Nc = 64; color.cmap = gray(Nc); color.cmapoverlay = parula(Nc); % color.cmapoverlay = jet(Nc); % load the defaults ini = iniread; % annoying warnings warning('off','MATLAB:hg:uicontrol:ParameterValuesMustBeValid') warning('off','MATLAB:hg:patch:RGBColorDataNotSupported') % load GUI elements % ========================================================================= % This m-file contains all the GUI elements, such as panels, controls and % axes. De default values are found in the corresponding uicontrols. The % m-file is organised according to the sections found in the gui. % The main gui layout consists of three panels, the top left panel is % constant and provides section selection. The other two panels actually % exist 9 times, one for each section. All 9 (times 2) panels are created % immediately but only one of the 9 is visible, and all other invisible. % All child objects of the panel automatically switch visibillity state % allong with their parent. This allows modifications to objects in all 9 % panels, at all times without constant re-rendering of the objects in all % panels. % Create GUI figure % ===================== if headlessmode visible = 'off'; else visible = 'on'; end H = figure('units','pixels',... 'position',[pos.x pos.y pos.w pos.h],... 'name',['basic gdic (' num2str(bgdicversion,'%3.2f') ')'],... 'numbertitle','off',... 'Color',color.bg,... 'menubar','none',... 'toolbar','none',... 'KeyPressFcn',@(H,A)keyPressFcn(H,A),... 'WindowKeyPressFcn',@(H,A)keyPressFcn(H,A),... 'WindowScrollWheelFcn',@(H,A)WindowScrollWheelFcn(H,A),... 'visible',visible,... 'Tag','BasicGDICuserinterfaces',... 'resize','on'); drawnow % Create a uipushtool in the toolbar CData = ind2rgb(reseticon,gray(255)); gcfpos = get(H,'Position'); pos.w = gcfpos(3); pos.h = gcfpos(4); set(H,'HandleVisibility','callback') % Sections % ===================== % Visible String seclabel{1,1} = 'Images'; seclabel{2,1} = 'Pattern Eval.'; seclabel{3,1} = 'ROI and Mask'; seclabel{4,1} = 'Init. Guess'; seclabel{5,1} = 'Basis'; seclabel{6,1} = 'DIC options'; seclabel{7,1} = 'Correlate'; seclabel{8,1} = 'Results'; seclabel{9,1} = 'Info'; % tooltip secttip{1,1} = 'select images'; secttip{2,1} = 'a priori pattern evaluation'; secttip{3,1} = 'region of interest and masking'; secttip{4,1} = 'initial guess'; secttip{5,1} = 'defining the basis (mesh)'; secttip{6,1} = 'dic options'; secttip{7,1} = 'starting the correlation'; secttip{8,1} = 'post processing'; secttip{9,1} = 'info, status and help'; % Create Panels % ===================== % panel positions pos.pan.margin = 10; pos.pan.width = 250; pos.pan.width3 = pos.w - (3*pos.pan.margin + pos.pan.width); pos.pan.height1 = 0.39*(pos.h-3*pos.pan.margin); pos.pan.height2 = 0.59*(pos.h-3*pos.pan.margin); pos.pan.height3 = pos.h - (2*pos.pan.margin); pos.pan.height4 = 0.02*(pos.h-3*pos.pan.margin); pos.pan1 = [pos.pan.margin 2*pos.pan.margin+pos.pan.height2+pos.pan.height4 pos.pan.width pos.pan.height1]; pos.pan2 = [pos.pan.margin pos.pan.margin pos.pan.width pos.pan.height2]; pos.pan3 = [2*pos.pan.margin+pos.pan.width pos.pan.margin pos.pan.width3 pos.pan.height3]; pos.pan4 = [pos.pan.margin 1.5*pos.pan.margin+pos.pan.height2 pos.pan.width pos.pan.height4]; % panel 1 (Sections) Hpan1 = uipanel('Title','Sections','FontSize',fontsize(2),... 'BackgroundColor',color.bg,... 'TitlePosition','lefttop',... 'Visible','On',... 'units','pixels',... 'Tag','pansections',... 'Parent',H,... 'Position',pos.pan1); % panel 2 (Submenus) for k = 1:9 if k == 9 visible = 'on'; else visible = 'off'; end Hpan2(k) = uipanel('Title',seclabel{k},'FontSize',fontsize(2),... 'BackgroundColor',color.bg,... 'TitlePosition','lefttop',... 'Visible',visible,... 'units','pixels',... 'Tag',['secpan' num2str(k)],... 'Parent',H,... 'Position',pos.pan2); end % panel 3 (Figures) for k = 1:9 if k == 9 visible = 'on'; else visible = 'off'; end Hpan3(k) = uipanel('Title',seclabel{k},'FontSize',fontsize(2),... 'BackgroundColor',color.bg,... 'TitlePosition','lefttop',... 'Visible',visible,... 'units','pixels',... 'Tag',['figpan' num2str(k)],... 'Parent',H,... 'Position',pos.pan3); end % Waitbar axes('FontSize',fontsize(2),... 'Color',color.bg,... 'Box','On',... 'XTick',[],... 'YTick',[],... 'XColor',color.axesfg,... 'YColor',color.axesfg,... 'Xlim',[0 1],... 'Ylim',[0 1],... 'Visible','On',... 'units','pixels',... 'Tag','waitbar',... 'Parent',H,... 'Position',pos.pan4); % Create Section Buttons % ===================== pos.but.x = 0.2; pos.but.y = linspace(0.90,0.05,9); pos.but.width = 0.7; pos.but.height = 0.08; for k = 1:9 if k == 9 bgcolor = color.hl; else bgcolor = color.bg; end % column panel button 1 (Input) Hbut(k) = uicontrol('String',seclabel{k},... 'ToolTipString',secttip{k},... 'Style','pushbutton',... 'BackgroundColor',bgcolor,... 'units','normalized',... 'Position',[pos.but.x pos.but.y(k) pos.but.width pos.but.height],... 'FontSize',fontsize(3),... 'HorizontalAlignment','left',... 'Tag',['secbut' num2str(k)],... 'Parent',Hpan1,... 'call',{@secbutton,H,k}); end % Create Section Indicators (squares in front) % ===================== pos.but.indx = 0.07; pos.but.indwidth = 0.1; for k = 1:9 % column panel button 1 (Input) Hind(k) = uicontrol('String',num2str(k),... 'ToolTipString','not ready',... 'Style','text',... 'BackgroundColor',color.init,... 'units','normalized',... 'Position',[pos.but.indx pos.but.y(k) pos.but.indwidth pos.but.height],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag',['secind' num2str(k)],... 'Parent',Hpan1); if any(k == [1,3,5,7]) set(Hind(k),'BackgroundColor',color.off) end end % ======================================================================== % Section 1: Load images % ======================================================================== pos.sec1.x1 = 0.05; pos.sec1.x2 = 0.5; pos.sec1.y = linspace(0.92,0.02,17); pos.sec1.w1 = 0.3; pos.sec1.w2 = 0.2; pos.sec1.w3 = 0.45; pos.sec1.w4 = 0.9; pos.sec1.h1 = 0.048; pos.sec1.h2 = 0.75; pos.sec1.x3 = pos.sec1.x1+0.2; pos.sec1.w5 = 0.18; pos.sec1.w6 = pos.sec1.w4-0.2; uicontrol('String','Add files',... 'ToolTipString','opens a file selection dialogue',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(1) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','fileadd',... 'Parent',Hpan2(1),... 'call',{@fileadd,H}); uicontrol('String','Remove files',... 'ToolTipString','removes selected files',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(2) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','filedel',... 'Parent',Hpan2(1),... 'call',{@filedel,H}); uicontrol('String','Up',... 'ToolTipString','move selected files up',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(3) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','fileup',... 'Parent',Hpan2(1),... 'call',{@fileup,H}); uicontrol('String','Down',... 'ToolTipString','move selected files down',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(3) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','filedown',... 'Parent',Hpan2(1),... 'call',{@filedown,H}); uicontrol('String',{''},... 'Style','listbox',... 'units','normalized',... 'BackgroundColor','w',... 'Position',[pos.sec1.x1 pos.sec1.y(end) pos.sec1.w4 pos.sec1.h2],... 'FontSize',fontsize(3),... 'Tag','filelist',... 'Parent',Hpan2(1),... 'call',{@fileselect,H}); % Populate figure panel (section 1) pos.fig.x1 = 0.05; pos.fig.x2 = 0.14; pos.fig.x3 = 0.89; pos.fig.y1 = 0.01; pos.fig.y2 = 0.1; pos.fig.w1 = 0.08; pos.fig.w2 = 0.84; pos.fig.w4 = 0.9; pos.fig.h1 = 0.03; pos.fig.h2 = 0.85; uicontrol('String','1',... 'ToolTipString','image id',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.fig.x1 pos.fig.y1 pos.fig.w1 pos.fig.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','imageid',... 'call',{@imageid,H},... 'Parent',Hpan3(1)); uicontrol('Style','slider',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.fig.x2 pos.fig.y1 pos.fig.w2 pos.fig.h1],... 'Tag','imageslider',... 'Min',1,... 'Max',2,... 'Sliderstep',[0.01 0.1],... 'Value',1,... 'call',{@imageslider,H},... 'Parent',Hpan3(1)); axes('Parent',Hpan3(1),... 'Position',[pos.fig.x1 pos.fig.y2 pos.fig.w4 pos.fig.h2],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes1',... 'FontSize',fontsize(2)); % ======================================================================== % Section 2: Pattern Eval % ======================================================================== axes('Parent',Hpan3(2),... 'Position',[pos.fig.x1 pos.fig.y2 pos.fig.w4 pos.fig.h2],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes2',... 'FontSize',fontsize(2)); axes('Parent',Hpan2(2),... 'Position',[pos.sec1.x1+0.05 pos.sec1.y(end)+0.05 pos.sec1.w4-0.05 4*pos.sec1.h1],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes2hist',... 'FontSize',fontsize(2)); uicontrol('String','1',... 'ToolTipString','image id',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.fig.x1 pos.fig.y1 pos.fig.w1 pos.fig.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','patid',... 'call',{@patid,H},... 'Parent',Hpan3(2)); uicontrol('Style','slider',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.fig.x2 pos.fig.y1 pos.fig.w2 pos.fig.h1],... 'Tag','patslider',... 'Min',1,... 'Max',2,... 'Sliderstep',[0.01 0.1],... 'Value',1,... 'call',{@patslider,H},... 'Parent',Hpan3(2)); uicontrol('String','Evaluate',... 'ToolTipString','evaluate the pattern (takes time)',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(1) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','patarea',... 'Parent',Hpan2(2),... 'call',{@pateval,H}); uicontrol('String','Show Pattern',... 'ToolTipString','Show the pattern, with the correlation lenght distribution',... 'Style','pushbutton',... 'BackgroundColor',color.hl,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(2) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','patshowpat',... 'Parent',Hpan2(2),... 'call',{@patshowpat,H}); uicontrol('String','Show ACF',... 'ToolTipString','Show the Auto Correlation Function, with the average correlation contour',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(3) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','patshowACF',... 'Parent',Hpan2(2),... 'call',{@patshowACF,H}); % ======================================================================== % Section 3: ROI and Mask % ======================================================================== axes('Parent',Hpan3(3),... 'Position',[pos.fig.x1 pos.fig.y2 pos.fig.w4 pos.fig.h2],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes3',... 'FontSize',fontsize(2)); uicontrol('String','1',... 'ToolTipString','image id',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.fig.x1 pos.fig.y1 pos.fig.w1 pos.fig.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','roiid',... 'call',{@roiid,H},... 'Parent',Hpan3(3)); uicontrol('Style','slider',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.fig.x2 pos.fig.y1 pos.fig.w2 pos.fig.h1],... 'Tag','roislider',... 'Min',1,... 'Max',2,... 'Sliderstep',[0.01 0.1],... 'Value',1,... 'call',{@roislider,H},... 'Parent',Hpan3(3)); uicontrol('String','Set ROI',... 'ToolTipString','position the region of interest rectangle',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(1) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','roiset',... 'Parent',Hpan2(3),... 'call',{@roiset,H}); uicontrol('String','Masking',... 'Style','text',... 'FontWeight','bold',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(3) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(3)); masktools{1,1} = 'rect'; masktools{2,1} = 'ellipse'; masktools{3,1} = 'polygon'; masktools{4,1} = 'bspline'; masktools{5,1} = 'spot 5px'; masktools{6,1} = 'spot 10px'; masktools{7,1} = 'spot 50px'; uicontrol('String',masktools,... 'ToolTipString','select a mask shape',... 'Style','popupmenu',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(4) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','masktool',... 'Parent',Hpan2(3)); uicontrol('String','Add',... 'ToolTipString','select pixels to add to the mask',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(5) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','maskadd',... 'Parent',Hpan2(3),... 'call',{@maskset,H,'add'}); uicontrol('String','Del',... 'ToolTipString','select pixels to delete from the mask',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(5) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','maskdel',... 'Parent',Hpan2(3),... 'call',{@maskset,H,'del'}); uicontrol('String','Intersect',... 'ToolTipString','intersection with selected pixels and the mask',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(6) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','maskintersect',... 'Parent',Hpan2(3),... 'call',{@maskset,H,'intersect'}); uicontrol('String','Invert',... 'ToolTipString','invert the mask',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(6) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','maskinvert',... 'Parent',Hpan2(3),... 'call',{@maskinvert,H}); uicontrol('String','Clear',... 'ToolTipString','clear the entire mask',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(7) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','maskclear',... 'Parent',Hpan2(3),... 'call',{@maskclear,H}); uicontrol('String','Save',... 'ToolTipString','save mask to file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','masksave',... 'Parent',Hpan2(3),... 'call',{@masksave,H}); uicontrol('String','Load',... 'ToolTipString','load mask from file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','maskload',... 'Parent',Hpan2(3),... 'call',{@maskload,H}); % ======================================================================== % Section 4: Init. Guess % ======================================================================== w = 0.94*pos.fig.w4/2; h = 0.94*pos.fig.h2/2; s = 0.08; % 2014b feature % 'Clipping','on',... % 'ClippingStyle','rectangle',... % 'ClippingStyle','3dbox',... axes('Parent',Hpan3(4),... 'Position',[pos.fig.x1 pos.fig.y2+h+s w h],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes41',... 'FontSize',fontsize(2)); axes('Parent',Hpan3(4),... 'Position',[pos.fig.x1+w+s pos.fig.y2+h+s w h],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes42',... 'FontSize',fontsize(2)); axes('Parent',Hpan3(4),... 'Position',[pos.fig.x1 pos.fig.y2 w h],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes43',... 'FontSize',fontsize(2)); axes('Parent',Hpan3(4),... 'Position',[pos.fig.x1+w+s pos.fig.y2 w h],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes44',... 'FontSize',fontsize(2)); uicontrol('String','1',... 'ToolTipString','image id',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.fig.x1 pos.fig.y1 pos.fig.w1 pos.fig.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','iguessid',... 'call',{@iguessid,H},... 'Parent',Hpan3(4)); uicontrol('Style','slider',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.fig.x2 pos.fig.y1 pos.fig.w2 pos.fig.h1],... 'Tag','iguessslider',... 'Min',1,... 'Max',2,... 'Sliderstep',[0.01 0.1],... 'Value',1,... 'call',{@iguessslider,H},... 'Parent',Hpan3(4)); % 5. Image processing uicontrol('String','Image Processing',... 'ToolTipString','create processed images',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(1) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessimprocess',... 'Parent',Hpan2(4),... 'call',{@iguessimprocess,H}); uicontrol('String','Blur',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(2) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(4)); uicontrol('String',ini.iguessblur.value,... 'ToolTipString','gaussian blur radius [px]',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(2) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessblur',... 'Parent',Hpan2(4)); uicontrol('String','Im. process',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(3) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(4)); improcesstype{1,1} = 'none'; improcesstype{2,1} = 'grad|xy|'; improcesstype{3,1} = 'grad|x|'; improcesstype{4,1} = 'grad|y|'; improcesstype{5,1} = 'grad(xy)'; improcesstype{6,1} = 'grad(x)'; improcesstype{7,1} = 'grad(y)'; uicontrol('String',improcesstype,... 'ToolTipString','process the image',... 'Style','popupmenu',... 'Value',ini.iguessimprocesstype.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(3) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessimprocesstype',... 'Parent',Hpan2(4)); % 5. Auto Iguess uicontrol('String','Add auto',... 'ToolTipString','apply a local (FFT) algorithm to obtain the initial guess',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(6) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessaddauto',... 'Parent',Hpan2(4),... 'call',{@iguessaddauto,H}); % 5. Manual Iguess uicontrol('String','Add manual',... 'ToolTipString','add a initial guess point manually',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(7) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessaddmanual',... 'Parent',Hpan2(4),... 'call',{@iguessaddmanual,H}); uicontrol('String','zoomselect',... 'Style','checkbox',... 'Value',ini.iguesszoomselect.value,... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(8) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguesszoomselect',... 'Parent',Hpan2(4)); uicontrol('String',ini.iguesszoomsize.value,... 'ToolTipString','zone of interest (subset) size',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(8) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguesszoomsize',... 'Parent',Hpan2(4)); % Delete uicontrol('String','Delete',... 'Style','text',... 'FontWeight','bold',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(10) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(4)); pos.sec1.wb = (pos.sec1.w4/3) - 0.01; pos.sec1.xb(1) = pos.sec1.x1; pos.sec1.xb(2) = pos.sec1.x1 + 1*pos.sec1.wb + 1*0.01; pos.sec1.xb(3) = pos.sec1.x1 + 2*pos.sec1.wb + 2*0.01; uicontrol('String','One',... 'ToolTipString','select one point to delete',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(1) pos.sec1.y(11) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessdelone',... 'Parent',Hpan2(4),... 'call',{@iguessdelone,H}); uicontrol('String','Area',... 'ToolTipString','clear the initial guess in an area',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(2) pos.sec1.y(11) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessdelbox',... 'Parent',Hpan2(4),... 'call',{@iguessdelbox,H}); uicontrol('String','All',... 'ToolTipString','clear the initial guess',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(3) pos.sec1.y(11) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessdelall',... 'Parent',Hpan2(4),... 'call',{@iguessdelall,H}); % This Frame uicontrol('String','Single frame operations',... 'Style','text',... 'FontWeight','bold',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(13) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(4)); uicontrol('String','Zero',... 'ToolTipString','Set all initial guess points to zero for this frame',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(1) pos.sec1.y(14) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessdelone',... 'Parent',Hpan2(4),... 'call',{@iguessframezero,H}); uicontrol('String','Auto',... 'ToolTipString','Perform the auto initial guess for this frame only',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(2) pos.sec1.y(14) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessdelbox',... 'Parent',Hpan2(4),... 'call',{@iguessframeauto,H}); uicontrol('String','Interpolate',... 'ToolTipString','interpolate (in time) the displacements of each iguess point in this frame based on the other frames',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(3) pos.sec1.y(14) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessdelall',... 'Parent',Hpan2(4),... 'call',{@iguessframeint,H}); uicontrol('String','Save',... 'ToolTipString','save initial guess to file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguesssave',... 'Parent',Hpan2(4),... 'call',{@iguesssave,H}); uicontrol('String','Load',... 'ToolTipString','load initialguess from file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','iguessload',... 'Parent',Hpan2(4),... 'call',{@iguessload,H}); % ======================================================================== % Section 5: Basis % ======================================================================== uicontrol('String','1',... 'ToolTipString','basis function id',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.fig.x1 pos.fig.y1 pos.fig.w1 pos.fig.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','phiid',... 'call',{@phiid,H},... 'Parent',Hpan3(5)); uicontrol('Style','slider',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.fig.x2 pos.fig.y1 pos.fig.w2 pos.fig.h1],... 'Tag','phislider',... 'Min',1,... 'Max',2,... 'Sliderstep',[0.01 0.1],... 'Value',1,... 'call',{@phislider,H},... 'Parent',Hpan3(5)); axes('Parent',Hpan3(5),... 'Position',[pos.fig.x1 pos.fig.y2 pos.fig.w4 pos.fig.h2],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes4',... 'FontSize',fontsize(2)); % Basis Selector % =================== uicontrol('String',{'basis 1';'basis 2';'basis 3';'basis 4'},... 'ToolTipString','select the basis to show or (re)define',... 'Value',1,... 'Style','listbox',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(4) pos.sec1.w4 4.5*pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basislist',... 'call',{@basislist,H},... 'Parent',Hpan2(5)); uicontrol('String','New',... 'ToolTipString','add a new basis',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(1) pos.sec1.y(5) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basisnew',... 'Parent',Hpan2(5),... 'call',{@basisnew,H}); uicontrol('String','Del',... 'ToolTipString','delete this basis',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(2) pos.sec1.y(5) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basisdel',... 'Parent',Hpan2(5),... 'call',{@basisdel,H}); uicontrol('String','Dupl.',... 'ToolTipString','duplicate this bases',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(3) pos.sec1.y(5) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basisduplicate',... 'Parent',Hpan2(5),... 'call',{@basisduplicate,H}); basistypes{1,1} = 'Polynomial'; basistypes{2,1} = 'Harmonic'; basistypes{3,1} = 'Zernike'; basistypes{4,1} = 'B-Spline'; basistypes{5,1} = 'FEM Triangle (a)'; basistypes{6,1} = 'FEM Triangle (b)'; basistypes{7,1} = 'FEM Quad'; uicontrol('String',basistypes,... 'ToolTipString','basis type (shape function family)',... 'Value',ini.basistype.value,... 'Style','popupmenu',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(7) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basistype',... 'call',{@basistype,H},... 'Parent',Hpan2(5)); uicontrol('String','Basis name',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(8) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(5)); uicontrol('String','basis 1',... 'ToolTipString','descriptive name for this basis set',... 'Style','edit',... 'Enable','On',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(8) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basisname',... 'Parent',Hpan2(5)); uicontrol('String','Boundary ratio',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(9) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(5)); uicontrol('String',ini.basisboundary.value,... 'ToolTipString','size ratio of boundary elements with respect to internal elements',... 'Style','edit',... 'Enable','Off',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(9) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basisboundary',... 'Parent',Hpan2(5)); uicontrol('String','Rows',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(10) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(5)); uicontrol('String',ini.basisrows.value,... 'ToolTipString','number of "nodes/knots" along the x-direction',... 'Style','edit',... 'Enable','off',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(10) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basisrows',... 'Parent',Hpan2(5)); uicontrol('String','Cols',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(11) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(5)); uicontrol('String',ini.basiscols.value,... 'ToolTipString','number of "nodes/knots" along the y-direction',... 'Style','edit',... 'Enable','off',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(11) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basiscols',... 'Parent',Hpan2(5)); uicontrol('String','Order',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(12) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(5)); uicontrol('String',ini.basisorder.value,... 'ToolTipString','polynomial order',... 'Style','edit',... 'Enable','On',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(12) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basisorder',... 'Parent',Hpan2(5)); uicontrol('String','Define Basis',... 'ToolTipString','Generate the basis',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(13) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'call',{@basisbuild,H},... 'Tag','basisdefine',... 'Parent',Hpan2(5)); % ================= uicontrol('String',ini.basissoften.value,... 'Style','edit',... 'Enable','inactive',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-2) pos.sec1.w5 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basissoften',... 'Parent',Hpan2(5)); uicontrol('Style','slider',... 'ToolTipString','soften the pattern',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x3 pos.sec1.y(end-2) pos.sec1.w6 pos.sec1.h1],... 'Tag','basissoftenslider',... 'Min',0,... 'Max',1,... 'Sliderstep',[0.01 0.1],... 'Value',str2double(ini.basissoften.value),... 'call',{@plotbasis,H},... 'Parent',Hpan2(5)); uicontrol('String',ini.basisalpha.value,... 'Style','edit',... 'Enable','inactive',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-1) pos.sec1.w5 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basisalpha',... 'Parent',Hpan2(5)); uicontrol('Style','slider',... 'ToolTipString','overlay transparancy',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x3 pos.sec1.y(end-1) pos.sec1.w6 pos.sec1.h1],... 'Tag','basisalphaslider',... 'Min',0,... 'Max',1,... 'Sliderstep',[0.01 0.1],... 'Value',str2double(ini.basisalpha.value),... 'call',{@plotbasis,H},... 'Parent',Hpan2(5)); % Save / Load uicontrol('String','Save',... 'ToolTipString','save basis to file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basissave',... 'Parent',Hpan2(5),... 'call',{@basissave,H}); uicontrol('String','Load',... 'ToolTipString','load basis from file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','basisload',... 'Parent',Hpan2(5),... 'call',{@basisload,H}); % ======================================================================== % Section 6: DIC Options % ======================================================================== w7 = 0.15; uicontrol('String','Dimen.',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(1) pos.sec1.w3-w7 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); dimensions{1,1} = '2D'; dimensions{2,1} = 'Quasi 3D'; uicontrol('String',dimensions,... 'ToolTipString','2D analysis or 3D surface analysis',... 'Style','popupmenu',... 'Value',ini.dicdimensions.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2-w7 pos.sec1.y(1) pos.sec1.w3+w7 pos.sec1.h1],... 'FontSize',fontsize(2),... 'Tag','dicdimensions',... 'Parent',Hpan2(6),... 'call',{@dicdimensions,H}); uicontrol('String','Relax.',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(2) pos.sec1.w3-w7 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); uicontrol('String',{'none','constant','linear','quadratic','cubic'},... 'ToolTipString','relax the brightness conservation equation, each level adds a field to be solved (deal with grayvalue intensity changes)',... 'Style','popupmenu',... 'Value',ini.dicrelaxation.value,... 'Enable','on',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2-w7 pos.sec1.y(2) pos.sec1.w3+w7 pos.sec1.h1],... 'FontSize',fontsize(2),... 'Tag','dicrelaxation',... 'Parent',Hpan2(6),... 'call',{@dicrelaxation,H}); dicrelbasis = {'same as U';'basis 1';'basis 2';'basis 3';'basis 4'}; uicontrol('String','Rel. Basis',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(3) pos.sec1.w3-w7 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); uicontrol('String',dicrelbasis,... 'ToolTipString','Choose a basis to use for the relaxed brightness (and contrast) fields',... 'Style','popupmenu',... 'Value',min([5 ini.dicrelbasis.value]),... 'Enable','on',... 'BackgroundColor','w',... 'units','normalized',... 'enable','off',... 'Position',[pos.sec1.x2-w7 pos.sec1.y(3) pos.sec1.w3+w7 pos.sec1.h1],... 'FontSize',fontsize(2),... 'Tag','dicrelbasis',... 'Parent',Hpan2(6)); uicontrol('String','Conv. Cr.',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(4) pos.sec1.w3-w7 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); dicconvparam{1,1} = 'change in disp.'; dicconvparam{2,1} = 'right hand member'; dicconvparam{3,1} = 'update in dof'; dicconvparam{4,1} = 'change in residual'; uicontrol('String',dicconvparam,... 'ToolTipString','convergence parameter',... 'Style','popupmenu',... 'Value',ini.dicconvparam.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2-w7 pos.sec1.y(4) pos.sec1.w3+w7 pos.sec1.h1],... 'FontSize',fontsize(2),... 'Tag','dicconvparam',... 'Parent',Hpan2(6)); uicontrol('String','Best iter.',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(5) pos.sec1.w3-w7 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); bestitparam{1,1} = 'residual'; bestitparam{2,1} = 'change in disp.'; bestitparam{3,1} = 'right hand member'; bestitparam{4,1} = 'update in dof'; bestitparam{5,1} = 'change in residual'; bestitparam{6,1} = 'last it.'; uicontrol('String',bestitparam,... 'ToolTipString','Use the best known iteration instead of the last (based on:)',... 'Style','popupmenu',... 'Value',ini.dicbestit.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2-w7 pos.sec1.y(5) pos.sec1.w3+w7 pos.sec1.h1],... 'FontSize',fontsize(2),... 'Tag','dicbestit',... 'Parent',Hpan2(6)); uicontrol('String','Max div.',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(6) pos.sec1.w3-w7 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); uicontrol('String',ini.dicmaxdiv.value,... 'ToolTipString','stop after N diverging steps (based on the residual)',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2-w7 pos.sec1.y(6) pos.sec1.w3+w7 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','dicmaxdiv',... 'Parent',Hpan2(6)); % incremental initial guess uicontrol('String','Init.',... 'Style','text',... 'Value',1,... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(7) pos.sec1.w3-w7 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); inciguess{1,1} = 'zero'; inciguess{2,1} = 'init. guess'; inciguess{3,1} = 'prev. inc.'; inciguess{4,1} = 'prev. inc. and init. guess'; inciguess{5,1} = 'reuse'; uicontrol('String',inciguess,... 'ToolTipString','what to use for initial guess for the next increment',... 'Style','popupmenu',... 'Value',ini.dicinciguess.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2-w7 pos.sec1.y(7) pos.sec1.w3+w7 pos.sec1.h1],... 'FontSize',fontsize(2),... 'Tag','dicinciguess',... 'Parent',Hpan2(6)); uicontrol('String','Total',... 'ToolTipString','the "Total Lagrange" method compares each image to the first image',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1+0.2 pos.sec1.y(9) pos.sec1.w3-0.1 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); uicontrol('String','Updated',... 'ToolTipString','the "Updated Lagrange" method compares each image to back-deformed version of the previous image',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','right',... 'units','normalized',... 'Position',[pos.sec1.x2+0.1 pos.sec1.y(9) pos.sec1.w3-0.1 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); uicontrol('String',ini.diclagrange.value,... 'Style','edit',... 'Enable','inactive',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(10) 0.18 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','diclagrange',... 'Parent',Hpan2(6)); uicontrol('Style','slider',... 'ToolTipString','Shift between the "Total Lagrange" (accurate) or the "Updated Lagrange" (robust) method',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1+0.2 pos.sec1.y(10) pos.sec1.w4-0.2 pos.sec1.h1],... 'Tag','diclagrangeslider',... 'Min',0,... 'Max',1,... 'Sliderstep',[0.01 0.1],... 'Value',str2double(ini.diclagrange.value),... 'call',{@diclagrangeslider,H},... 'Parent',Hpan2(6)); uicontrol('String','Auto save',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-4) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); uicontrol('String',{'0';'1'},... 'ToolTipString','save the correlation results after each increment',... 'Style','popupmenu',... 'Value',ini.dicautosave.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end-4) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','dicautosave',... 'Parent',Hpan2(6)); uicontrol('String','Mem. save',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-3) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); uicontrol('String',{'0';'1';'2'},... 'ToolTipString','reduce memory requirement, (0 = full L matrix in memory, 1 = L matrix per dimension, 2 = L matrix per dof)',... 'Style','popupmenu',... 'Value',ini.dicmemsave.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end-3) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','dicmemsave',... 'Parent',Hpan2(6)); uicontrol('String','Precision',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-2) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); uicontrol('String',{'single';'double'},... 'ToolTipString','use single (32 bit) or double (64 bit) precision floating point matrices (single disables sparse matrices)',... 'Style','popupmenu',... 'Value',ini.dicprecision.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end-2) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','dicprecision',... 'Parent',Hpan2(6)); uicontrol('String','use GPU',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-1) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(6)); uicontrol('String',{'0';'1'},... 'ToolTipString','Use the Graphics card for the correlation computations (requires CUDA capable GPU, see help gpuDevice)',... 'Style','popupmenu',... 'Value',ini.dicusegpu.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end-1) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','dicusegpu',... 'Parent',Hpan2(6)); uicontrol('String','Save',... 'ToolTipString','save dic options to file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','dicsave',... 'Parent',Hpan2(6),... 'call',{@dicsave,H}); uicontrol('String','Load',... 'ToolTipString','load dic options from file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','dicload',... 'Parent',Hpan2(6),... 'call',{@dicload,H}); cgtypes{1,1} = 'Preparation'; cgtypes{2,1} = 'Preparation'; cgtypes{3,1} = 'Preparation'; cgtypes{4,1} = 'Final'; cgstr{1,1} = 'prepA'; cgstr{2,1} = 'prepB'; cgstr{3,1} = 'prepC'; cgstr{4,1} = 'final'; pos.cgx = linspace(10,pos.pan3(3)-10,5); pos.cgy = 10; pos.cgh = min([451 pos.pan3(4)]); pos.cgw = diff(pos.cgx(1:2))-5; pos.cg(1,:) = [pos.cgx(1) pos.cgy pos.cgw pos.cgh]; pos.cg(2,:) = [pos.cgx(2) pos.cgy pos.cgw pos.cgh]; pos.cg(3,:) = [pos.cgx(3) pos.cgy pos.cgw pos.cgh]; pos.cg(4,:) = [pos.cgx(4) pos.cgy pos.cgw pos.cgh]; dicgradient{1,1} = 'auto'; dicgradient{2,1} = 'gradfg'; dicgradient{3,1} = 'gradf'; dicgradient{4,1} = 'gradg'; % ======================================================================== for k = 1:4 % Create CG settings panels % ===================== Hcgpan(k) = uipanel('Title',cgtypes{k},'FontSize',fontsize(2),... 'BackgroundColor',color.bg,... 'TitlePosition','centertop',... 'Visible','on',... 'units','pixels',... 'Tag',['cgpan' num2str(k)],... 'Parent',Hpan3(6),... 'Position',pos.cg(k,:)); if k <= 3 % Enabled? if ini.([cgstr{k} 'on']).value == 1 cgAon = true; cgAoff = false; enabled = 'on'; else cgAon = false; cgAoff = true; enabled = 'off'; end % Create CG controls % ===================== uicontrol('String','On',... 'ToolTipString','switch current coarse grain step on',... 'Style','togglebutton',... 'Value',cgAon,... 'BackgroundColor',color.hl,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(1) pos.sec1.w3 1.5*pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'on'],... 'Parent',Hcgpan(k),... 'call',{@cgon,H,k}); uicontrol('String','Off',... 'ToolTipString','switch current coarse grain step off',... 'Style','togglebutton',... 'Value',cgAoff,... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(1) pos.sec1.w3 1.5*pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'off'],... 'Parent',Hcgpan(k),... 'call',{@cgoff,H,k}); end uicontrol('String','Blur',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(3) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',ini.([cgstr{k} 'blur']).value,... 'ToolTipString','gaussian blur radius [px]',... 'Style','edit',... 'BackgroundColor','w',... 'Units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(3) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'blur'],... 'Parent',Hcgpan(k)); uicontrol('String','Coarsegrain',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(4) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',ini.([cgstr{k} 'level']).value,... 'ToolTipString','coarse grain N times (i.e. superpixel size 2^N)',... 'Style','edit',... 'BackgroundColor','w',... 'Units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(4) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'level'],... 'Parent',Hcgpan(k)); uicontrol('String','Im. process',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(5) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',improcesstype,... 'ToolTipString','process the image',... 'Style','popupmenu',... 'Value',ini.([cgstr{k} 'improcess']).value,... 'BackgroundColor','w',... 'units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(5) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'improcess'],... 'Parent',Hcgpan(k)); uicontrol('String','Basis',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(7) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',{'basis 1';'basis 2';'basis 3';'basis 4'},... 'ToolTipString','select the basis used for this cg step',... 'Style','popupmenu',... 'Value',min([4 ini.([cgstr{k} 'basis']).value]),... 'BackgroundColor','w',... 'units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(7) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'basis'],... 'Parent',Hcgpan(k)); uicontrol('String','Convcrit.',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(8) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',ini.([cgstr{k} 'convcrit']).value,... 'ToolTipString','convergation criteria',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(8) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'convcrit'],... 'Parent',Hcgpan(k)); uicontrol('String','Maxit.',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(9) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',ini.([cgstr{k} 'maxit']).value,... 'ToolTipString','maximum number of iteration (per cg step)',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(9) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'maxit'],... 'Parent',Hcgpan(k)); uicontrol('String','Im. gradient',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(10) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',dicgradient,... 'ToolTipString','image gradient to apply, gradf is faster for small deformation cases, gradfg is more robust (uses 0.5(gradf+gradg))',... 'Style','popupmenu',... 'Value',ini.([cgstr{k} 'gradient']).value,... 'BackgroundColor','w',... 'units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(10) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'gradient'],... 'Parent',Hcgpan(k)); % Tikhonov uicontrol('String','Tikhonov Regularization',... 'Style','text',... 'FontWeight','bold',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(12) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String','aplha(1)',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(13) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',ini.([cgstr{k} 'tikhpar1']).value,... 'ToolTipString','Tikhonov parameter (alpha) at the first iteration (relative to the largest eigenvalue of M)',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(13) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'tikhpar1'],... 'Parent',Hcgpan(k)); uicontrol('String','aplha(2)',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(14) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',ini.([cgstr{k} 'tikhpar2']).value,... 'ToolTipString','Tikhonov parameter (alpha) at the last Tikhonov iteration (relative to the largest eigenvalue of M)',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(14) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'tikhpar2'],... 'Parent',Hcgpan(k)); uicontrol('String','steps',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(15) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hcgpan(k)); uicontrol('String',ini.([cgstr{k} 'tikhsteps']).value,... 'ToolTipString','Change the Tikhonov parameter from alpha(1) to alpha(2) in N steps, set 0 to disable Tikhonov regularizatoin',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Enable',enabled,... 'Position',[pos.sec1.x2 pos.sec1.y(15) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag',[cgstr{k} 'tikhsteps'],... 'Parent',Hcgpan(k)); end % ======================================================================== % ======================================================================== % Section 7: Correlate % ======================================================================== axes('Parent',Hpan3(7),... 'Position',[pos.fig.x1 pos.fig.y2 pos.fig.w4 pos.fig.h2],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes7',... 'FontSize',fontsize(2)); uicontrol('String','0',... 'ToolTipString','image id',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.fig.x1 pos.fig.y1 pos.fig.w1 pos.fig.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','corid',... 'call',{@corid,H},... 'Parent',Hpan3(7)); uicontrol('Style','slider',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.fig.x2 pos.fig.y1 pos.fig.w2 pos.fig.h1],... 'Tag','corslider',... 'Min',0,... 'Max',1,... 'Sliderstep',[0.01 0.1],... 'Value',1,... 'call',{@corslider,H},... 'Parent',Hpan3(7)); % Go, Continue, Stop uicontrol('String','Go',... 'ToolTipString','start the correlation process',... 'Style','togglebutton',... 'Value',0,... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(1) pos.sec1.y(1) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','corgo',... 'Parent',Hpan2(7),... 'call',{@corgo,H}); uicontrol('String','Continue',... 'ToolTipString','force convergence on the current cg step, continue to the next',... 'Style','togglebutton',... 'Value',0,... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(2) pos.sec1.y(1) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','corcontinue',... 'Parent',Hpan2(7)); uicontrol('String','Stop',... 'ToolTipString','stop the correlation process (please wait for the command to be processed)',... 'Style','togglebutton',... 'Value',1,... 'BackgroundColor',color.hl,... 'units','normalized',... 'Position',[pos.sec1.xb(3) pos.sec1.y(1) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','corstop',... 'Parent',Hpan2(7),... 'call',{@corstop,H}); % Clear one, all uicontrol('String','Clear One',... 'ToolTipString','clear the correlation results of the current increment',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(1) pos.sec1.y(2) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','corclearinc',... 'Parent',Hpan2(7),... 'call',{@corclearinc,H}); uicontrol('String','Clear All',... 'ToolTipString','clear correlation results, start fresh',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(1) pos.sec1.y(3) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','corclear',... 'Parent',Hpan2(7),... 'call',{@corclear,H}); % Reuse one, all uicontrol('String','Restart One',... 'ToolTipString','restart the correlation of this increment (when pressing "go")',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(2) pos.sec1.y(2) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','correstartinc',... 'Parent',Hpan2(7),... 'call',{@correstartinc,H}); uicontrol('String','Restart All',... 'ToolTipString','restart the correlation of all increment (when pressing "go")',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(2) pos.sec1.y(3) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','correstart',... 'Parent',Hpan2(7),... 'call',{@correstart,H}); uicontrol('String','to iguess',... 'ToolTipString','save results as initial guess',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.xb(3) pos.sec1.y(2) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','cor2iguess',... 'Parent',Hpan2(7),... 'call',{@cor2iguess,H}); uicontrol('String',{'0';'1';'2'},... 'ToolTipString','how often to update the live view (0 = never, 1 = once per cg step, 2 = each iteration)',... 'Value',ini.corliveview.value,... 'Style','popupmenu',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.xb(3) pos.sec1.y(3) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','corliveview',... 'Parent',Hpan2(7)); h = pos.sec1.y(3) - (pos.sec1.y(end) + 0.02); uicontrol('Style','edit',... 'Max',2,... 'String',{''},... 'Enable','inactive',... 'units','normalized',... 'BackgroundColor','w',... 'Position',[pos.sec1.x1 pos.sec1.y(end) pos.sec1.w4 h],... 'FontSize',fontsize(1),... 'FontName',fixwidthfont,... 'HorizontalAlignment','left',... 'Tag','corstatus',... 'Parent',Hpan2(7)); % ======================================================================== % Section 8: Results % ======================================================================== axes('Parent',Hpan3(8),... 'Position',[pos.fig.x1 pos.fig.y2 pos.fig.w4-0.02 pos.fig.h2],... 'Box','On',... 'NextPlot','Add',... 'Tag','axes8',... 'FontSize',fontsize(2)); uicontrol('String','0',... 'ToolTipString','lower color limit',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[0.94 pos.fig.y2 0.05 pos.fig.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','resclim1',... 'call',{@plotres,H},... 'Parent',Hpan3(8)); uicontrol('String','0',... 'ToolTipString','upper color limit',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[0.94 pos.fig.y2+pos.fig.h2-pos.fig.h1 0.05 pos.fig.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','resclim2',... 'call',{@plotres,H},... 'Parent',Hpan3(8)); uicontrol('String','1',... 'ToolTipString','image id',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.fig.x1 pos.fig.y1 pos.fig.w1 pos.fig.h1],... 'FontSize',fontsize(3),... 'HorizontalAlignment','center',... 'Tag','resid',... 'call',{@resid,H},... 'Parent',Hpan3(8)); uicontrol('Style','slider',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.fig.x2 pos.fig.y1 pos.fig.w2 pos.fig.h1],... 'Tag','resslider',... 'Min',0,... 'Max',1,... 'Sliderstep',[0.01 0.1],... 'Value',1,... 'call',{@resslider,H},... 'Parent',Hpan3(8)); % Pattern controls uicontrol('String','Pattern',... 'Style','text',... 'FontWeight','bold',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(1) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(8)); underlay{1,1} = 'f'; underlay{2,1} = 'g'; underlay{3,1} = 'gtilde'; underlay{4,1} = 'r'; underlay{5,1} = 'none'; uicontrol('String',underlay,... 'ToolTipString','what pattern to show',... 'Style','popupmenu',... 'Value',ini.resunderlay.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(2) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','resunderlay',... 'call',{@plotres,H},... 'Parent',Hpan2(8)); uicontrol('String',ini.ressoftening.value,... 'Style','edit',... 'Enable','inactive',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(3) pos.sec1.w5 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','ressoftening',... 'Parent',Hpan2(8)); uicontrol('Style','slider',... 'ToolTipString','soften the pattern',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x3 pos.sec1.y(3) pos.sec1.w6 pos.sec1.h1],... 'Tag','ressofteningslider',... 'Min',0,... 'Max',1,... 'Sliderstep',[0.01 0.1],... 'Value',str2double(ini.ressoftening.value),... 'call',{@plotres,H},... 'Parent',Hpan2(8)); % Overlay controls uicontrol('String','Overlay',... 'Style','text',... 'FontWeight','bold',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(5) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(8)); overlay{ 1,1} = 'U1 (x)'; overlay{ 2,1} = 'U2 (y)'; overlay{ 3,1} = 'U3 (z or Constant)'; overlay{ 4,1} = 'U4 (Linear)'; overlay{ 5,1} = 'U5 (Quadratic)'; overlay{ 6,1} = 'U6 (Cubic)'; overlay{ 7,1} = 'strain xx'; overlay{ 8,1} = 'strain yy'; overlay{ 9,1} = 'strain xy'; overlay{10,1} = 'strain yx'; overlay{11,1} = 'strain maj'; overlay{12,1} = 'strain min'; overlay{13,1} = 'strain eq.'; overlay{14,1} = 'r'; overlay{15,1} = 'q'; overlay{16,1} = 'none'; uicontrol('String',overlay,... 'ToolTipString','what overlay to show',... 'Style','popupmenu',... 'Value',ini.resoverlay.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(6) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','resoverlay',... 'call',{@plotres,H},... 'Parent',Hpan2(8)); uicontrol('String',ini.resalpha.value,... 'Style','edit',... 'Enable','inactive',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(7) pos.sec1.w5 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','resalpha',... 'Parent',Hpan2(8)); uicontrol('Style','slider',... 'ToolTipString','overlay transparency',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x3 pos.sec1.y(7) pos.sec1.w6 pos.sec1.h1],... 'Tag','resalphaslider',... 'Min',0,... 'Max',1,... 'Sliderstep',[0.01 0.1],... 'Value',str2double(ini.resalpha.value),... 'call',{@plotres,H},... 'Parent',Hpan2(8)); % Arrow controls uicontrol('String','Vectors',... 'Style','text',... 'FontWeight','bold',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(9) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(8)); arrows{ 1,1} = 'U (x,y)'; arrows{ 2,1} = 'strain (xx,yy)'; arrows{ 3,1} = 'strain (min,maj)'; arrows{ 4,1} = 'none'; uicontrol('String',arrows,... 'ToolTipString','what overlay to show',... 'Style','popupmenu',... 'Value',ini.resarrows.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(10) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','resarrows',... 'call',{@plotres,H},... 'Parent',Hpan2(8)); uicontrol('String',ini.resarrowscale.value,... 'Style','edit',... 'Enable','inactive',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(11) pos.sec1.w5 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','resarrowscale',... 'Parent',Hpan2(8)); uicontrol('Style','slider',... 'ToolTipString','arrow scale factor',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x3 pos.sec1.y(11) pos.sec1.w6 pos.sec1.h1],... 'Tag','resarrowscaleslider',... 'Min',0,... 'Max',100,... 'Sliderstep',[0.001 0.01],... 'Value',str2double(ini.resarrowscale.value),... 'call',{@plotres,H},... 'Parent',Hpan2(8)); % extra result options uicontrol('String','Pixelsize',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.xb(1) pos.sec1.y(end-3) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(8)); uicontrol('String',ini.respixelsize.value,... 'ToolTipString','size of a pixel in the unit selected below',... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.xb(2) pos.sec1.y(end-3) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','respixelsize',... 'call',{@plotres,H},... 'Parent',Hpan2(8)); units{ 1,1} = 'nm'; units{ 2,1} = 'um'; units{ 3,1} = 'mm'; units{ 4,1} = 'm'; units{ 4,1} = 'km'; units{ 5,1} = 'px'; units{ 6,1} = 'inch'; units{ 7,1} = 'ft.'; uicontrol('String',units,... 'ToolTipString','unit of the pixelsize',... 'Style','popupmenu',... 'Value',ini.resunit.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.xb(3) pos.sec1.y(end-3) pos.sec1.wb pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','resunit',... 'call',{@plotres,H},... 'Parent',Hpan2(8)); straindef{ 1,1} = 'small strain'; straindef{ 2,1} = 'logarithmic strain'; straindef{ 3,1} = 'Green-Lagrange strain'; straindef{ 4,1} = 'Euler-Almansi strain'; straindef{ 5,1} = 'membrane strain'; straindef{ 6,1} = 'none'; uicontrol('String',straindef,... 'ToolTipString','strain definition',... 'Style','popupmenu',... 'Value',ini.resstraindef.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-2) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','resstraindef',... 'call',{@plotres,H,1},... 'Parent',Hpan2(8)); renderer{1,1} = 'OpenGL'; renderer{2,1} = 'zbuffer'; renderer{3,1} = 'painters'; uicontrol('String','renderer',... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-1) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(8)); uicontrol('String',renderer,... 'ToolTipString','switch to a different renderer (switch this when some parts of the plot are not proberly rendered)',... 'Style','popupmenu',... 'Value',ini.resrenderer.value,... 'BackgroundColor','w',... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end-1) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','resrenderer',... 'call',{@resrenderer,H},... 'Parent',Hpan2(8)); uicontrol('String','Save',... 'ToolTipString','save result figure',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','ressave',... 'Parent',Hpan2(8),... 'call',{@ressave,H}); % crosssection uicontrol('String','Cross-section',... 'ToolTipString','open cross-section controls',... 'Style','pushbutton',... 'Enable','inactive',... 'BackgroundColor',color.bg,... 'ForegroundColor',0.5*color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','rescrosssection',... 'call',{@rescrosssection,H},... 'Parent',Hpan2(8)); % ======================================================================== % Section 9: Info % ======================================================================== ipanlabel{1,1} = 'Info'; ipanlabel{2,1} = 'Status'; ipanlabel{3,1} = 'Help'; pos.ipan = [0 0 1 1]; for k = 1:3 if k == 3 visible = 'on'; else visible = 'off'; end Hipan(k) = uipanel('Title',ipanlabel{k},'FontSize',fontsize(2),... 'BackgroundColor',color.bg,... 'TitlePosition','lefttop',... 'Visible',visible,... 'units','normalized',... 'Tag',['infopan' num2str(k)],... 'Parent',Hpan3(9),... 'Position',pos.ipan); end uicontrol('String','Info',... 'ToolTipString','Show info panel',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(1) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','infobut1',... 'Parent',Hpan2(9),... 'call',{@infobutton,H,1}); uicontrol('String','Status',... 'ToolTipString','Show status panel',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'HorizontalAlignment','left',... 'Position',[pos.sec1.x1 pos.sec1.y(2) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','infobut2',... 'Parent',Hpan2(9),... 'call',{@infobutton,H,2}); uicontrol('String','Help',... 'ToolTipString','Show help panel',... 'Style','pushbutton',... 'BackgroundColor',color.hl,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(3) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','infobut3',... 'Parent',Hpan2(9),... 'call',{@infobutton,H,3}); uicontrol('String','Save guidata to D',... 'ToolTipString','save the guidata to the D structure in the base workspace',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-4) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(9),... 'call',{@infoguidataput,H}); uicontrol('String','Load guidata from D',... 'ToolTipString','load the D structure from the base workspace to the guidata',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-3) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Parent',Hpan2(9),... 'call',{@infoguidataget,H}); uicontrol('String','Reset GUI',... 'ToolTipString','reset the GUI state',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end-1) pos.sec1.w4 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','inforeset',... 'Parent',Hpan2(9),... 'call',{@inforeset,H}); uicontrol('String','Save',... 'ToolTipString','save GUI state to file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x1 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','infosave',... 'Parent',Hpan2(9),... 'call',{@infosave,H}); uicontrol('String','Load',... 'ToolTipString','load GUI state from file',... 'Style','pushbutton',... 'BackgroundColor',color.bg,... 'units','normalized',... 'Position',[pos.sec1.x2 pos.sec1.y(end) pos.sec1.w3 pos.sec1.h1],... 'FontSize',fontsize(3),... 'Tag','infoload',... 'Parent',Hpan2(9),... 'call',{@infoload,H}); % Info - Info % ============================ x = [0.02 0.4]; y = 0.05; w = [0.37 0.58]; h = 0.92; h2 = 0.03; pos.itable(1,:) = [x(1) y w(1) h]; pos.itable(2,:) = [x(2) y w(2) h]; pos.itxt(1,:) = [x(1) y+h w(1) h2]; pos.itxt(2,:) = [x(2) y+h w(2) h2]; str{1,1} = 'General Info'; str{2,1} = 'Correlation Info'; % general info uicontrol('String',str{1},... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',pos.itxt(1,:),... 'FontSize',fontsize(3),... 'FontWeight','bold',... 'Parent',Hipan(1)); uitable('units','normalized',... 'Position',pos.itable(1,:),... 'FontSize',fontsize(1),... 'Enable','On',... 'Tag','infogeneral',... 'Parent',Hipan(1)); % correlation info uicontrol('String',str{2},... 'Style','text',... 'BackgroundColor',color.bg,... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',pos.itxt(2,:),... 'FontSize',fontsize(3),... 'FontWeight','bold',... 'Parent',Hipan(1)); uitable('units','normalized',... 'Position',pos.itable(2,:),... 'FontSize',fontsize(1),... 'Enable','On',... 'Tag','infocorrelation',... 'Parent',Hipan(1)); % Info - Status % ============================ uicontrol('Style','edit',... 'Max',2,... 'String','Status',... 'Enable','inactive',... 'units','normalized',... 'BackgroundColor','w',... 'HorizontalAlignment','left',... 'Position',pos.ipan,... 'FontSize',fontsize(3),... 'FontName',fixwidthfont,... 'Tag','status',... 'Parent',Hipan(2)); % Info - Help % ============================ Hhelp = uicontrol('Style','edit',... 'Max',2,... 'String','Help',... 'Enable','inactive',... 'units','normalized',... 'BackgroundColor','w',... 'HorizontalAlignment','left',... 'Position',pos.ipan,... 'FontSize',fontsize(3),... 'FontName',fixwidthfont,... 'Tag','help',... 'Parent',Hipan(3)); % ======================================================================== drawnow; set(0,'CurrentFigure',H); % set the renderer set(H,'Renderer','opengl') try opengl hardwarebasic end % Defaults % ===================== D.gui.activepanel = 9; D.gui.activeinfopanel = 3; D.gui.activepatview = 1; D.gui.ini = ini; D.mask = []; D.basis(4).name = []; % initialize info D.gui.info(1).str = 'date'; D.gui.info(1).val = datestr(now,'yyyy-mm-dd'); D.gui.info(2).str = 'time'; D.gui.info(2).val = datestr(now,'HH:MM:SS'); % initialize status str = ['Basic gdic tool started: ' datestr(now,'yyyy-mm-dd')]; D.gui.stat = appendstatus({''},str); D.gui.stat = appendstatus(D.gui.stat,'rule'); % initialize help helpstr = basicgdic_help; set(Hhelp,'String',helpstr); % Finalizing GUI buildup % ===================== % convert to normalized units (to allow resizing) Hu = findobj(H,'-property','units'); Hu = setdiff(Hu,H); set(Hu,'units','normalized'); % Generate handles structure S = guihandles(H); % add to data structure D.gui.pos = pos; D.gui.color = color; D.gui.fontsize = fontsize; D.gui.fixwidthfont = fixwidthfont; D.gui.linewidth = 1.6; D.gui.markersize = 12; % collection of controls to disable when processing D.gui.waithandles = waithandlesfun(S); % update the application data guidata(H,D); basisset(H); % debugging % -------------- % assignin('base','H',H) % assignin('base','S',S) % assignin('base','D',D) % read inputfile from ini (the input argument takes precedence) if ~exist('inputfile','var') && ~isempty(D.gui.ini.inputfile.value) inputfile = D.gui.ini.inputfile.value; end % load the input variables if exist('inputfile','var') % convert relative path to absolute if ~isstruct(inputfile) && ~strcmp(inputfile(1),'/') && ~strcmp(inputfile(2),':') inputfile = fullfile(D.gui.ini.basedir.value,inputfile); end % load the inputfile if isstruct(inputfile) && isfield(inputfile,'version') % input is the D structure guidata(H,inputfile); D = guidata(H); % update the state of the GUI iniset(H);drawnow guidata(H,D);drawnow updateinfo(H) inputfile = sprintf('var: %s',inputname(1)); elseif exist(inputfile,'file') % inputfile is specified absolute infoload([],[],H,inputfile) else msgstr = sprintf('The input file (%s) was not found, nothing loaded',inputfile); msgdlgjn(msgstr,dlgposition(H)); return end else return end % get the current guidata D = guidata(H); % store the inputfile D.inputfile = inputfile; % update the status D.gui.stat = appendstatus(D.gui.stat,sprintf('[9] basicgdic data loaded from %s',inputfile)); guidata(H,D);drawnow % ============================================= if ~headlessmode varargout{1} = D; return end % convert relative path to absolute if ~strcmp(outputfile(1),'/') && ~strcmp(outputfile(2),':') outputfile = fullfile(D.gui.ini.basedir.value,outputfile); end D.outputfile = outputfile; % update the application data guidata(H,D);drawnow; if headlessmode headlessstatus(sprintf('inputfile %s loaded (GUI handle is %d)',inputfile,H)); % disable liveview (nobody is watching) set(S.corliveview,'Value',1) % start the correlation headlessstatus('starting correlation'); corgo([],[],H) % save the result D = guidata(H); D = rmfield(D,'outputfile'); guidata(H,D); headlessstatus(sprintf('writing outputfile %s',outputfile)); infosave([],[],H,outputfile) headlessstatus(sprintf('outputfile %s saved',outputfile)); % exit gui delete(H) headlessstatus('exiting basicgdic'); end % set the output varargout{1} = D; end % ========================================================================= % Section 0: Main GUI functions % ========================================================================= % ================================================== function iniwrite(filename,ini) % this function reads all the guihandles and populates the ini structure % from the current state of the GUI fields = fieldnames(ini); N = length(fields); fid = fopen(filename,'w+t'); % print the header fprintf(fid,'%% settings file written by basicgdic on %s \n',datestr(now)); fprintf(fid,'%% ================================================== \n'); % set all the options for k = 1:N name = fields{k}; type = ini.(fields{k}).type; value = ini.(fields{k}).value; if ~strcmpi(type,'string') value = num2str(value); end fprintf(fid,'%s:%s = %s\n',name,type,value); end fprintf(fid,'%% ================================================== \n'); fclose(fid); end % ================================================== function ini = iniread(varargin) filename = 'basicgdic_defaults.ini'; % create the defaults file if it doesn't exist basicgdic_defaults; if ~exist(filename,'file') ini = []; return end % read the entire option file into memory fid = fopen(filename,'rt'); F = textscan(fid,'%s','Delimiter','\n','Whitespace',''); fclose(fid); F = F{1}; % Remove empty lines I = regexpi(F,'.*'); I = ~cellfun('isempty',I); F = F(I); % Remove comment lines I = regexpi(F,'^[%#\[].*'); I = cellfun('isempty',I); F = F(I); % Remove inline comments I = regexpi(F,'\s*[%#\[].*'); J = ~cellfun('isempty',I); n = 1:length(J); for k = n(J) % keep only the characters before the match F{k} = F{k}(1:I{k}-1); end % Remove extra white spaces F = strtrim(F); % process to a structure for k = 1:length(F) % one line A = F{k}; try % evaluate the line S = regexpi(A,'^\s*(.*?)\s*\:\s*(.*?)\s*=\s*(.*?)\s*$','tokens'); name = S{1}{1}; type = S{1}{2}; value = S{1}{3}; catch fprintf(2,'!!! iniread: error processing the line [%s]\n',A); return end % convert string to double if ~strcmpi(type,'string') value = eval(value); end % correct the basedir if strcmpi(name,'basedir') % change all slashes to foreward value = regexprep(value,'\\','/'); if isempty(value) value = pwd; elseif ~strcmp(value(1),'/') && ~strcmp(value(2),':') value = fullfile(pwd,value); end end ini.(name).type = type; ini.(name).value = value; end end % ================================================== function ini = iniget(H) % this function reads all the guihandles and populates the ini structure % from the current state of the GUI S = guihandles(H); D = guidata(H); % process the ini % ============================= fields = fieldnames(D.gui.ini); N = length(fields); ini = D.gui.ini; % set all the options for k = 1:N if isfield(S,fields{k}) && ishandle(S.(fields{k})) ini.(fields{k}).value = get(S.(fields{k}),ini.(fields{k}).type); end end end % ================================================== function iniset(H) % this function should read the contents of D.gui.ini and apply all % properties. Additionally, it should read from D.files and D.basis to fill % those properties (these are done first). Finally, it should correctly % enable/disable all options and correctly set the sliders S = guihandles(H); D = guidata(H); % update the Images GUI part fileset(H) % update the Basis GUI part basisset(H) % process the ini % ============================= fields = fieldnames(D.gui.ini); N = length(fields); ini = D.gui.ini; % set all the options for k = 1:N if isfield(S,fields{k}) && ishandle(S.(fields{k})) set(S.(fields{k}),ini.(fields{k}).type,ini.(fields{k}).value) end end % Correct the basis choise if necessary % ============================= basislst = get(S.basislist,'String'); Nbasis = length(basislst); set(S.prepAbasis,'Value',min([Nbasis get(S.prepAbasis,'Value')])); set(S.prepBbasis,'Value',min([Nbasis get(S.prepBbasis,'Value')])); set(S.prepCbasis,'Value',min([Nbasis get(S.prepCbasis,'Value')])); set(S.finalbasis,'Value',min([Nbasis get(S.finalbasis,'Value')])); set(S.dicrelbasis,'Value',min([Nbasis+1 get(S.dicrelbasis,'Value')])); % Correct the enable states % ============================= basistype([],[],H) cgstr{1,1} = 'prepA'; cgstr{2,1} = 'prepB'; cgstr{3,1} = 'prepC'; cgstr{4,1} = 'final'; for k = 1:3 if ini.([cgstr{k} 'on']).value == 1 set(S.([cgstr{k} 'on']),'BackgroundColor',D.gui.color.hl); set(S.([cgstr{k} 'off']),'BackgroundColor',D.gui.color.bg); set(S.([cgstr{k} 'on']),'Value',1); set(S.([cgstr{k} 'off']),'Value',0); enable = 'on'; else set(S.([cgstr{k} 'on']),'BackgroundColor',D.gui.color.bg); set(S.([cgstr{k} 'off']),'BackgroundColor',D.gui.color.hl); set(S.([cgstr{k} 'on']),'Value',0); set(S.([cgstr{k} 'off']),'Value',1); enable = 'off'; end end for k = 1:4 set(S.([cgstr{k} 'blur']),'Enable',enable); set(S.([cgstr{k} 'level']),'Enable',enable); set(S.([cgstr{k} 'improcess']),'Enable',enable); set(S.([cgstr{k} 'basis']),'Enable',enable); set(S.([cgstr{k} 'convcrit']),'Enable',enable); set(S.([cgstr{k} 'maxit']),'Enable',enable); set(S.([cgstr{k} 'gradient']),'Enable',enable); set(S.([cgstr{k} 'tikhpar1']),'Enable',enable); set(S.([cgstr{k} 'tikhpar2']),'Enable',enable); set(S.([cgstr{k} 'tikhsteps']),'Enable',enable); end drawnow; % Dimensions if get(S.dicdimensions,'Value') == 1 %2D set(S.dicrelaxation,'Enable','on') if get(S.dicrelaxation,'Value') == 1 %none set(S.dicrelbasis,'Enable','off') else % brightness or brightness+contrast set(S.dicrelbasis,'Enable','on') end elseif get(S.dicdimensions,'Value') == 2 %3D set(S.dicrelaxation,'Enable','off') set(S.dicrelbasis,'Enable','off') set(S.resstraindef,'Value',5) end % Relaxation if get(S.dicrelaxation,'Value') == 1 %none set(S.dicrelbasis,'Enable','off') else % brightness or brightness+contrast set(S.dicrelbasis,'Enable','on') end % Correct the sliders % ============================= set(S.basissoftenslider,'Value',str2double(ini.basissoften.value)); set(S.basisalphaslider,'Value',str2double(ini.basisalpha.value)); set(S.diclagrangeslider,'Value',str2double(ini.diclagrange.value)); set(S.ressofteningslider,'Value',str2double(ini.ressoftening.value)); set(S.resalphaslider,'Value',str2double(ini.resalpha.value)); set(S.resarrowscaleslider,'Value',str2double(ini.resarrowscale.value)); % image sliders sliderupdate(H) % Correct the indicators % ============================= if isfield(D,'files') set(S.secind1,'BackgroundColor',D.gui.color.on) else set(S.secind1,'BackgroundColor',D.gui.color.off) end if isfield(D,'pateval') set(S.secind2,'BackgroundColor',D.gui.color.on) else set(S.secind2,'BackgroundColor',D.gui.color.init) end if isfield(D,'roi') set(S.secind3,'BackgroundColor',D.gui.color.on) else set(S.secind3,'BackgroundColor',D.gui.color.off) end if isfield(D,'iguess') set(S.secind4,'BackgroundColor',D.gui.color.on) else set(S.secind4,'BackgroundColor',D.gui.color.init) end if isfield(D,'basis') set(S.secind5,'BackgroundColor',D.gui.color.on) else set(S.secind5,'BackgroundColor',D.gui.color.off) end if isfield(D,'cor') set(S.secind6,'BackgroundColor',D.gui.color.on) set(S.secind7,'BackgroundColor',D.gui.color.on) else set(S.secind6,'BackgroundColor',D.gui.color.init) set(S.secind7,'BackgroundColor',D.gui.color.off) end if isfield(D,'res') set(S.secind8,'BackgroundColor',D.gui.color.on) else set(S.secind8,'BackgroundColor',D.gui.color.off) end end % ================================================== function fileset(H) % this function reads D.files and populates the corresponding GUI parts S = guihandles(H); D = guidata(H); if ~isfield(D,'files') set(S.filelist,'String',{''}); set(S.filelist,'Max',2); return end % fix the filelist filelist = {D.files(:).name}'; N = length(filelist); set(S.filelist,'String',filelist); set(S.filelist,'Max',N); % update info info(1).str = 'Nfiles'; info(1).val = N; D.gui.info = appendinfo(D.gui.info,info); guidata(H,D);drawnow end % ================================================== function basisset(H) % this function reads D.basis and populates the corresponding GUI parts S = guihandles(H); D = guidata(H); if ~isfield(D,'basis') set(S.basislist,'String',{'basis 1';'basis 2';'basis 3';'basis 4'}) set(S.basislist,'Value',1) return end % populate the basislist Nb = length(D.basis); done = 0; for id = 1:Nb if ~isempty(D.basis(id).name) done = done + 1; basislst{id,1} = D.basis(id).name; else basislst{id,1} = sprintf('basis %d',id); end end set(S.basislist,'String',basislst) set(S.basislist,'Value',1) % set the enable states basistype([],[],H) % check if the current selection still makes sense tags{1,1} = 'prepAbasis'; tags{2,1} = 'prepBbasis'; tags{3,1} = 'prepCbasis'; tags{4,1} = 'finalbasis'; tags{5,1} = 'dicrelbasis'; for k = 1:5 % append to the current list if k == 5 basislst = [{'same as U'} ; basislst]; end % get the current string set(S.(tags{k}),'Value',1) set(S.(tags{k}),'String',basislst) end % Set the indicator if done == Nb set(S.secind5,'BackgroundColor',D.gui.color.on) end end % ================================================== function sliderupdate(H) % this function fixes the length of all sliders, such that it matches the % number of images and basis functions. S = guihandles(H); D = guidata(H); % get the number of images if ~isfield(D,'files') Nfiles = 1; else Nfiles = length(D.files); end % setting the maximum slider position slidermax = max([Nfiles 2]); sliderstep = [1/(slidermax-1) 10/(slidermax-1)]; % update sliders (related to images) set(S.imageid,'String','1') set(S.imageslider,'Value',1) set(S.imageslider,'Min',1) set(S.imageslider,'Max',slidermax) set(S.imageslider,'Sliderstep',sliderstep) set(S.patid,'String','1') set(S.patslider,'Value',1) set(S.patslider,'Min',1) set(S.patslider,'Max',slidermax) set(S.patslider,'Sliderstep',sliderstep) set(S.roiid,'String','1') set(S.roislider,'Value',1) set(S.roislider,'Min',1) set(S.roislider,'Max',slidermax) set(S.roislider,'Sliderstep',sliderstep) set(S.iguessid,'String','1') set(S.iguessslider,'Value',1) set(S.iguessslider,'Min',1) set(S.iguessslider,'Max',slidermax) set(S.iguessslider,'Sliderstep',sliderstep) set(S.corid,'String','0') set(S.corslider,'Value',0) set(S.corslider,'Min',0) set(S.corslider,'Max',slidermax-1) set(S.corslider,'Sliderstep',sliderstep) set(S.resid,'String','1') set(S.resslider,'Value',0) set(S.resslider,'Min',0) set(S.resslider,'Max',slidermax-1) set(S.resslider,'Sliderstep',sliderstep) % get the number of basis functions k = get(S.basislist,'Value'); if isfield(D,'basis') && isfield(D.basis,'plotphi') Nphi = D.basis(k).Nphi; else Nphi = 1; end % setting the maximum slider position slidermax = max([Nphi 2]); if Nphi > 2 sliderstep = [1/(slidermax-2) 10/(slidermax-2)]; else sliderstep = [1/(slidermax-1) 10/(slidermax-1)]; end % update sliders (related to basis functions) set(S.phiid,'String','1') set(S.phislider,'Value',1) set(S.phislider,'Max',slidermax) set(S.phislider,'Sliderstep',sliderstep) drawnow; end % ================================================== function WindowScrollWheelFcn(H,evnt) % this function is called when using the mousewheel in the gui S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end % number of images Nim = length(D.files); % depending on the current panel, get the current slider value (id) if D.gui.activepanel == 1 id = str2double(get(S.imageid,'String')); id = round(id); elseif D.gui.activepanel == 2 id = str2double(get(S.patid,'String')); id = round(id); elseif D.gui.activepanel == 3 id = str2double(get(S.roiid,'String')); id = round(id); elseif D.gui.activepanel == 4 id = str2double(get(S.iguessid,'String')); id = round(id); elseif D.gui.activepanel == 5 id = str2double(get(S.phiid,'String')); id = round(id); k = get(S.basislist,'Value'); if isfield(D,'basis') && isfield(D.basis(k),'Nphi') Nim = D.basis(k).Nphi; Nim = max([Nim 2]); else return end elseif D.gui.activepanel == 7 id = str2double(get(S.corid,'String')); id = round(id); elseif D.gui.activepanel == 8 id = str2double(get(S.resid,'String')); id = round(id); else return end % mouse wheel up or down if evnt.VerticalScrollCount < 0 id = id - 1 ; elseif evnt.VerticalScrollCount > 0 id = id + 1 ; end % limit the id to the slider limits if any(D.gui.activepanel == [1 2 3 4 5 6 9]) id = max([id 1]); id = min([id Nim]); elseif any(D.gui.activepanel == [7,8]) id = max([id 0]); id = min([id Nim-1]); end % depending on the current panel, change the correct slider if D.gui.activepanel == 1 set(S.imageslider,'Value',id); set(S.imageid,'String',num2str(id)); plotimage(H) elseif D.gui.activepanel == 2 set(S.patslider,'Value',id); set(S.patid,'String',num2str(id)); if D.gui.activepatview == 1 plotpattern(H) elseif D.gui.activepatview == 2 plotacf(H) end elseif D.gui.activepanel == 3 set(S.roislider,'Value',id); set(S.roiid,'String',num2str(id)); plotroimask(H) elseif D.gui.activepanel == 4 set(S.iguessslider,'Value',id); set(S.iguessid,'String',num2str(id)); plotiguess(H) elseif D.gui.activepanel == 5 set(S.phislider,'Value',id); set(S.phiid,'String',num2str(id)); plotbasis([],[],H); elseif D.gui.activepanel == 6 elseif D.gui.activepanel == 7 set(S.corslider,'Value',id); set(S.corid,'String',num2str(id)); plotcor(H) elseif D.gui.activepanel == 8 set(S.resslider,'Value',id); set(S.resid,'String',num2str(id)); plotres([],[],H) end drawnow end % ================================================== function unlockGUI(H,evnt) % function called when pressing the unlock toolbar button disp('unlocking') D = guidata(H); set(D.gui.waithandles,'Enable','on');drawnow end % ================================================== function keyPressFcn(H,evnt) % call function for keypresses in the gui D = guidata(H); % press escale to "exit" a blocked state if strcmp(evnt.Key,'escape') % enable gui controls disp('unlocking') set(D.gui.waithandles,'Enable','on');drawnow end % Ctrl-N shortcuts to the sections if strcmp(evnt.Modifier,'control') if strcmp(evnt.Key,'1') secbutton([],[],H,1) elseif strcmp(evnt.Key,'2') secbutton([],[],H,2) elseif strcmp(evnt.Key,'3') secbutton([],[],H,3) elseif strcmp(evnt.Key,'4') secbutton([],[],H,4) elseif strcmp(evnt.Key,'5') secbutton([],[],H,5) elseif strcmp(evnt.Key,'6') secbutton([],[],H,6) elseif strcmp(evnt.Key,'7') secbutton([],[],H,7) elseif strcmp(evnt.Key,'8') secbutton([],[],H,8) elseif strcmp(evnt.Key,'9') secbutton([],[],H,9) end end % arrows if strcmp(evnt.Key,'leftarrow') || strcmp(evnt.Key,'downarrow') E.VerticalScrollCount = -1; WindowScrollWheelFcn(H,E) elseif strcmp(evnt.Key,'rightarrow') || strcmp(evnt.Key,'uparrow') E.VerticalScrollCount = 1; WindowScrollWheelFcn(H,E) end end % ================================================== function [] = secbutton(varargin) % Button Callback: Switch section pannels H = varargin{3}; S = guihandles(H); D = guidata(H); % the pressed button but = varargin{4}; D.gui.activepanel = but; % switch all buttons to gray, and one to blue for k = 1:9 if k == but set(S.(['secpan' num2str(k)]),'Visible','on'); set(S.(['figpan' num2str(k)]),'Visible','on'); set(S.(['secbut' num2str(k)]),'BackgroundColor',D.gui.color.hl); else set(S.(['secpan' num2str(k)]),'Visible','off'); set(S.(['figpan' num2str(k)]),'Visible','off'); set(S.(['secbut' num2str(k)]),'BackgroundColor',D.gui.color.bg); end end % change colormap between gray and colored if any(but == [5 8]) colormap(D.gui.color.cmapoverlay) else colormap(D.gui.color.cmap) end % set indicator on for DIC options if but == 6 set(S.secind6,'BackgroundColor',D.gui.color.on) elseif but == 9 set(S.secind9,'BackgroundColor',D.gui.color.on) end % update the application data guidata(H,D); % update the corresponding figures if D.gui.activepanel == 1 cla(S.axes1); plotimage(H); elseif D.gui.activepanel == 2 cla(S.axes2); if D.gui.activepatview == 1 plotpattern(H) elseif D.gui.activepatview == 2 plotacf(H) end elseif D.gui.activepanel == 3 cla(S.axes3); plotroimask(H); elseif D.gui.activepanel == 4 cla(S.axes41); cla(S.axes42); cla(S.axes43); cla(S.axes44); plotiguess(H); elseif D.gui.activepanel == 5 cla(S.axes4); plotbasis([],[],H); elseif D.gui.activepanel == 6 % update the basis list basislst = get(S.basislist,'String'); % check if the current selection still makes sense tags{1,1} = 'prepAbasis'; tags{2,1} = 'prepBbasis'; tags{3,1} = 'prepCbasis'; tags{4,1} = 'finalbasis'; tags{5,1} = 'dicrelbasis'; for k = 1:5 % get the current string strs = get(S.(tags{k}),'String'); val = get(S.(tags{k}),'Value'); val = min([val length(strs)]); val = max([val 1]); str = strs{val}; % append to the current list if k == 5 basislst = [{'same as U'} ; basislst]; end id = find(strcmp(str,basislst),1); if isempty(id) val = min([val Nb]); val = max([val 1]); else val = id; end set(S.(tags{k}),'Value',val) set(S.(tags{k}),'String',basislst) end elseif D.gui.activepanel == 7 cla(S.axes7); plotcor(H); elseif D.gui.activepanel == 8 cla(S.axes8); plotres([],[],H); elseif D.gui.activepanel == 9 updateinfo(H) end % force redrawing of gui elements drawnow end % ================================================== function [] = infobutton(varargin) % Button Callback: Switch info panels (Info,Status,Help) H = varargin{3}; S = guihandles(H); D = guidata(H); but = varargin{4}; D.gui.activeinfopanel = but; % switch all buttons to gray, and one to blue for k = 1:3 if k == but set(S.(['infopan' num2str(k)]),'Visible','on'); set(S.(['infobut' num2str(k)]),'BackgroundColor',D.gui.color.hl); else set(S.(['infopan' num2str(k)]),'Visible','off'); set(S.(['infobut' num2str(k)]),'BackgroundColor',D.gui.color.bg); end end % update the application data guidata(H,D); end % ========================================================================= % Section 1: Images % ========================================================================= % ================================================== function [] = fileadd(varargin) % Load additional images H = varargin{3}; S = guihandles(H); D = guidata(H); % old filelist filelist = get(S.filelist,'String'); % old file datastructure if (isfield(D,'files')) && (~isempty(D.files)) files = D.files; Nfiles = length(files); val = get(S.filelist,'Value'); if ~isempty(val) basedir = files(val(end)).path; else basedir = files(end).path; end else Nfiles = 0; % get the previous basedir if ~isempty(D.gui.ini.basedir.value); basedir = D.gui.ini.basedir.value; else basedir = pwd; end end % get the filesize of the reference if isfield(D,'files') nref = D.files(1).size(1); mref = D.files(1).size(2); end %uigetfile [FileName,PathName] = uigetfile(... {'*.bmp;*.jpg;*.tif;*.png;*.gif;*.plu;*.BMP;*.JPG;*.TIF;*.PNG;*.GIF;*.PLU',... 'All Image Files';... '*.*','All Files' },... 'add files',... 'MultiSelect','on',... basedir); % if cancel if isequal(FileName,0) return end % for output of uigetfile to be a string, even if only one file if ~iscell(FileName) fname{1} = FileName; else fname = FileName; end % number of new files Nselected = length(fname); colorimage = false; for isel = 1:Nselected id = Nfiles+isel; bcwaitbar(H,isel/Nselected,sprintf('loading files (%d/%d)',isel,Nselected)); % add files to list and datastruct ext = regexp(fname{isel},'\..*$','match'); ext = ext{1}(2:end); files(id).name = fname{isel}; files(id).path = PathName; files(id).ext = ext; filelist{id} = fname{isel}; % read the images filename = fullfile(files(id).path,files(id).name); % get the extention ext = regexp(filename,'\.','split'); ext = ext{end}; if strcmp(ext,'plu') plu = pluread(filename); A = plu.Z;% + plu.z0; [n, m] = size(A); cls = 'double'; % check for NaN values if any(isnan(A(:))); [X, Y] = meshgrid(1:m,1:n); I = find(~isnan(A)); A = griddata(X(I),Y(I),A(I),X,Y); end set(S.respixelsize,'String',num2str(plu.pixelsize(1))); set(S.resunit,'Value',2); else % read image A = imread(filename); % store current class cls = class(A); % convert to double A = double(A); % convert RGB to Grayscale [n, m, k] = size(A); if k == 3 colorimage = true; A = 0.2989*A(:,:,1) + 0.5870*A(:,:,2) + 0.1140*A(:,:,3); end end % get the image size of the reference image if id == 1 nref = n; mref = m; else if (n ~= nref) || (m ~= mref) msgstr{1,1} = sprintf('Incompatible image size of %s (%d,%d), expected (%d,%d)',fname{isel},n,m,nref,mref); msgstr{2,1} = 'Add file procedure stopped'; msgdlgjn(msgstr,dlgposition(H)); delete(hwait) return end end % store images files(id).size = size(A); files(id).range = [min(A(:)) max(A(:))]; files(id).class = cls; files(id).image = A; % add zero initial guess if isfield(D,'iguess') D.iguess.ux(:,id) = 0; D.iguess.uy(:,id) = 0; end % add initial guess (processed) image if isfield(files,'imageproc') % get settings Rblur = str2double(get(S.iguessblur,'String')); gradtype = get(S.iguessimprocesstype,'String'); gradtype = gradtype(get(S.iguessimprocesstype,'Value')); % blur % =========== if Rblur > 0.3 Im = image_blur(A,Rblur); end % gradient transform % =========== if ~strcmp(gradtype,'none') [dImdx, dImdy] = gradient(Im); end if strcmp(gradtype,'grad|xy|'); Im = sqrt(dImdx.^2+dImdy.^2); elseif strcmp(gradtype,'grad|x|'); Im = abs(dImdx); elseif strcmp(gradtype,'grad|y|'); Im = abs(dImdy); elseif strcmp(gradtype,'grad(xy)'); Im = 0.5*(dImdx+dImdy); elseif strcmp(gradtype,'grad(x)'); Im = dImdx; elseif strcmp(gradtype,'grad(y)'); Im = dImdy; end files(id).imageproc = Im; end % add zero initial guess if isfield(D,'cor') D.cor(id-1).inc = id-1; end % add zero initial guess if isfield(D,'res') D.res(id-1).inc = id-1; end end bcwaitbar(H); if colorimage msgstr{1,1} = 'Color images detected and converted to grayscale.'; msgstr{2,1} = 'The blur radii of the coarse grain steps are set to 2 pixels'; msgstr{3,1} = 'to reduce demosaicing artifacts'; msgdlgjn(msgstr,dlgposition(H)); tags{1,1} = 'prepAblur'; tags{2,1} = 'prepBblur'; tags{3,1} = 'prepCblur'; tags{4,1} = 'finalblur'; for k = 1:4 set(S.(tags{k}),'String','2') end end % update list in gui Nfiles = length(files); set(S.filelist,'String',filelist); set(S.filelist,'Max',Nfiles); D.files = files; % update info info(1).str = 'Nfiles'; info(1).val = Nfiles; info(2).str = 'n'; info(2).val = n; info(3).str = 'm'; info(3).val = m; info(4).str = 'Npx'; info(4).val = n*m; info(5).str = 'class'; info(5).val = cls; D.gui.info = appendinfo(D.gui.info,info); % update status D.gui.stat = appendstatus(D.gui.stat,sprintf('[1] %d files added',Nselected)); % update the application data guidata(H,D); % update sliders sliderupdate(H); % plot the figures plotimage(H); % set section indicator on set(S.secind1,'BackgroundColor',D.gui.color.on) end % ================================================== function [] = filedel(varargin) % remove files from the list H = varargin{3}; S = guihandles(H); D = guidata(H); if isfield(D,'files') files = D.files; Nfiles = length(files); else return end % get current filelist filelist = get(S.filelist,'String'); % get selection selected = get(S.filelist,'Value'); Nselected = length(selected); if Nselected == 1 filestr = 'file'; else filestr = 'files'; end % ask for confirmation if any(selected==1) qstr{1,1} = 'Warning: Removing the reference image (first file) will reset all results'; qstr{2,1} = sprintf('Delete %d %s from the list?',Nselected,filestr); else qstr{1,1} = sprintf('Delete %d %s from the list?',Nselected,filestr); end button = questdlgjn(qstr,'deleting files','Yes','No','Yes',dlgposition(H)); if isempty(button) || strcmpi(button,'No') return end if any(selected==1) set(S.secind1,'BackGroundColor',D.gui.color.off) set(S.secind2,'BackGroundColor',D.gui.color.init) set(S.secind3,'BackGroundColor',D.gui.color.off) set(S.secind4,'BackGroundColor',D.gui.color.init) set(S.secind5,'BackGroundColor',D.gui.color.off) set(S.secind6,'BackGroundColor',D.gui.color.init) set(S.secind7,'BackGroundColor',D.gui.color.off) set(S.secind8,'BackGroundColor',D.gui.color.init) set(S.secind9,'BackGroundColor',D.gui.color.init) end if Nselected == Nfiles % delete all files D = rmfield(D,'files'); Nfiles = 2; filelist = {}; if isfield(D,'iguess') D = rmfield(D,'iguess'); end if isfield(D,'cor') D = rmfield(D,'cor'); end if isfield(D,'res') D = rmfield(D,'res'); end if isfield(D,'roi') D = rmfield(D,'roi'); end if isfield(D,'pateval') D = rmfield(D,'pateval'); end else % invert index I = 1:Nfiles; I = setdiff(I,selected); Inc = 1:(Nfiles-1); Inc = setdiff(Inc,selected-1); % delete files from lists filelist = filelist(I); files = files(I); Nfiles = length(files); D.files = files; % Delete corresponding data if isfield(D,'iguess') if any(selected == 1) % reference is deleted, start over D = rmfield(D,'iguess'); else D.iguess.ux = D.iguess.ux(:,I); D.iguess.uy = D.iguess.uy(:,I); end end if isfield(D,'cor') if any(selected == 1) % reference is deleted, start over D = rmfield(D,'cor'); else D.cor = D.cor(Inc); end end if isfield(D,'res') if any(selected == 1) % reference is deleted, start over D = rmfield(D,'res'); else D.res = D.res(Inc); end end end % update gui set(S.filelist,'Value',1); set(S.filelist,'Max',Nfiles); set(S.filelist,'String',filelist); % update status D.gui.stat = appendstatus(D.gui.stat,sprintf('[1] %d files deleted',Nselected)); % update the application data guidata(H,D); % update sliders sliderupdate(H); % plot the figures plotimage(H); end % ================================================== function [] = fileup(varargin) % move files up the list H = varargin{3}; S = guihandles(H); D = guidata(H); if isfield(D,'files') files = D.files; Nfiles = length(files); else return end % get current filelist filelist = get(S.filelist,'String'); % get selection sel = get(S.filelist,'Value'); Nsel = length(sel); % files above selected ab = sel-1; ab(ab<=1) = 1; % index I = 1:Nfiles; Inc = I - 1; % swap selected index with item above for k = 1:length(sel) I([sel(k),ab(k)]) = I([ab(k),sel(k)]); Inc([sel(k),ab(k)]) = Inc([ab(k),sel(k)]); end Inc = Inc(2:end); if Nsel == 1 filestr = 'file'; else filestr = 'files'; end % ask for confirmation if I(1) ~= 1 % changing the reference qstr{1,1} = 'Warning: Changing the reference image (first file) will reset all results'; qstr{2,1} = sprintf('Move %d %s in list?',Nsel,filestr); button = questdlgjn(qstr,'move files','Yes','No','Yes',dlgposition(H)); if isempty(button) || strcmpi(button,'No') return end end % update to new list order filelist = filelist(I); files = files(I); Nfiles = length(files); % update gui set(S.filelist,'Value',ab); set(S.filelist,'String',filelist); D.files = files; % Move corresponding data if isfield(D,'iguess') if I(1) ~= 1 % changing the reference D = rmfield(D,'iguess'); else D.iguess.ux = D.iguess.ux(:,I); D.iguess.uy = D.iguess.uy(:,I); end end if isfield(D,'cor') if I(1) ~= 1 % changing the reference D = rmfield(D,'cor'); else D.cor = D.cor(Inc); end end if isfield(D,'res') if I(1) ~= 1 % changing the reference D = rmfield(D,'res'); else D.res = D.res(Inc); end end % update status D.gui.stat = appendstatus(D.gui.stat,sprintf('[1] %d files moved up in the list',Nsel)); % update the application data guidata(H,D); % plot the figures plotimage(H); end % ================================================== function [] = filedown(varargin) % move files down the list H = varargin{3}; S = guihandles(H); D = guidata(H); if isfield(D,'files') files = D.files; Nfiles = length(files); else return; end % get current filelist filelist = get(S.filelist,'String'); % get selection sel = get(S.filelist,'Value'); Nsel = length(sel); % file below selected bel = sel+1; bel(bel>=Nfiles) = Nfiles; % index I = 1:Nfiles; Inc = I-1; % switch index with item below for k = length(sel):-1:1 I([sel(k),bel(k)]) = I([bel(k),sel(k)]); Inc([sel(k),bel(k)]) = Inc([bel(k),sel(k)]); end Inc = Inc(2:end); if Nsel == 1 filestr = 'file'; else filestr = 'files'; end % ask for confirmation if I(1) ~= 1 % changing the reference qstr{1,1} = 'Warning: Changing the reference image (first file) will reset all results'; qstr{2,1} = sprintf('Move %d %s in list?',Nsel,filestr); button = questdlgjn(qstr,'move files','Yes','No','Yes',dlgposition(H)); if isempty(button) || strcmpi(button,'No') return end end % update file order filelist = filelist(I); files = files(I); % update gui set(S.filelist,'Value',bel); set(S.filelist,'String',filelist); D.files = files; % Move corresponding data if isfield(D,'iguess') if I(1) ~= 1 % changing the reference D = rmfield(D,'iguess'); else D.iguess.ux = D.iguess.ux(:,I); D.iguess.uy = D.iguess.uy(:,I); end end if isfield(D,'cor') if I(1) ~= 1 % changing the reference D = rmfield(D,'cor'); else D.cor = D.cor(Inc); end end if isfield(D,'res') if I(1) ~= 1 % changing the reference D = rmfield(D,'res'); else D.res = D.res(Inc); end end % update status D.gui.stat = appendstatus(D.gui.stat,sprintf('[1] %d files moved down in the list',Nsel)); % update the application data guidata(H,D); % plot the figures plotimage(H); end % ================================================== function [] = imageid(varargin) % Callback for the edit box below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = str2double(get(S.imageid,'String')); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nim]); % update the gui set(S.imageslider,'Value',id); plotimage(H) end % ================================================== function [] = fileselect(varargin) % Callback for the slider below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = get(S.filelist,'Value'); id = id(1); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nim]); % update the gui set(S.imageid,'String',num2str(id)); set(S.imageslider,'Value',id); plotimage(H) end % ================================================== function [] = imageslider(varargin) % Callback for the slider below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = get(S.imageslider,'Value'); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nim]); % update the gui set(S.imageid,'String',num2str(id)); plotimage(H) end % ========================================================================= % Section 2: Pattern Evaluation % ========================================================================= % ================================================== function [] = patid(varargin) % Callback for the edit box below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = str2double(get(S.patid,'String')); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nim]); % update the gui set(S.patslider,'Value',id); plotpattern(H) end % ================================================== function [] = patslider(varargin) % Callback for the slider below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = get(S.patslider,'Value'); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nim]); % update the gui set(S.patid,'String',num2str(id)); plotpattern(H) end % ================================================== function [] = patshowpat(varargin) % Button Callback: Show the pattern H = varargin{3}; S = guihandles(H); D = guidata(H); set(S.patshowpat,'BackgroundColor',D.gui.color.hl); set(S.patshowACF,'BackgroundColor',D.gui.color.bg); plotpattern(H); D.gui.activepatview = 1; guidata(H,D); end % ================================================== function [] = patshowACF(varargin) % Button Callback: Show the autocorrelation function H = varargin{3}; S = guihandles(H); D = guidata(H); set(S.patshowpat,'BackgroundColor',D.gui.color.bg); set(S.patshowACF,'BackgroundColor',D.gui.color.hl); plotacf(H); D.gui.activepatview = 2; guidata(H,D); end % ========================================================================= % Section 3: ROI and Mask % ========================================================================= % ================================================== function [] = roiid(varargin) % Callback for the edit box below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = str2double(get(S.roiid,'String')); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nim]); % update the gui set(S.roislider,'Value',id); plotroimask(H) end % ================================================== function [] = roislider(varargin) % Callback for the slider below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = get(S.roislider,'Value'); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nim]); % update the gui set(S.roiid,'String',num2str(id)); plotroimask(H) end % ================================================== function [] = masksave(varargin) % Button Callback: save the mask H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % user fileselect [filename, pathname] = uiputfile(fullfile(basedir,'mask.mat'), 'save the mask'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end % store the basename D.gui.ini.basedir.value = pathname; % save to file bgdic.mask = D.mask; bgdic.roi = D.roi; bgdic.version = D.version; bgdic.savetype = 'mask'; save('-v7.3',fullfile(pathname,filename),'bgdic') % update status D.gui.stat = appendstatus(D.gui.stat,'[3] Mask saved to file'); guidata(H,D); set(D.gui.waithandles,'Enable','on');drawnow end % ================================================== function [] = maskload(varargin) % Button Callback: load the mask H = varargin{3}; S = guihandles(H); D = guidata(H); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % user fileselect [filename, pathname] = uigetfile(fullfile(basedir,'mask.mat'), 'load the mask'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end % store the basename D.gui.ini.basedir.value = pathname; % load from file load(fullfile(pathname,filename),'bgdic') if ~exist('bgdic','var') || ~isfield(bgdic,'savetype') msgstr = 'incompatible save file'; msgdlgjn(msgstr,dlgposition(H)); set(D.gui.waithandles,'Enable','on');drawnow return end if ~strcmp(bgdic.savetype,'mask') msgstr = sprintf('incorrect save type (%s), try loading it in another section',bgdic.savetype); msgdlgjn(msgstr,dlgposition(H)); set(D.gui.waithandles,'Enable','on');drawnow return end D.mask = bgdic.mask; D.roi = bgdic.roi; if isfield(D,'savetype') D = rmfield(D,'savetype'); end % update status D.gui.stat = appendstatus(D.gui.stat,'[3] Mask loaded from file'); % update the application data guidata(H,D); set(D.gui.waithandles,'Enable','on');drawnow plotroimask(H); end % ================================================== function [] = roiset(varargin) % Button Callback: Define a region of interest H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end if isfield(D,'cor') qstr{1,1} = 'Warning: Changing the ROI will reset all results'; qstr{2,1} = 'Continue?'; button = questdlgjn(qstr,'Change the ROI','Yes','No','Yes',dlgposition(H)); if isempty(button) || strcmpi(button,'No') return end D = rmfield(D,'cor'); end if isfield(D,'res') D = rmfield(D,'res'); end % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow n = D.files(1).size(1); m = D.files(1).size(2); % Select an area set(H,'CurrentAxes',S.axes3); h = title('position the rectangle, confirm with a doubleclick'); set(h,'color',D.gui.color.axeshl); % reuse roi if isfield(D,'roi') D.roi = max([1 2 1 2;D.roi]); D.roi = min([m-1 m n-1 n;D.roi]); rect = [D.roi(1),D.roi(3) ; D.roi(2),D.roi(4)]; else rect = [0.1*m,0.1*n ; 0.9*m,0.9*n]; end % load interactive rectangle tool position = selectarea(rect); % reset the title set(h,'color','k'); title(''); roi(1) = min(position(:,1)); roi(2) = max(position(:,1)); roi(3) = min(position(:,2)); roi(4) = max(position(:,2)); D.roi = roi; % update info info(1).str = 'roi1 (x1)'; info(1).val = roi(1); info(2).str = 'roi2 (x2)'; info(2).val = roi(2); info(3).str = 'roi3 (y1)'; info(3).val = roi(3); info(4).str = 'roi4 (y2)'; info(4).val = roi(4); D.gui.info = appendinfo(D.gui.info,info); % set section indicator on set(S.secind3,'BackgroundColor',D.gui.color.on) % disable gui controls set(D.gui.waithandles,'Enable','on');drawnow % update status D.gui.stat = appendstatus(D.gui.stat,'[3] Mask saved to file'); % update the application data guidata(H,D); plotroimask(H); end % ================================================== function [] = maskset(varargin) % Button Callback: Add pixels to the Mask H = varargin{3}; modtype = varargin{4}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % load the current mask mask = D.mask; % image size n = D.files(1).size(1); m = D.files(1).size(2); % coordinate vectors x = 1:m; y = 1:n; [X, Y] = meshgrid(x,y); % get the current tool type tool = get(S.masktool,'String'); tool = tool{get(S.masktool,'Value')}; if strcmpi(tool,'rect') % update figure title set(H,'CurrentAxes',S.axes3) title('position the rectangle, confirm with a doubleclick'); % load interactive rectangle tool B = [0.4*m,0.4*n ; 0.2*m,0.2*n]; A = selectarea(B); % reset the title title(''); xlim(1) = min(A(:,1)); xlim(2) = max(A(:,1)); ylim(1) = min(A(:,2)); ylim(2) = max(A(:,2)); % get the indices inside the rect I = find(X > xlim(1) & X < xlim(2) & Y > ylim(1) & Y < ylim(2)); elseif strcmpi(tool,'ellipse') % update figure title set(H,'CurrentAxes',S.axes3) title('position the ellipse, confirm with a doubleclick'); % load interactive ellipse tool B = [0.3*m,0.3*n ; 0.3*m,0.1*n ; 0.25*m,0.3*n]; [A, P] = selectarea(B,'ellipse'); % reset the title title(''); I = inpolygon(X,Y,P(:,1),P(:,2)); I = find(I==1); elseif strcmpi(tool,'polygon') % update figure title set(H,'CurrentAxes',S.axes3) title({'draw the polygon, confirm with a doubleclick';'(right-click to add contol points)'}); % load interactive polygon tool B = [0.2*m,0.2*n ; 0.4*m,0.2*n ; 0.4*m,0.4*n ; 0.2*m,0.4*n ; 0.2*m,0.2*n]; A = selectarea(B,'Polyline'); % reset the title title(''); I = inpolygon(X,Y,A(:,1),A(:,2)); I = find(I==1); elseif strcmpi(tool,'bspline') % update figure title set(H,'CurrentAxes',S.axes3) title({'draw the bspline, confirm with a doubleclick';'(right-click to add contol points)'}); % load interactive polygon tool B = [0.2*m,0.2*n ; 0.4*m,0.2*n ; 0.4*m,0.4*n ; 0.2*m,0.4*n ; 0.2*m,0.2*n]; [A, P] = selectarea(B,'BSpline',3); % reset the title title(''); I = inpolygon(X,Y,P(:,1),P(:,2)); I = find(I==1); elseif strncmpi(tool,'spot',4) % update figure title set(H,'CurrentAxes',S.axes3) title('select a spot'); % ask the user to select a spot B = ginputjn(1); % reset the title title(''); if strcmpi(tool,'spot 5px') R = 5; elseif strcmpi(tool,'spot 10px') R = 10; elseif strcmpi(tool,'spot 50px') R = 50; end I = find( (X - B(1,1)).^2 + (Y - B(1,2)).^2 < R^2); end if strcmp(modtype,'add') mask = union(mask(:),I(:)); elseif strcmp(modtype,'del') mask = setdiff(mask(:),I(:)); elseif strcmp(modtype,'intersect') mask = intersect(mask(:),I(:)); end mask = mask(:); % maskimage Im = maskimage(mask,n,m); D.mask = mask; % update info info(1).str = 'mask Npx'; info(1).val = length(mask); D.gui.info = appendinfo(D.gui.info,info); % update status D.gui.stat = appendstatus(D.gui.stat,['[3] Mask modified (' modtype ')']); % update the application data guidata(H,D); set(D.gui.waithandles,'Enable','on');drawnow plotroimask(H); end % ================================================== function [] = maskinvert(varargin) % Button Callback: Invert the mask H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % image size n = D.files(1).size(1); m = D.files(1).size(2); % get the old mask mask = D.mask; % maskimage Im = maskimage(mask,n,m); % invert Im = ~Im; % back to mask index D.mask = maskindex(Im); % update info info(1).str = 'mask Npx'; info(1).val = length(D.mask); D.gui.info = appendinfo(D.gui.info,info); % update status D.gui.stat = appendstatus(D.gui.stat,'[3] Mask modified (invert)'); % update the application data guidata(H,D); plotroimask(H); end % ================================================== function [] = maskclear(varargin) % Button Callback: clear the mask H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end % back to mask index D.mask = []; % update info info(1).str = 'mask Npx'; info(1).val = length(D.mask); D.gui.info = appendinfo(D.gui.info,info); % update status D.gui.stat = appendstatus(D.gui.stat,'[3] Mask cleared'); % update the application data guidata(H,D); plotroimask(H); end % ========================================================================= % Section 4: Initial Guess % ========================================================================= % ================================================== function [] = iguesssave(varargin) % Button Callback: save the initial guess H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end if ~isfield(D,'iguess') msgstr = {'This action requires an initial guess,';'create an initial guess in section 4'}; msgdlgjn(msgstr,dlgposition(H)); return; end % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % user fileselect [filename, pathname] = uiputfile(fullfile(basedir,'iguess.mat'), 'save the initial guess'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end % store the basename D.gui.ini.basedir.value = pathname; % save to file bgdic.iguess = D.iguess; bgdic.version = D.version; bgdic.savetype = 'iguess'; save('-v7.3',fullfile(pathname,filename),'bgdic') % update status D.gui.stat = appendstatus(D.gui.stat,'[4] Initial guess saved to file'); % update the application data guidata(H,D); set(D.gui.waithandles,'Enable','on');drawnow end % ================================================== function [] = iguessload(varargin) % Button Callback: load the initial guess H = varargin{3}; S = guihandles(H); D = guidata(H); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % user fileselect [filename, pathname] = uigetfile(fullfile(basedir,'iguess.mat'), 'save the initial guess'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end % store the basename D.gui.ini.basedir.value = pathname; % load from file load(fullfile(pathname,filename),'bgdic') if ~exist('bgdic','var') || ~isfield(bgdic,'savetype') msgstr = 'incompatible save file'; msgdlgjn(msgstr,dlgposition(H)); set(D.gui.waithandles,'Enable','on');drawnow return end if ~strcmp(bgdic.savetype,'iguess') msgstr = sprintf('incorrect save type (%s), try loading it in another section',bgdic.savetype); msgdlgjn(msgstr,dlgposition(H)); set(D.gui.waithandles,'Enable','on');drawnow return end D.iguess = bgdic.iguess; if isfield(D,'savetype') D = rmfield(D,'savetype'); end % update status D.gui.stat = appendstatus(D.gui.stat,'[4] Initial guess loaded from file'); % update the application data guidata(H,D); set(D.gui.waithandles,'Enable','on');drawnow plotiguess(H); end % ================================================== function [] = iguessid(varargin) % Callback for the edit box below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = str2double(get(S.iguessid,'String')); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nim]); % update the gui set(S.iguessslider,'Value',id); plotiguess(H) end % ================================================== function [] = iguessslider(varargin) % Callback for the slider below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = get(S.iguessslider,'Value'); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nim]); % update the gui set(S.iguessid,'String',num2str(id)); plotiguess(H) end % ================================================== function [] = iguessimprocess(varargin) % Button Callback: process the images H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % update status D.gui.stat = appendstatus(D.gui.stat,'[4] Image processing started'); N = length(D.files); n = D.files(1).size(1); m = D.files(1).size(2); x = 1:m; y = 1:n; % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get settings Rblur = str2double(get(S.iguessblur,'String')); gradtype = get(S.iguessimprocesstype,'String'); gradtype = gradtype(get(S.iguessimprocesstype,'Value')); for k = 1:N bcwaitbar(H,k/N,sprintf('processing images (%d/%d)',k,N)); Im = D.files(k).image; % blur % =========== if Rblur > 0.3 Im = image_blur(Im,Rblur); end % gradient transform % =========== if ~strcmp(gradtype,'none') [dImdx, dImdy] = gradient(Im); end if strcmp(gradtype,'grad|xy|'); Im = sqrt(dImdx.^2+dImdy.^2); elseif strcmp(gradtype,'grad|x|'); Im = abs(dImdx); elseif strcmp(gradtype,'grad|y|'); Im = abs(dImdy); elseif strcmp(gradtype,'grad(xy)'); Im = 0.5*(dImdx+dImdy); elseif strcmp(gradtype,'grad(x)'); Im = dImdx; elseif strcmp(gradtype,'grad(y)'); Im = dImdy; end % store D.files(k).imageproc = Im; end % update status D.gui.stat = appendstatus(D.gui.stat,'[4] Image processing done'); % update the application data guidata(H,D); % enable gui controls set(D.gui.waithandles,'Enable','on'); bcwaitbar(H); plotiguess(H); end % ================================================== function [] = iguessaddauto(varargin) % Button Callback: apply local DIC to get initial guess H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end if isfield(D.files,'imageproc') Img = {D.files.imageproc}; elseif isfield(D.files,'image') Img = {D.files.image}; else msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % update status D.gui.stat = appendstatus(D.gui.stat,'[4] Auto initial guess routine started'); N = length(D.files); n = D.files(1).size(1); m = D.files(1).size(2); x = 1:m; y = 1:n; % get previous guesses if isfield(D,'iguess') iguess = D.iguess; Niguess = length(iguess.x); else iguess.x = []; iguess.y = []; iguess.ux = []; iguess.uy = []; iguess.cc = []; Niguess = 0; end % % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % Ask for iguess options dlg_title = 'Automatic initial guess options'; prompt = {'Subset Size',... 'Search Size',... 'Subset Rows',... 'Subset Cols',... 'Updated'}; def{1} = D.gui.ini.iguesssubsetsize.value; def{2} = D.gui.ini.iguesssearchsize.value; def{3} = D.gui.ini.iguesssubsetrows.value; def{4} = D.gui.ini.iguesssubsetcols.value; def{5} = D.gui.ini.iguessupdated.value; num_lines = 1; answer = inputdlgjn(prompt,dlg_title,num_lines,def,dlgposition(H)); if isempty(answer) set(D.gui.waithandles,'Enable','on'); return end Lzoi = eval(answer{1}); Lsearch = eval(answer{2}); Nrows = eval(answer{3}); Ncols = eval(answer{4}); updated = eval(answer{5}); % store the defaults D.gui.ini.iguesssubsetsize.value = answer{1}; D.gui.ini.iguesssearchsize.value = answer{2}; D.gui.ini.iguesssubsetrows.value = answer{3}; D.gui.ini.iguesssubsetcols.value = answer{4}; D.gui.ini.iguessupdated.value = answer{5}; % re-use roi if isfield(iguess,'box') box = iguess.box; rect = [box(1),box(3) ; box(2),box(4)]; elseif isfield(D,'roi') rect = [D.roi(1),D.roi(3) ; D.roi(2),D.roi(4)]; else rect = [0.1*m 0.1*n 0.8*m 0.8*n]; end % Select an area set(H,'CurrentAxes',S.axes41); h = title('position the rectangle, confirm with a doubleclick'); set(h,'color',D.gui.color.axeshl); % load interactive rectangle tool position = selectarea(rect); % reset the title set(h,'color','k'); title(''); % store the rectangle for later use box(1) = min(position(:,1)); box(2) = max(position(:,1)); box(3) = min(position(:,2)); box(4) = max(position(:,2)); iguess.box = box; % ZOI must be at least 10 pixels if Lzoi < 10 Lzoi = 10; end % Search ZOI must be bigger than ZOI if Lsearch < round(1.1*Lzoi) Lsearch = round(1.1*Lzoi); end Nrows = max([Nrows 1]); Ncols = max([Ncols 1]); Nzoi = Ncols*Nrows; % create subset center locations boxedge = min([D.gui.ini.iguessboxedge.value 0.1*Lzoi]); if Nzoi == 1 xc = mean(box([1,2])); yc = mean(box([3,4])); elseif Nrows == 1 xc = linspace(box(1)+boxedge,box(2)-boxedge,Ncols); yc = mean(box([3,4])); elseif Ncols == 1 xc = mean(box([1,2])); yc = linspace(box(3)+boxedge,box(4)-boxedge,Nrows); else xc = linspace(box(1)+boxedge,box(2)-boxedge,Ncols); yc = linspace(box(3)+boxedge,box(4)-boxedge,Nrows); end % store initial guess locations (centers of ZOI) [Xc, Yc] = meshgrid(xc,yc); % create ZOI corner coordinate vectors zoiX = [Xc(:)-0.5*Lzoi Xc(:)+0.5*Lzoi Xc(:)+0.5*Lzoi Xc(:)-0.5*Lzoi]; zoiY = [Yc(:)-0.5*Lzoi Yc(:)-0.5*Lzoi Yc(:)+0.5*Lzoi Yc(:)+0.5*Lzoi]; searchX = [Xc(:)-0.5*Lsearch Xc(:)+0.5*Lsearch Xc(:)+0.5*Lsearch Xc(:)-0.5*Lsearch]; searchY = [Yc(:)-0.5*Lsearch Yc(:)-0.5*Lsearch Yc(:)+0.5*Lsearch Yc(:)+0.5*Lsearch]; % store for plotting later on iguess.subset.X = zoiX'; iguess.subset.Y = zoiY'; % for each image for id = 1:N bcwaitbar(H,id/N,sprintf('correlating increment (%d/%d)',id,N)); % for each initial guess location for kz = 1:Nzoi if id == 1 % if first image, iguess = 0 iguess.x(Niguess+kz,id) = Xc(kz); iguess.y(Niguess+kz,id) = Yc(kz); iguess.ux(Niguess+kz,id) = 0; iguess.uy(Niguess+kz,id) = 0; else % get pixel indices for the search ZOI Ima = find(x >= searchX(kz,1) & x <= searchX(kz,2)); Ina = find(y >= searchY(kz,2) & y <= searchY(kz,3)); % get second image (g) xg = x(Ima); yg = y(Ina); g = Img{id}(Ina,Ima); [n, m] = size(g); % fill f with correct pixels (placed in the center, with % boundary of zeros) if updated % using the previous image as reference f = Img{id-1}(y >= zoiY(kz,2) & y <= zoiY(kz,3),x >= zoiX(kz,1) & x <= zoiX(kz,2)); else % using the first image as reference f = Img{1}(y >= zoiY(kz,2) & y <= zoiY(kz,3),x >= zoiX(kz,1) & x <= zoiX(kz,2)); end % zero-normalize f meanf = mean(f(:)); stdf = std(f(:)); ff = (f-meanf)./stdf; % zero-normalize g meang = mean(g(:)); stdg = std(g(:)); g = (g-meang)./stdg; % assign f in the zeropadded large image f = zeros(n,m); f(yg >= zoiY(kz,2) & yg <= zoiY(kz,3),xg >= zoiX(kz,1) & xg <= zoiX(kz,2)) = ff; % Cross-Correlation Function (ccf) displacement space, these % coordinates are very typical because of the way matlab % returns the CCF if updated ux = 1:0.5:m; uy = 1:0.5:n; else ux = 1:m; uy = 1:n; end ux = ux - ux(floor(length(ux)/2)+1); uy = uy - uy(floor(length(uy)/2)+1); [Ux, Uy] = meshgrid(ux,uy); Ux = ifftshift(Ux); Uy = ifftshift(Uy); % interpolate f and g for the updated case (add one pixel % inbetween each pixel). This is to enhance accuracy to % mitigate the accumulation of errors in the update method. if updated f = interp2(f,1,'linear'); g = interp2(g,1,'linear'); end % normalize the image scale = sqrt( sum(f(:).^2) * sum(g(:).^2) ); % Cross-Correlation function ccf = ifft2( conj(fft2(f)) .* fft2(g) ) ./ scale; % find the maximum in the ccf (location of best correlation) [cc,I] = max(ccf(:)); % store displacement belonging to the maximum if updated dux = Ux(I); duy = Uy(I); zoiX(kz,:) = zoiX(kz,:) + dux; zoiY(kz,:) = zoiY(kz,:) + duy; searchX(kz,:) = searchX(kz,:) + dux; searchY(kz,:) = searchY(kz,:) + duy; iguess.ux(Niguess+kz,id) = iguess.ux(Niguess+kz,id-1) + dux; iguess.uy(Niguess+kz,id) = iguess.uy(Niguess+kz,id-1) + duy; iguess.cc(Niguess+kz,id) = cc; else iguess.ux(Niguess+kz,id) = Ux(I); iguess.uy(Niguess+kz,id) = Uy(I); iguess.cc(Niguess+kz,id) = cc; end end end % update the application data D.iguess = iguess; guidata(H,D); % update the figure set(S.iguessid,'String',num2str(id)); set(S.iguessslider,'Value',id); drawnow plotiguess(H) end % test if new guesses are reasonable, delete an initial guess point if the % displacement any any frame was bigger than 30% of the search box (30% % seen from the center means the point moved to within 20% of the edge) Lreject = D.gui.ini.iguessreject.value*Lsearch; if updated failx = sum(abs(diff(D.iguess.ux(end-Nzoi+1:end,:),[],2)) > Lreject,2); faily = sum(abs(diff(D.iguess.uy(end-Nzoi+1:end,:),[],2)) > Lreject,2); else failx = sum(abs(D.iguess.ux(end-Nzoi+1:end,:)) > Lreject,2); faily = sum(abs(D.iguess.uy(end-Nzoi+1:end,:)) > Lreject,2); end I = find(failx > 0 | faily > 0); D.iguess.x(Niguess+I,:) = []; D.iguess.y(Niguess+I,:) = []; D.iguess.ux(Niguess+I,:) = []; D.iguess.uy(Niguess+I,:) = []; % update info info(1).str = 'Niguess'; info(1).val = length(D.iguess.x); D.gui.info = appendinfo(D.gui.info,info); % update status D.gui.stat = appendstatus(D.gui.stat,'[4] Auto initial guess routine done'); bcwaitbar(H); % update the application data guidata(H,D); % enable gui controls set(D.gui.waithandles,'Enable','on'); drawnow plotiguess(H) end % ================================================== function [] = iguessaddmanual(varargin) % Button Callback: Add manual initial guess point H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end if isfield(D.files,'image') ImgA = {D.files.image}; else return end if isfield(D.files,'imageproc') ImgB = {D.files.imageproc}; elseif isfield(D.files,'image') ImgB = {D.files.image}; else return end % update status D.gui.stat = appendstatus(D.gui.stat,'[4] Manual initial guess routine started'); % get image properties N = length(ImgA); [n, m] = size(ImgA{1}); x = 1:m; y = 1:n; % get previous guesses if isfield(D,'iguess') iguess = D.iguess; Niguess = length(iguess.x); else iguess.x = []; iguess.y = []; iguess.ux = []; iguess.uy = []; Niguess = 0; end % get zoom options zoomsize = str2double(get(S.iguesszoomsize,'String')); zoomselect = get(S.iguesszoomselect,'Value'); % % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % initialize the reference coordinate refx = []; refy = []; % for each image frame for k = 1:N % update the figure set(S.iguessid,'String',num2str(k)); set(S.iguessslider,'Value',k); drawnow % plot the four images for ka = 1:4 if ka == 1 A = ImgA{1}; ha = S.axes41; id = 1; titlestr = sprintf('id:%d %s',1,'original'); tag = 'iguess_image1'; elseif ka == 2 A = ImgA{k}; ha = S.axes42; id = k; titlestr = sprintf('id:%d %s',k,'original'); tag = 'iguess_image2'; elseif ka == 3 A = ImgB{1}; ha = S.axes43; id = 1; titlestr = sprintf('id:%d %s',1,'processed'); tag = 'iguess_image3'; elseif ka == 4 A = ImgB{k}; ha = S.axes44; id = k; titlestr = sprintf('id:%d %s',k,'processed'); tag = 'iguess_image4'; end % change the image set(H,'CurrentAxes',ha) hi = findobj(H,'Tag',tag); set(hi,'CData',A); title(titlestr) htxt = text(0.01,0.03,sprintf('%d/%d',id,N),'units','normalized'); set(htxt,'color',D.gui.color.fg) set(htxt,'FontSize',D.gui.fontsize(3)) set(htxt,'FontWeight','bold') end % change the border color, to indicate where to look if k == 1 % first image. look left top set(H,'CurrentAxes',S.axes42) set(gca,'Xcolor','k') set(gca,'Ycolor','k') set(H,'CurrentAxes',S.axes41) set(gca,'Xcolor',D.gui.color.axeshl) set(gca,'Ycolor',D.gui.color.axeshl) else % consecutive images, look right top set(H,'CurrentAxes',S.axes41) set(gca,'Xcolor','k') set(gca,'Ycolor','k') set(H,'CurrentAxes',S.axes42) set(gca,'Xcolor',D.gui.color.axeshl) set(gca,'Ycolor',D.gui.color.axeshl) end % if using zoom select, zoom the image if zoomselect if k == 1 % for the first image, select where to zoom ht = title('Select zoom area (i.e. a material point)'); set(ht,'color',D.gui.color.axeshl); % using own variant of ginput, to create a more visible cursor [xc, yc] = ginputjn(1); xlim = xc + [-0.5 0.5]*zoomsize; ylim = yc + [-0.5 0.5]*zoomsize; else % for other images, don't ask, but center the FOV on the % previous location set(ht,'color',D.gui.color.axeshl); xlim = lastx + [-0.5 0.5]*zoomsize; ylim = lasty + [-0.5 0.5]*zoomsize; end if k == 1 % for the first image only zoom the left axes set(S.axes41,'xlim',xlim); set(S.axes41,'ylim',ylim); set(S.axes43,'xlim',xlim); set(S.axes43,'ylim',ylim); else % for the other images zoom the right axes set(S.axes42,'xlim',xlim); set(S.axes42,'ylim',ylim); set(S.axes44,'xlim',xlim); set(S.axes44,'ylim',ylim); % center the zoom around the reference location for the left % axes xlim = refx + [-0.5 0.5]*zoomsize; ylim = refy + [-0.5 0.5]*zoomsize; set(S.axes41,'xlim',xlim); set(S.axes41,'ylim',ylim); set(S.axes43,'xlim',xlim); set(S.axes43,'ylim',ylim); end end % prepare axes for material point selection ht = title('Select material point'); set(ht,'color',D.gui.color.axeshl); % select the material point if k == 1 % if first image, this is the reference [refx, refy] = ginputjn(1); defx = refx; defy = refy; defk = k; lastx = refx; lasty = refy; % Plot the reference href = findobj(H,'Tag','iguess_pointscref'); if ~isempty(href); set(href,'XData',refx,'YData',refy); else set(H,'CurrentAxes',S.axes41) set(gca,'NextPlot','add') plot(refx,refy,'*','Color',D.gui.color.fg,'Markersize',D.gui.markersize,'Tag','iguess_pointscref') set(H,'CurrentAxes',S.axes42) set(gca,'NextPlot','add') plot(refx,refy,'*','Color',D.gui.color.fg,'Markersize',D.gui.markersize,'Tag','iguess_pointscref') set(H,'CurrentAxes',S.axes43) set(gca,'NextPlot','add') plot(refx,refy,'*','Color',D.gui.color.fg,'Markersize',D.gui.markersize,'Tag','iguess_pointscref') set(H,'CurrentAxes',S.axes44) set(gca,'NextPlot','add') plot(refx,refy,'*','Color',D.gui.color.fg,'Markersize',D.gui.markersize,'Tag','iguess_pointscref') end % Plot the deformed hdef = findobj(H,'Tag','iguess_pointscdef'); if ~isempty(hdef); set(hdef,'XData',defx,'YData',defy); else set(H,'CurrentAxes',S.axes42) set(gca,'NextPlot','add') plot(defx,defy,'.','Color',D.gui.color.fg,'Markersize',D.gui.markersize,'Tag','iguess_pointscdef') set(H,'CurrentAxes',S.axes44) set(gca,'NextPlot','add') plot(defx,defy,'.','Color',D.gui.color.fg,'Markersize',D.gui.markersize,'Tag','iguess_pointscdef') end drawnow else % if other image, this is a deformed location [defx(k), defy(k), but] = ginputjn(1); if but == 3 % if the right button is used, this frame is skipped, store % NaNs instead. defx(k) = NaN; defy(k) = NaN; defk(k) = NaN; else % otherwise store new material point location lastx = defx(k); lasty = defy(k); defk(k) = k; end hdef = findobj(H,'Tag','iguess_pointscdef'); if ~isempty(hdef); set(hdef,'XData',defx,'YData',defy); else set(H,'CurrentAxes',S.axes42) set(gca,'NextPlot','add') plot(refx,refy,'.','Color',D.gui.color.fg,'Markersize',D.gui.markersize,'Tag','iguess_pointscdef') set(H,'CurrentAxes',S.axes44) set(gca,'NextPlot','add') plot(refx,refy,'.','Color',D.gui.color.fg,'Markersize',D.gui.markersize,'Tag','iguess_pointscdef') drawnow end end end % clear the selection points delete(findobj(H,'Tag','iguess_pointscref')); delete(findobj(H,'Tag','iguess_pointscdef')); % Interpolate skipped frames % ================= % prepare some data x = refx; y = refy; ux = defx(~isnan(defx)) - x; uy = defy(~isnan(defy)) - y; k = defk(~isnan(defk)); % interpolate if ux < N i = 1:N; ux = interp1(k,ux,i,'linear','extrap'); uy = interp1(k,uy,i,'linear','extrap'); end % reset the axes to the default colors ha = [S.axes41,S.axes42,S.axes43,S.axes44]; for k = 1:4 set(get(ha(k),'title'),'Color','k'); set(ha(k),'Xcolor','k','Ycolor','k') set(ha(k),'Xlim',[1, m],'Ylim',[1, n]); end % store the new initial guess points D.iguess.x(Niguess+1,1) = x; D.iguess.y(Niguess+1,1) = y; D.iguess.ux(Niguess+1,:) = ux; D.iguess.uy(Niguess+1,:) = uy; % update info info(1).str = 'Niguess'; info(1).val = length(D.iguess.x); D.gui.info = appendinfo(D.gui.info,info); % update status D.gui.stat = appendstatus(D.gui.stat,'[4] Manual initial guess routine done'); % update the application data guidata(H,D); plotiguess(H) % enable gui controls set(D.gui.waithandles,'Enable','on'); end % ================================================== function [] = iguessframezero(varargin) % Button Callback: Zero all the points in this frame H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'iguess') msgstr = {'This action requires an initial guess for all frames,';'create one by pressing <Add auto> or <Add manual>'}; msgdlgjn(msgstr,dlgposition(H)); return end if isempty(D.iguess.x) return end % get current frame id = str2double(get(S.iguessid,'String')); D.iguess.ux(:,id) = 0; D.iguess.uy(:,id) = 0; % update status D.gui.stat = appendstatus(D.gui.stat,sprintf('[4] Initial guess set to zero for frame %d',id)); % update the application data guidata(H,D); plotiguess(H) end % ================================================== function [] = iguessframeauto(varargin) % Button Callback: Perform auto iguess for this frame % this function is very similar to the iguessaddauto, see the comments in % that function for more info. H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end if ~isfield(D,'iguess') msgstr = {'This action requires an initial guess for some frames,';'create one by pressing <Add auto> or <Add manual>'}; msgdlgjn(msgstr,dlgposition(H)); return end if isempty(D.iguess.x) return end iguess = D.iguess; % get current frame id = str2double(get(S.iguessid,'String')); if id == 1 return end if isfield(D.files,'imageproc') Img = {D.files.imageproc}; elseif isfield(D.files,'image') Img = {D.files.image}; else msgstr = {'This action requires an initial guess for some frames,';'create one by pressing <Add auto> or <Add manual>'}; msgdlgjn(msgstr,dlgposition(H)); return; end % % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % coordinate space [n, m] = size(Img{1}); x = 1:m; y = 1:n; % Ask for iguess options dlg_title = 'Automatic initial guess options'; prompt = {'Subset Size',... 'Search Size',... 'Updated'}; def{1} = D.gui.ini.iguesssubsetsize.value; def{2} = D.gui.ini.iguesssearchsize.value; def{3} = D.gui.ini.iguessupdated.value; num_lines = 1; answer = inputdlgjn(prompt,dlg_title,num_lines,def,dlgposition(H)); if isempty(answer) % enable gui controls set(D.gui.waithandles,'Enable','on'); return end Lzoi = eval(answer{1}); Lsearch = eval(answer{2}); updated = eval(answer{3}); % store the defaults D.gui.ini.iguesssubsetsize.value = answer{1}; D.gui.ini.iguesssearchsize.value = answer{2}; D.gui.ini.iguessupdated.value = answer{3}; Xc = D.iguess.x; Yc = D.iguess.y; Nzoi = length(Xc); zoiX = [Xc(:)-0.5*Lzoi Xc(:)+0.5*Lzoi Xc(:)+0.5*Lzoi Xc(:)-0.5*Lzoi]; zoiY = [Yc(:)-0.5*Lzoi Yc(:)-0.5*Lzoi Yc(:)+0.5*Lzoi Yc(:)+0.5*Lzoi]; searchX = [Xc(:)-0.5*Lsearch Xc(:)+0.5*Lsearch Xc(:)+0.5*Lsearch Xc(:)-0.5*Lsearch]; searchY = [Yc(:)-0.5*Lsearch Yc(:)-0.5*Lsearch Yc(:)+0.5*Lsearch Yc(:)+0.5*Lsearch]; for kz = 1:Nzoi if mod(kz,5) == 0 bcwaitbar(H,kz/Nzoi,sprintf('correlating subset (%d/%d)',kz,Nzoi)); end if id == 1 iguess.x(kz,id) = Xc(kz); iguess.y(kz,id) = Yc(kz); iguess.ux(kz,id) = 0; iguess.uy(kz,id) = 0; else Ima = find(x >= searchX(kz,1) & x <= searchX(kz,2)); Ina = find(y >= searchY(kz,2) & y <= searchY(kz,3)); xg = x(Ima); yg = y(Ina); g = Img{id}(Ina,Ima); [n, m] = size(g); f = zeros(n,m); if updated f(yg >= zoiY(kz,2) & yg <= zoiY(kz,3),... xg >= zoiX(kz,1) & xg <= zoiX(kz,2))... = Img{id-1}(... y >= zoiY(kz,2) & y <= zoiY(kz,3),... x >= zoiX(kz,1) & x <= zoiX(kz,2)); else f(yg >= zoiY(kz,2) & yg <= zoiY(kz,3),... xg >= zoiX(kz,1) & xg <= zoiX(kz,2))... = Img{1}(... y >= zoiY(kz,2) & y <= zoiY(kz,3),... x >= zoiX(kz,1) & x <= zoiX(kz,2)); end % ccf displacement space if updated ux = 1:0.5:m; uy = 1:0.5:n; else ux = 1:m; uy = 1:n; end ux = ux - ux(floor(length(ux)/2)+1); uy = uy - uy(floor(length(uy)/2)+1); [Ux, Uy] = meshgrid(ux,uy); Ux = ifftshift(Ux); Uy = ifftshift(Uy); % interpolate f and g if updated f = interp2(f,1,'linear'); g = interp2(g,1,'linear'); end mnf = mean(f(:)); mng = mean(g(:)); fbar = f - mnf; gbar = g - mng; scale = sqrt( sum(fbar(:).^2) * sum(gbar(:).^2) ); % Cross-Correlation function ccf = ifft2( conj(fft2(fbar)) .* fft2(gbar) ) ./ scale; % find the maximum in the ccf [cc,I] = max(ccf(:)); if updated dux = Ux(I); duy = Uy(I); zoiX(kz,:) = zoiX(kz,:) + dux; zoiY(kz,:) = zoiY(kz,:) + duy; searchX(kz,:) = searchX(kz,:) + dux; searchY(kz,:) = searchY(kz,:) + duy; iguess.ux(kz,id) = iguess.ux(kz,id-1) + dux; iguess.uy(kz,id) = iguess.uy(kz,id-1) + duy; iguess.cc(kz,id) = cc; else iguess.ux(kz,id) = Ux(I); iguess.uy(kz,id) = Uy(I); iguess.cc(kz,id) = cc; end end end % update the application data D.iguess = iguess; % test if new guesses are reasonable Lreject = D.gui.ini.iguessreject.value*Lsearch; if updated failx = sum(abs(diff(D.iguess.ux(end-Nzoi+1:end,:),[],2)) > Lreject,2); faily = sum(abs(diff(D.iguess.uy(end-Nzoi+1:end,:),[],2)) > Lreject,2); else failx = sum(abs(D.iguess.ux(end-Nzoi+1:end,:)) > Lreject,2); faily = sum(abs(D.iguess.uy(end-Nzoi+1:end,:)) > Lreject,2); end I = find(failx > 0 | faily > 0); D.iguess.x(I,:) = []; D.iguess.y(I,:) = []; D.iguess.ux(I,:) = []; D.iguess.uy(I,:) = []; % update status D.gui.stat = appendstatus(D.gui.stat,sprintf('[4] Auto initial guess performed for frame %d',id)); bcwaitbar(H); % update the application data guidata(H,D); plotiguess(H) % enable gui controls set(D.gui.waithandles,'Enable','on'); end % ================================================== function [] = iguessframeint(varargin) % Button Callback: Interpolate the initial guess for this from fom other % frames H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'iguess') msgstr = {'This action requires an initial guess for all frames,';'create one by pressing <Add auto> or <Add manual>'}; msgdlgjn(msgstr,dlgposition(H)); return end if isempty(D.iguess.x) return end iguess = D.iguess; % get current frame id = str2double(get(S.iguessid,'String')); if id == 1 return end ux = iguess.ux; uy = iguess.uy; [N, Nid] = size(ux); % time vector ti = 1:Nid; t = 1:Nid; % remove the time values for the current frame t(id) = []; % remove the displacements for hte current frame ux(:,id) = []; uy(:,id) = []; % assignin('base','ux',ux) % assignin('base','uy',ux) % assignin('base','t',t) % assignin('base','ti',ti) % interpolate for k = 1:N if mod(k,5) == 0 bcwaitbar(H,k/N,sprintf('interpolating subset (%d/%d)',k,N)); end uxi(k,:) = interp1(t,ux(k,:),ti,'linear','extrap'); uyi(k,:) = interp1(t,uy(k,:),ti,'linear','extrap'); end D.iguess.ux = uxi; D.iguess.uy = uyi; % update status D.gui.stat = appendstatus(D.gui.stat,sprintf('[4] Initial guess for frame %d interpolated from other frames',id)); bcwaitbar(H); % update the application data guidata(H,D); plotiguess(H) end % ================================================== function [] = iguessdelone(varargin) % Button Callback: Delete an initial guess point (nearest one to click) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'iguess') msgstr = {'This action requires an initial guess,';'create an initial guess in section 4'}; msgdlgjn(msgstr,dlgposition(H)); return end if isempty(D.iguess.x) return end iguess = D.iguess; x = iguess.x; y = iguess.y; N = length(x); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % prepare axes set(H,'CurrentAxes',S.axes41) ht = title('Select material point'); set(ht,'color',D.gui.color.axeshl); h = findobj(H,'type','patch'); delete(h); % select material point [xc, yc] = ginputjn(1); set(ht,'color','k'); title(''); % compute the distances from selection to all points R = sqrt( (x-xc).^2 + (y-yc).^2 ); % find the nearest one [~, I] = sort(R); del = I(1); keep = 1:N; keep = setdiff(keep,del); iguess.x = iguess.x(keep); iguess.y = iguess.y(keep); iguess.ux = iguess.ux(keep,:); iguess.uy = iguess.uy(keep,:); D.iguess = iguess; % update info info(1).str = 'Niguess'; info(1).val = length(D.iguess.x); D.gui.info = appendinfo(D.gui.info,info); % update status D.gui.stat = appendstatus(D.gui.stat,'[4] One initial guess point deleted'); if isempty(iguess.x) D = rmfield(D,'iguess'); end % update the application data guidata(H,D); plotiguess(H) % enable gui controls set(D.gui.waithandles,'Enable','on'); end % ================================================== function [] = iguessdelbox(varargin) % Button Callback: Delete initial guess points selected by a box H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'iguess') msgstr = {'This action requires an initial guess,';'set the initial guess in section 4'}; msgdlgjn(msgstr,dlgposition(H)); return; end if isempty(D.iguess.x) return end % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow iguess = D.iguess; x = iguess.x; y = iguess.y; n = D.files(1).size(1); m = D.files(1).size(2); N = length(x); % Select an area set(H,'CurrentAxes',S.axes41); h = title('position the rectangle, confirm with a doubleclick'); set(h,'color',D.gui.color.axeshl); % position the box rect = [0.2*m,0.2*n ; 0.4*m,0.4*n]; A = [rect(1,1),rect(1,2);rect(2,1),rect(1,2);rect(2,1),rect(2,2);rect(1,1),rect(2,2);rect(1,1),rect(1,2)]; % load interactive rectangle tool A = selectarea(A,'Polyline'); % reset the title set(h,'color','k'); title(''); del = find(inpolygon(x,y,A(:,1),A(:,2))); keep = 1:N; keep = setdiff(keep,del); iguess.x = iguess.x(keep); iguess.y = iguess.y(keep); iguess.ux = iguess.ux(keep,:); iguess.uy = iguess.uy(keep,:); D.iguess = iguess; % update info info(1).str = 'Niguess'; info(1).val = length(D.iguess.x); D.gui.info = appendinfo(D.gui.info,info); % update status stat = sprintf('[4] %d initial guess points deleted',length(del)); D.gui.stat = appendstatus(D.gui.stat,stat); if isempty(iguess.x) D = rmfield(D,'iguess'); end % update the application data guidata(H,D); plotiguess(H) % enable gui controls set(D.gui.waithandles,'Enable','on'); end % ================================================== function [] = iguessdelall(varargin) % Button Callback: Delete all initial guess points H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'iguess') msgstr = {'This action requires an initial guess,';'set the initial guess in section 4'}; msgdlgjn(msgstr,dlgposition(H)); return; end % delete the initial guess D = rmfield(D,'iguess'); % update info info(1).str = 'Niguess'; info(1).val = 0; D.gui.info = appendinfo(D.gui.info,info); % update status D.gui.stat = appendstatus(D.gui.stat,'[4] All initial guess point deleted'); % update the application data guidata(H,D); plotiguess(H); end % ========================================================================= % Section 5: Basis % ========================================================================= % ================================================== function [] = basissave(varargin) % Button Callback: save the basis functions H = varargin{3}; S = guihandles(H); D = guidata(H); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % user fileselect [filename, pathname] = uiputfile(fullfile(basedir,'basis.mat'), 'save the basis'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end % store the basename D.gui.ini.basedir.value = pathname; % save to file bgdic.basis = D.basis; bgdic.version = D.version; bgdic.savetype = 'basis'; save('-v7.3',fullfile(pathname,filename),'bgdic') % update status D.gui.stat = appendstatus(D.gui.stat,'[5] Basis saved to file'); % update the application data guidata(H,D); set(D.gui.waithandles,'Enable','on');drawnow end % ================================================== function [] = basisload(varargin) % Button Callback: load the bases H = varargin{3}; S = guihandles(H); D = guidata(H); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % user fileselect [filename, pathname] = uigetfile(fullfile(basedir,'basis.mat'), 'load a basis'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end % store the basename D.gui.ini.basedir.value = pathname; % load from file load(fullfile(pathname,filename),'bgdic') if ~exist('bgdic','var') || ~isfield(bgdic,'savetype') msgstr = 'incompatible save file'; msgdlgjn(msgstr,dlgposition(H)); set(D.gui.waithandles,'Enable','on');drawnow return end if ~strcmp(bgdic.savetype,'basis') msgstr = sprintf('incorrect save type (%s), try loading it in another section',bgdic.savetype); msgdlgjn(msgstr,dlgposition(H)); set(D.gui.waithandles,'Enable','on');drawnow return end % load the basis functions D.basis = bgdic.basis; if isfield(D,'savetype') D = rmfield(D,'savetype'); end % build the plotphi if isfield(D,'files') && isfield(D,'roi') [n, m] = size(D.files(1).image); % number of pixels (in x-dir) to use to generate plot versions of the basis Nplot = 300; plotx = linspace(1,m,Nplot); ploty = linspace(1,n,round(n*Nplot/m)); Nb = length(D.basis); for k = 1:Nb % computing the plot shapes D.basis(k).plotx = plotx; D.basis(k).ploty = ploty; D.basis(k).plotphi = phibuild(plotx,ploty,D.roi,D.basis(k),H,'single'); D.basis(k).Nphi = size(D.basis(k).plotphi,2); end end % update status D.gui.stat = appendstatus(D.gui.stat,'[5] Basis loaded from file'); % update the application data guidata(H,D); drawnow; basisset(H); set(D.gui.waithandles,'Enable','on');drawnow plotbasis([],[],H); end % ================================================== function [] = phiid(varargin) % Callback for the edit box below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'basis') return; end k = get(S.basislist,'Value'); Nphi = D.basis(k).Nphi; % get the updated id id = str2double(get(S.phiid,'String')); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nphi]); % update the gui set(S.phislider,'Value',id); plotbasis([],[],H); end % ================================================== function [] = phislider(varargin) % Callback for the slider below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'basis') return; end k = get(S.basislist,'Value'); Nphi = D.basis(k).Nphi; % get the updated id id = get(S.phislider,'Value'); % rounding and limits id = round(id); id = max([id 1]); id = min([id Nphi]); % update the gui set(S.phiid,'String',num2str(id)); plotbasis([],[],H); end % ================================================== function [] = basislist(varargin) % Button Callback: Change the currently active basis set H = varargin{3}; S = guihandles(H); D = guidata(H); % get the selected basis basislst = get(S.basislist,'String'); id = get(S.basislist,'Value'); if ~isfield(D,'basis') || (length(D.basis) < id) || isempty(D.basis(id).name) set(S.basistype,'Value',D.gui.ini.basistype.value); set(S.basisname,'String',sprintf('basis %d',id)); set(S.basisboundary,'String',D.gui.ini.basisboundary.value); set(S.basisrows,'String',D.gui.ini.basisrows.value); set(S.basiscols,'String',D.gui.ini.basiscols.value); set(S.basisorder,'String',D.gui.ini.basisorder.value); basistype([],[],H) return else set(S.basistype,'Value',D.basis(id).typeval); set(S.basisname,'String',D.basis(id).name); set(S.basisboundary,'String',D.basis(id).boundratio); set(S.basisrows,'String',D.basis(id).Nrows); set(S.basiscols,'String',D.basis(id).Ncols); set(S.basisorder,'String',D.basis(id).order); basistype([],[],H) end % update sliders phiid = str2double(get(S.phiid,'String')); if ~isfield(D.basis,'plotphi') || isempty(D.basis(id).plotphi) Nphi = 1; else Nphi = size(D.basis(id).plotphi,2); end phiid = min([phiid Nphi]); % setting the maximum slider position slidermax = max([Nphi 2]); sliderstep = [1/(slidermax-1) 10/(slidermax-1)]; % update sliders (related to basis functions) set(S.phiid,'String',num2str(phiid)) set(S.phislider,'Max',slidermax) set(S.phislider,'Sliderstep',sliderstep) set(S.phislider,'Value',phiid) plotbasis([],[],H); end % ================================================== function [] = basisnew(varargin) % Button Callback: Add a new basis set H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % get the selected basis basislst = get(S.basislist,'String'); id = get(S.basislist,'Value'); Nb = length(basislst); str = sprintf('basis %d',Nb+1); basislst{Nb+1} = str; set(S.basislist,'String',basislst); set(S.basislist,'Value',Nb+1); D.basis(Nb+1).name = []; % initiate defaults set(S.basistype,'Value',D.gui.ini.basistype.value); set(S.basisname,'String',sprintf('basis %d',Nb+1)); set(S.basisboundary,'String',D.gui.ini.basisboundary.value); set(S.basisrows,'String',D.gui.ini.basisrows.value); set(S.basiscols,'String',D.gui.ini.basiscols.value); set(S.basisorder,'String',D.gui.ini.basisorder.value); % update the application data guidata(H,D); basistype([],[],H) end % ================================================== function [] = basisdel(varargin) % Button Callback: Delete a basis set H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % get the selected basis basislst = get(S.basislist,'String'); id = get(S.basislist,'Value'); Nb = length(basislst); I = setdiff(1:Nb,id); basislst = basislst(I); D.basis = D.basis(I); set(S.basislist,'String',basislst); if id == 1 set(S.basislist,'Value',id); else set(S.basislist,'Value',id-1); end % update the application data guidata(H,D); if isempty(D.basis) % if all are deleted, create a new one Nb = 0; str = sprintf('basis %d',Nb+1); basislst{Nb+1} = str; set(S.basislist,'String',basislst); set(S.basislist,'Value',Nb+1); D.basis(Nb+1).name = []; % initiate defaults set(S.basistype,'Value',D.gui.ini.basistype.value); set(S.basisname,'String',sprintf('basis %d',id)); set(S.basisboundary,'String',D.gui.ini.basisboundary.value); set(S.basisrows,'String',D.gui.ini.basisrows.value); set(S.basiscols,'String',D.gui.ini.basiscols.value); set(S.basisorder,'String',D.gui.ini.basisorder.value); end basislst = get(S.basislist,'String'); Nb = length(basislst); % check if the current selection still makes sense tags{1,1} = 'prepAbasis'; tags{2,1} = 'prepBbasis'; tags{3,1} = 'prepCbasis'; tags{4,1} = 'finalbasis'; tags{5,1} = 'dicrelbasis'; for k = 1:5 % get the current string strs = get(S.(tags{k}),'String'); val = get(S.(tags{k}),'Value'); val = min([val length(strs)]); val = max([val 1]); str = strs{val}; % append to the current list if k == 5 basislst = [{'same as U'} ; basislst]; Nb = Nb + 1; end % find a matching basis id = find(strcmp(str,basislst),1); if isempty(id) val = min([val Nb]); val = max([val 1]); else val = id; end set(S.(tags{k}),'Value',val) set(S.(tags{k}),'String',basislst) end % update the application data guidata(H,D); basislist([],[],H); end % ================================================== function [] = basisduplicate(varargin) % Button Callback: Copy a basis set H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % get the selected basis basislst = get(S.basislist,'String'); id = get(S.basislist,'Value'); Nb = length(basislst); basislst = [basislst ; basislst(id)]; D.basis = [D.basis , D.basis(id)]; set(S.basislist,'String',basislst); set(S.basislist,'Value',Nb+1); % update the application data guidata(H,D); basislist([],[],H); end % ================================================== function [] = basistype(varargin) % Button Callback: Disable/Enable options upon type selection H = varargin{3}; S = guihandles(H); D = guidata(H); % get the basis type str = get(S.basistype,'String'); val = get(S.basistype,'Value'); type = str{val}; if strcmp(type,'Polynomial') set(S.basisboundary,'Enable','Off'); set(S.basisrows,'Enable','Off'); set(S.basiscols,'Enable','Off'); set(S.basisorder,'Enable','On'); elseif strcmp(type,'Harmonic') set(S.basisboundary,'Enable','Off'); set(S.basisrows,'Enable','Off'); set(S.basiscols,'Enable','Off'); set(S.basisorder,'Enable','On'); elseif strcmp(type,'Zernike') set(S.basisboundary,'Enable','Off'); set(S.basisrows,'Enable','Off'); set(S.basiscols,'Enable','Off'); set(S.basisorder,'Enable','On'); elseif strcmp(type,'B-Spline') set(S.basisboundary,'Enable','On'); set(S.basisrows,'Enable','On'); set(S.basiscols,'Enable','On'); set(S.basisorder,'Enable','On'); elseif strcmp(type,'FEM Triangle (a)') set(S.basisboundary,'Enable','On'); set(S.basisrows,'Enable','On'); set(S.basiscols,'Enable','On'); set(S.basisorder,'Enable','On'); elseif strcmp(type,'FEM Triangle (b)') set(S.basisboundary,'Enable','On'); set(S.basisrows,'Enable','On'); set(S.basiscols,'Enable','On'); set(S.basisorder,'Enable','On'); elseif strcmp(type,'FEM Quad') set(S.basisboundary,'Enable','On'); set(S.basisrows,'Enable','On'); set(S.basiscols,'Enable','On'); set(S.basisorder,'Enable','On'); end end % ================================================== function [] = basisbuild(varargin) % Button Callback: Generate the Mesh H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end n = D.files(1).size(1); m = D.files(1).size(2); x = 1:m; y = 1:n; % Region of interest if ~isfield(D,'roi') msgstr = {'This action requires a defined ROI,';'set the ROI in section 3'}; msgdlgjn(msgstr,dlgposition(H)); return; end roi = D.roi; % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the old basis if isfield(D,'basis') basis = D.basis; else basis(1).type = []; end % get the selected basis basislst = get(S.basislist,'String'); id = get(S.basislist,'Value'); % get the selected type typelist = get(S.basistype,'String'); typeval = get(S.basistype,'Value'); type = typelist{typeval}; basis(id).type = type; basis(id).typeval = typeval; % get the other options boundratio = eval(get(S.basisboundary,'String')); Nrows = round(eval(get(S.basisrows,'String'))); Ncols = round(eval(get(S.basiscols,'String'))); order = round(eval(get(S.basisorder,'String'))); % set minimum values boundratio = max([boundratio 0.1]); Nrows = max([Nrows 2]); Ncols = max([Ncols 2]); order = max([order 0]); set(S.basisboundary,'String',num2str(boundratio)); set(S.basisrows,'String',num2str(Nrows)); set(S.basiscols,'String',num2str(Ncols)); set(S.basisorder,'String',num2str(order)) % store to structure basis(id).boundratio = boundratio; basis(id).Nrows = Nrows; basis(id).Ncols = Ncols; basis(id).order = order; % Defining the mesh % ==================== if strcmp(type,'Polynomial') basis(id).type = 'polynomial'; basis(id).order = order; elseif strcmp(type,'Harmonic') basis(id).type = 'harmonic'; basis(id).order = order; elseif strcmp(type,'Zernike') basis(id).type = 'zernike'; basis(id).order = order; elseif strcmp(type,'B-Spline') basis(id).type = 'bspline'; basis(id).order = order; xknot = boundratiovec(roi(1),roi(2),Ncols,boundratio); yknot = boundratiovec(roi(3),roi(4),Nrows,boundratio); % store for plotting basis(id).xknot = xknot; basis(id).yknot = yknot; basis(id).Nrows = Nrows; basis(id).Ncols = Ncols; elseif strcmp(type,'FEM Triangle (a)') basis(id).type = 'FEM-T'; % limit polynomial order to 2 order = max([order 1]); order = min([order 2]); order = round(order); set(S.basisorder,'String',num2str(order)) basis(id).order = order; % generate the mesh [nodes,conn] = meshgen_T3a(Nrows,Ncols,boundratio,roi); if order == 2 [nodes,conn] = meshgen_T3toT6(nodes,conn,boundratio,roi); end % store the basis basis(id).coordinates = nodes; basis(id).connectivity = conn; basis(id).Nrows = Nrows; basis(id).Ncols = Ncols; elseif strcmp(type,'FEM Triangle (b)') basis(id).type = 'FEM-T'; % limit polynomial order to 2 order = max([order 1]); order = min([order 2]); order = round(order); set(S.basisorder,'String',num2str(order)) basis(id).order = order; % generate the mesh [nodes,conn] = meshgen_T3b(Nrows,Ncols,boundratio,roi); if order == 2 % convert T3 to T6 [nodes,conn] = meshgen_T3toT6(nodes,conn,boundratio,roi); end % store the basis basis(id).coordinates = nodes; basis(id).connectivity = conn; basis(id).Nrows = Nrows; basis(id).Ncols = Ncols; elseif strcmp(type,'FEM Quad') basis(id).type = 'FEM-Q'; % limit polynomial order to 2 order = max([order 1]); order = min([order 2]); order = round(order); set(S.basisorder,'String',num2str(order)) basis(id).order = order; % generate the mesh if order == 1 [nodes,conn] = meshgen_Q4(Nrows,Ncols,boundratio,roi); elseif order == 2 [nodes,conn] = meshgen_Q8(Nrows,Ncols,boundratio,roi); end % store the basis basis(id).coordinates = nodes; basis(id).connectivity = conn; basis(id).Nrows = Nrows; basis(id).Ncols = Ncols; end % delete old basis functions if isfield(basis(id),'plotphi') basis(id).plotphi = []; end % number of pixels (in x-dir) to use to generate plot versions of the basis Nplot = D.gui.ini.basisplotcol.value; basis(id).plotx = linspace(min(x),max(x),Nplot); basis(id).ploty = linspace(min(y),max(y),round(n*Nplot/m)); % computing the plot shapes basis(id).plotphi = phibuild(basis(id).plotx,basis(id).ploty,roi,basis(id),H,'single'); basis(id).Nphi = size(basis(id).plotphi,2); % add the number of dof to the name basisname = get(S.basisname,'String'); basislst{id} = sprintf('%s (%d)',basisname,basis(id).Nphi); % update the name to the list set(S.basislist,'String',basislst); basis(id).name = basisname; % also update the basis names of section 6 tags{1,1} = 'prepAbasis'; tags{2,1} = 'prepBbasis'; tags{3,1} = 'prepCbasis'; tags{4,1} = 'finalbasis'; tags{5,1} = 'dicrelbasis'; for k = 1:5 if k == 5 basislst = [{'same as U'} ; basislst]; end set(S.(tags{k}),'String',basislst) end % update sliders Nphi = size(basis(id).plotphi,2); Nphi = max([Nphi 2]); set(S.phislider,'Value',1) set(S.phiid,'String','1') set(S.phislider,'Max',max([Nphi 2])) set(S.phislider,'Sliderstep',[1/Nphi 10/Nphi]) % make the indicator green set(S.secind5,'BackgroundColor',D.gui.color.on) % update info info(1).str = sprintf('basis %d name',id); info(1).val = basis(id).name; info(2).str = sprintf('basis %d type',id); info(2).val = basis(id).type; info(3).str = sprintf('basis %d Nphi',id); info(3).val = basis(id).Nphi; D.gui.info = appendinfo(D.gui.info,info); % update status stat = sprintf('[5] Basis %d generated',id); D.gui.stat = appendstatus(D.gui.stat,stat); % update the application data D.basis = basis; set(D.gui.waithandles,'Enable','on');drawnow guidata(H,D); plotbasis([],[],H); end % ========================================================================= % Section 6: DIC options % ========================================================================= % ================================================== function [] = diclagrangeslider(varargin) % Button Callback: handle Lagrange/Updated Slider changes H = varargin{3}; S = guihandles(H); val = get(S.diclagrangeslider,'Value'); val = round(val*100)/100; str = num2str(val); set(S.diclagrangeslider,'Value',val); set(S.diclagrange,'String',str) end % ================================================== function [] = dicdimensions(varargin) % Button Callback: If 3D disable relaxation, if 2D enable H = varargin{3}; S = guihandles(H); if get(S.dicdimensions,'Value') == 1 %2D set(S.dicrelaxation,'Enable','on') if get(S.dicrelaxation,'Value') == 1 %none set(S.dicrelbasis,'Enable','off') else % brightness or brightness+contrast set(S.dicrelbasis,'Enable','on') end elseif get(S.dicdimensions,'Value') == 2 %3D set(S.dicrelaxation,'Enable','off') set(S.dicrelbasis,'Enable','off') set(S.resstraindef,'Value',5) end end % ================================================== function [] = dicrelaxation(varargin) % Button Callback: no relaxation disable basis H = varargin{3}; S = guihandles(H); if get(S.dicrelaxation,'Value') == 1 %none set(S.dicrelbasis,'Enable','off') else % brightness or brightness+contrast set(S.dicrelbasis,'Enable','on') end end % ================================================== function [] = cgon(varargin) % Button Callback: Switch CG step on H = varargin{3}; D = guidata(H); S = guihandles(H); id = varargin{4}; cgstr{1,1} = 'prepA'; cgstr{2,1} = 'prepB'; cgstr{3,1} = 'prepC'; cgstr{4,1} = 'final'; if id <= 3 set(S.([cgstr{id} 'on']),'BackgroundColor',D.gui.color.hl); set(S.([cgstr{id} 'off']),'BackgroundColor',D.gui.color.bg); set(S.([cgstr{id} 'on']),'Value',1); set(S.([cgstr{id} 'off']),'Value',0); end enable = 'on'; set(S.([cgstr{id} 'blur']),'Enable',enable); set(S.([cgstr{id} 'level']),'Enable',enable); set(S.([cgstr{id} 'improcess']),'Enable',enable); set(S.([cgstr{id} 'basis']),'Enable',enable); set(S.([cgstr{id} 'convcrit']),'Enable',enable); set(S.([cgstr{id} 'maxit']),'Enable',enable); set(S.([cgstr{id} 'gradient']),'Enable',enable); set(S.([cgstr{id} 'tikhpar1']),'Enable',enable); set(S.([cgstr{id} 'tikhpar2']),'Enable',enable); set(S.([cgstr{id} 'tikhsteps']),'Enable',enable); end % ================================================== function [] = cgoff(varargin) % Button Callback: Switch CG step off H = varargin{3}; D = guidata(H); S = guihandles(H); id = varargin{4}; cgstr{1,1} = 'prepA'; cgstr{2,1} = 'prepB'; cgstr{3,1} = 'prepC'; cgstr{4,1} = 'final'; if id <= 3 set(S.([cgstr{id} 'off']),'BackgroundColor',D.gui.color.hl); set(S.([cgstr{id} 'on']),'BackgroundColor',D.gui.color.bg); set(S.([cgstr{id} 'off']),'Value',1); set(S.([cgstr{id} 'on']),'Value',0); end enable = 'off'; set(S.([cgstr{id} 'blur']),'Enable',enable); set(S.([cgstr{id} 'level']),'Enable',enable); set(S.([cgstr{id} 'improcess']),'Enable',enable); set(S.([cgstr{id} 'basis']),'Enable',enable); set(S.([cgstr{id} 'convcrit']),'Enable',enable); set(S.([cgstr{id} 'maxit']),'Enable',enable); set(S.([cgstr{id} 'gradient']),'Enable',enable); set(S.([cgstr{id} 'tikhpar1']),'Enable',enable); set(S.([cgstr{id} 'tikhpar2']),'Enable',enable); set(S.([cgstr{id} 'tikhsteps']),'Enable',enable); end % ================================================== function [] = dicsave(varargin) % Button Callback: save the dic options % this function is also called at the start of correlation see % the corgo function below H = varargin{3}; S = guihandles(H); D = guidata(H); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % user fileselect [filename, pathname] = uiputfile(fullfile(basedir,'dicoptions.ini'), 'save the dic options'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end % store the basename D.gui.ini.basedir.value = pathname; % gather settings ini = iniget(H); % save to file iniwrite(fullfile(pathname,filename),ini); set(D.gui.waithandles,'Enable','on');drawnow % update the status D.gui.stat = appendstatus(D.gui.stat,'[6] DIC options saved to file'); % update the application data guidata(H,D); end % ================================================== function [] = dicload(varargin) % Button Callback: load dic options H = varargin{3}; S = guihandles(H); D = guidata(H); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % user fileselect [filename, pathname] = uigetfile(fullfile(basedir,'dicoptions.ini'), 'load the dic options'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end % store the basename D.gui.ini.basedir.value = pathname; % set section indicator on set(S.secind6,'BackgroundColor',D.gui.color.on) % update status D.gui.stat = appendstatus(D.gui.stat,'[6] DIC options saved to file'); % update the application data guidata(H,D);drawnow; iniset(H); set(D.gui.waithandles,'Enable','on');drawnow end % ========================================================================= % Section 7: Correlate % ========================================================================= % ================================================== function [] = corgo(varargin) % Button Callback: Start the corrlation H = varargin{3}; D = guidata(H); S = guihandles(H); % remove any old results if isfield(D,'res') D = rmfield(D,'res'); end set(S.corgo,'BackgroundColor',D.gui.color.hl); set(S.corstop,'BackgroundColor',D.gui.color.bg); set(S.corgo,'Value',1); set(S.corstop,'Value',0); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % enable stop button set(S.corstop,'Enable','on');drawnow % enable continue button set(S.corcontinue,'Enable','on');drawnow % set indicator color set(S.secind7,'BackgroundColor',D.gui.color.off) % set continue button set(S.corcontinue,'Value',0) % update the application data D.gui.ini = iniget(H); guidata(H,D); drawnow; corsequence(H); drawnow; set(D.gui.waithandles,'Enable','on');drawnow set(S.secind7,'BackgroundColor',D.gui.color.on) corstop([],[],H) end % ================================================== function [] = corstop(varargin) % Button Callback: Stop the correlation (ASAP) H = varargin{3}; D = guidata(H); S = guihandles(H); set(S.corgo,'BackgroundColor',D.gui.color.bg); set(S.corstop,'BackgroundColor',D.gui.color.hl); set(S.corgo,'Value',0); set(S.corstop,'Value',1); end % ================================================== function [] = corclear(varargin) % Button Callback: Clear the correlation data for all increments H = varargin{3}; S = guihandles(H); D = guidata(H); if isfield(D,'cor') Ninc = length(D.cor); for inc = 1:Ninc D.cor(inc).done = 0; D.cor(inc).U1 = []; D.cor(inc).U2 = []; D.cor(inc).U3 = []; D.cor(inc).U4 = []; D.cor(inc).U5 = []; D.cor(inc).U6 = []; end end delete(findobj(H,'Tag','cor_quiver')); % update status set(S.corstatus,'String',{''});drawnow % update status D.gui.stat = appendstatus(D.gui.stat,'[7] Correlation results cleared for all increments'); % remove any old results if isfield(D,'res') D = rmfield(D,'res'); end % update the application data guidata(H,D); plotcor(H); end % ================================================== function [] = corclearinc(varargin) % Button Callback: Clear the correlation data for one increment % Actually, nothing is deleted, only the done parameter is set to 0 H = varargin{3}; S = guihandles(H); D = guidata(H); % get the updated id inc = str2double(get(S.corid,'String')); % don't reset the zero increment if inc == 0 return end if isfield(D,'cor') D.cor(inc).done = 0; D.cor(inc).U1 = []; D.cor(inc).U2 = []; D.cor(inc).U3 = []; D.cor(inc).U4 = []; D.cor(inc).U5 = []; D.cor(inc).U6 = []; end stat = get(S.corstatus,'String'); stat = [sprintf('increment (%d) cleared',inc) ; stat]; set(S.corstatus,'String',stat);drawnow % update status stat = sprintf('[7] Correlation results cleared for increment %d',inc); D.gui.stat = appendstatus(D.gui.stat,stat); % remove any old results if isfield(D,'res') D = rmfield(D,'res'); end % update the application data guidata(H,D); plotcor(H); end % ================================================== function [] = correstart(varargin) % Button Callback: Clear the correlation data for all increments H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'cor') return end Ninc = length(D.cor); for inc = 1:Ninc D.cor(inc).done = 0; end % update status set(S.corstatus,'String',{'(Init. option changed to reuse)';'restarting all'});drawnow % set the Init. options to reuse set(S.dicinciguess,'Value',5);drawnow % update status D.gui.stat = appendstatus(D.gui.stat,'[7] Restart set for all increments'); % remove any old results if isfield(D,'res') D = rmfield(D,'res'); end % update the application data guidata(H,D); plotcor(H); end % ================================================== function [] = correstartinc(varargin) % Button Callback: Clear the correlation data for one increment % Actually, nothing is deleted, only the done parameter is set to 0 H = varargin{3}; S = guihandles(H); D = guidata(H); % get the updated id inc = str2double(get(S.corid,'String')); % don't reset the zero increment if inc == 0 return end if isfield(D,'cor') D.cor(inc).done = 0; end stat = get(S.corstatus,'String'); stat = [sprintf('restarting increment (%d)',inc) ; stat]; stat = ['(Init. option changed to reuse)' ; stat]; set(S.corstatus,'String',stat);drawnow % update status stat = sprintf('[7] Restart set for increment %d',inc); D.gui.stat = appendstatus(D.gui.stat,stat); % remove any old results if isfield(D,'res') D = rmfield(D,'res'); end % update the application data guidata(H,D); plotcor(H); end % ================================================== function [] = corid(varargin) % Callback for the edit box below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = str2double(get(S.corid,'String')); % rounding and limits id = round(id); id = max([id 0]); id = min([id Nim-1]); % update the gui set(S.corslider,'Value',id); plotcor(H) end % ================================================== function [] = corslider(varargin) % Callback for the slider below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = get(S.corslider,'Value'); % rounding and limits id = round(id); id = max([id 0]); id = min([id Nim-1]); % update the gui set(S.corid,'String',num2str(id)); plotcor(H) end % ================================================== function [] = cor2iguess(varargin) % Button Callback: Convert the correlation to initial guess points H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end if ~isfield(D,'cor') msgstr = {'This action requires a succesfull correlation,';'perform a correlation in section 7'}; msgdlgjn(msgstr,dlgposition(H)); return; end % ask for grid size prompt = {'number of points in x direction:','number of points in y direction:'}; dlg_title = 'Select initial guess grid size'; num_lines = 1; def = {D.gui.ini.cor2iguesscols.value,D.gui.ini.cor2iguessrows.value}; answer = inputdlgjn(prompt,dlg_title,num_lines,def,dlgposition(H)); if isempty(answer) return end % get previous guesses if isfield(D,'iguess') iguess = D.iguess; Niguess = length(iguess.x); else iguess.x = []; iguess.y = []; iguess.ux = []; iguess.uy = []; Niguess = 0; end Nx = round(str2double(answer{1})); Ny = round(str2double(answer{2})); Nx = max([1 Nx]); Ny = max([1 Ny]); N = Nx * Ny; % locations of the iguess points x = linspace(D.cor(1).xroi(3),D.cor(1).xroi(end-2),Nx); y = linspace(D.cor(1).yroi(3),D.cor(1).yroi(end-2),Ny); [X, Y] = meshgrid(x,y); % initiate masked iguess counter masked = zeros(N,1); % get maskimage [n, m] = size(D.cor(1).U1); maskimg = double(maskimage(D.cor(1).Imask,n,m)); Ncg = 4; Ninc = length(D.cor); for inc = 0:Ninc inc1 = 1; if inc == 0 || isempty(D.cor(inc).done) || (D.cor(inc).done ~= Ncg); % zero increment iguess.x(Niguess+1:Niguess+N,1) = X(:); iguess.y(Niguess+1:Niguess+N,1) = Y(:); iguess.ux(Niguess+1:Niguess+N,inc+1) = zeros(N,1); iguess.uy(Niguess+1:Niguess+N,inc+1) = zeros(N,1); else % other increments ux = interp2(D.cor(inc1).xroi,D.cor(inc1).yroi',D.cor(inc).U1,X,Y,'linear',0); uy = interp2(D.cor(inc1).xroi,D.cor(inc1).yroi',D.cor(inc).U2,X,Y,'linear',0); iguess.ux(Niguess+1:Niguess+N,inc+1) = gather(ux(:)); iguess.uy(Niguess+1:Niguess+N,inc+1) = gather(uy(:)); % interpolate maskimage on iguess locations msk = interp2(D.cor(inc1).xroi,D.cor(inc1).yroi',maskimg,X,Y,'linear',1); % store mask value for each inc masked = masked + msk(:); end bcwaitbar(H,inc/Ninc,sprintf('initial guess increment (%d/%d)',inc,Ninc)); end % remove initial guesses which are in the masked area I = find(masked ~= 0); iguess.x(Niguess+I,:) = []; iguess.y(Niguess+I,:) = []; iguess.ux(Niguess+I,:) = []; iguess.uy(Niguess+I,:) = []; % store results D.iguess = iguess; % update info info(1).str = 'Niguess'; info(1).val = length(D.iguess.x); D.gui.info = appendinfo(D.gui.info,info); % update status D.gui.stat = appendstatus(D.gui.stat,'[7] Correlation results copied to initial guess'); bcwaitbar(H); % update the application data guidata(H,D); plotiguess(H); end % ========================================================================= % Section 8: Results % ========================================================================= % ================================================== function [] = resid(varargin) % Callback for the edit box below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = str2double(get(S.resid,'String')); % rounding and limits id = round(id); id = max([id 0]); id = min([id Nim-1]); % update the gui set(S.resslider,'Value',id); plotres([],[],H) end % ================================================== function [] = resslider(varargin) % Callback for the slider below the figures (in figpanel1) H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') return; end Nim = length(D.files); % get the updated id id = get(S.resslider,'Value'); % rounding and limits id = round(id); id = max([id 0]); id = min([id Nim-1]); % update the gui set(S.resid,'String',num2str(id)); plotres([],[],H) end % ================================================== function resrenderer(varargin) % Button Callback: switch renderer H = varargin{3}; S = guihandles(H); renderer = get(S.resrenderer,'String'); set(H,'Renderer',renderer{get(S.resrenderer,'Value')}); end % ================================================== function [] = ressave(varargin) % Button Callback: save the result figure H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % user fileselect [filename, pathname] = uiputfile(fullfile(basedir,'basicgdic_result.png'), 'Save current result figure as'); if isequal(filename,0) || isequal(pathname,0) % if cancel set(D.gui.waithandles,'Enable','on');drawnow return end % store the basename D.gui.ini.basedir.value = pathname; Hpan = S.figpan8; Hch = findobj(Hpan,'Type','axes'); set(Hpan,'units','pixels'); set(Hpan,'units','normalized'); % Create the figure % ===================== pos = [50, 50, D.gui.pos.w, D.gui.pos.h]; Hfig = figure('units','pixels',... 'position',pos,... 'name','basic gdic figure'); % copy the object to the new figure window Hch = copyobj(Hch,Hfig); colormap(D.gui.color.cmapoverlay); % fix the colorbar width Ha = findobj(Hch,'Tag','axes8'); Hc = findobj(Hch,'Tag','Colorbar'); set([Ha Hc],'units','pixels'); hapos = get(Ha,'Position'); pos(1) = hapos(1)+hapos(3)+2; pos(2) = hapos(2); pos(3) = 20; pos(4) = hapos(4); set(Hc,'Position',pos); set([Ha Hc],'units','normalized'); % set the Render mode renderer = get(S.resrenderer,'String'); renderer = renderer{get(S.resrenderer,'Value')}; set(Hfig,'Renderer',renderer) % fix the extention filename = [regexprep(filename,'.png$','','ignorecase') '.png']; savepos = get(Hfig,'Position'); % set the paper position to 1 inch per 100 pixels set(Hfig,'PaperUnits','inches','PaperPosition',savepos.*[0 0 1e-2 1e-2]); set(Hfig,'PaperSize',savepos(3:4).*[1e-2 1e-2]); % save png if strcmpi(renderer,'OpenGL') print(Hfig,fullfile(pathname,filename),'-dpng','-r200','-opengl'); else print(Hfig,fullfile(pathname,filename),'-dpng','-r200'); end set(D.gui.waithandles,'Enable','on');drawnow % update status stat = sprintf('[8] Results figure saved (%s)',filename); D.gui.stat = appendstatus(D.gui.stat,stat); % update the application data guidata(H,D); end % ================================================== function [] = rescrosssection(varargin) % Button Callback: open the cross-section sub-gui H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end end % ========================================================================= % Section 9: Info % ========================================================================= % ================================================== function [] = inforeset(varargin) % Button Callback: Reset the entire GUI H = varargin{3}; S = guihandles(H); D = guidata(H); if isfield(D,'files') D = rmfield(D,'files'); end if isfield(D,'roi') D = rmfield(D,'roi'); end if isfield(D,'iguess') D = rmfield(D,'iguess'); end if isfield(D,'basis') D = rmfield(D,'basis'); end if isfield(D,'cor') D = rmfield(D,'cor'); end if isfield(D,'res') D = rmfield(D,'res'); end % initialize status str = ['Basic gdic tool started: ' datestr(now,'yyyy-mm-dd')]; D.gui.stat = appendstatus({''},str); D.gui.stat = appendstatus(D.gui.stat,'rule'); % initialize info D.gui.info = []; D.gui.info(1).str = 'date'; D.gui.info(1).val = datestr(now,'yyyy-mm-dd'); D.gui.info(2).str = 'time'; D.gui.info(2).val = datestr(now,'HH:MM:SS'); % Load the stored defaults from file D.gui.ini = iniread; % update the gui guidata(H,D);drawnow iniset(H); updateinfo(H) cla(S.axes1) cla(S.axes2) cla(S.axes2hist) cla(S.axes3) cla(S.axes4) cla(S.axes41) cla(S.axes42) cla(S.axes43) cla(S.axes44) cla(S.axes7) cla(S.axes8) end % ================================================== function [] = infoguidataput(varargin) % Button Callback: Put the guidata in the workspace (D) H = varargin{3}; S = guihandles(H); D = guidata(H); % update the gui state D.gui.ini = iniget(H); % delete the waithandles since they produce large files in matlab 2014b+ if isfield(D.gui,'waithandles') D.gui = rmfield(D.gui,'waithandles'); end assignin('base','D',D); evalin('base','D'); % update the waithandles D.gui.waithandles = waithandlesfun(S); % update status D.gui.stat = appendstatus(D.gui.stat,'[9] guidata stored to D'); guidata(H,D);drawnow updateinfo(H) end % ================================================== function [] = infoguidataget(varargin) % Button Callback: Get the guidata from the workspace (D) H = varargin{3}; S = guihandles(H); if verLessThan('matlab','8.4') evalin('base',['guidata(' num2str(H) ',D)']); else evalin('base',['guidata(' num2str(H.Number) ',D)']); end % update status D = guidata(H); % set the gui elements if isfield(D,'files') set(S.secind1,'BackgroundColor',D.gui.color.on) Nfiles = length(D.files); filelist = {D.files(:).name}'; set(S.filelist,'String',filelist); set(S.filelist,'Max',Nfiles); else set(S.secind1,'BackgroundColor',D.gui.color.init) Nfiles = 2; end % update info info(1).str = 'Nfiles'; info(1).val = Nfiles; D.gui.info = appendinfo(D.gui.info,info); % load the gui state if ~isfield(D.gui,'ini') D.gui.ini = iniread; end % set all the uicontrols iniset(H); % update the waithandles D.gui.waithandles = waithandlesfun(S); D.gui.stat = appendstatus(D.gui.stat,'[9] D loaded to guidata'); guidata(H,D);drawnow updateinfo(H) end % ================================================== function [] = infosave(varargin) % Button Callback: save the entire gui (this file can be used as an % inputfile) H = varargin{3}; S = guihandles(H); D = guidata(H); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; if length(varargin) > 3 filename = varargin{4}; if strcmp(filename(1),'/') || strcmp(filename(2),':') pathname = ''; else pathname = basedir; end else [filename, pathname] = uiputfile(fullfile(basedir,'basicgdic.mat'), 'save the GUI state'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end end % store the basename D.gui.ini.basedir.value = pathname; % get the gui state D.gui.ini = iniget(H); % update status D.gui.stat = appendstatus(D.gui.stat,sprintf('[9] basicgdic data saved to %s',fullfile(pathname,filename))); if length(varargin) == 3 bcwaitbar(H,0.5,'saving basicgdic data'); end % save to file bgdic = D; bgdic.savetype = 'info'; % delete any results (because they are big and can be regenerated from % cor) if isfield(bgdic,'res') bgdic = rmfield(bgdic,'res'); end % delete the waithandles since they produce large files in matlab 2014b+ if isfield(bgdic.gui,'waithandles') bgdic.gui = rmfield(bgdic.gui,'waithandles'); end save('-v7.3',fullfile(pathname,filename),'bgdic') if length(varargin) == 3 bcwaitbar(H); end set(D.gui.waithandles,'Enable','on');drawnow guidata(H,D);drawnow end % ================================================== function [] = infoload(varargin) % Button Callback: Load the an inputfile (initialize the entire GUI) H = varargin{3}; S = guihandles(H); D = guidata(H); % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % get the previous basedir basedir = D.gui.ini.basedir.value; % load defaults if length(varargin) > 3 % use the argument filename = varargin{4}; if strcmp(filename(1),'/') || strcmp(filename(2),':') % absolute path pathname = ''; else % relative path pathname = basedir; end else % ask for a filename [filename, pathname] = uigetfile(fullfile(basedir,'basicgdic.mat'), 'load GUI state'); if isequal(filename,0) || isequal(pathname,0) set(D.gui.waithandles,'Enable','on');drawnow return end end % test if the file exists if ~exist(fullfile(pathname,filename),'file') msgstr = 'save file not found'; msgdlgjn(msgstr,dlgposition(H)); set(D.gui.waithandles,'Enable','on');drawnow return end if length(varargin) == 3 bcwaitbar(H,0.5,'loading basicgdic data'); end % load from file if isempty(whos('-file',fullfile(pathname,filename),'bgdic')) % if autosave, the fields are directly in the file bgdic = load(fullfile(pathname,filename)); else % normal infosave file load(fullfile(pathname,filename),'bgdic') end if ~isfield(bgdic,'savetype') msgstr = 'incompatible save file'; msgdlgjn(msgstr,dlgposition(H)); set(D.gui.waithandles,'Enable','on');drawnow return end if ~any(strcmp(bgdic.savetype,{'info','autosave'})) msgstr = sprintf('incorrect save type (%s), try loading it in another section',bgdic.savetype); msgdlgjn(msgstr,dlgposition(H)); set(D.gui.waithandles,'Enable','on');drawnow return end D = bgdic; % store the basename D.gui.ini.basedir.value = pathname; if isfield(D,'savetype') D = rmfield(D,'savetype'); end % update the waithandles D.gui.waithandles = waithandlesfun(S); % load the gui state if ~isfield(D.gui,'ini') D.gui.ini = iniread; end D.gui.stat = appendstatus(D.gui.stat,sprintf('[9] basicgdic data loaded from %s',fullfile(pathname,filename))); guidata(H,D); % set all the uicontrols iniset(H); if length(varargin) == 3 bcwaitbar(H); end set(D.gui.waithandles,'Enable','on');drawnow end % ================================================== function [] = updateinfo(H) % collect information for the infopanel S = guihandles(H); D = guidata(H); % update info info(1).str = 'date'; info(1).val = datestr(now,'yyyy-mm-dd'); info(2).str = 'time'; info(2).val = datestr(now,'HH:MM:SS'); % Info panel 1: General Info info = appendinfo(D.gui.info,info); N = length(info); for k = 1:N rnam{k,1} = info(k).str; data{k,1} = info(k).val; end cnam = []; set(S.infogeneral,'Data',data,... 'RowName',rnam,... 'ColumnName',cnam); % update the application data D.gui.info = info; guidata(H,D); % Info panel 2: Correlation Info if isfield(D,'cor') % colnames cnam{ 1,1} = 'inc'; cnam{ 2,1} = 'cg'; cnam{ 3,1} = 'it'; cnam{ 4,1} = 'Nphi'; cnam{ 5,1} = 'Npx'; cnam{ 6,1} = 'r [%]'; cnam{ 7,1} = 'du [px]'; cnam{ 8,1} = 'b'; cnam{ 9,1} = 'dp'; cnam{10,1} = 'dr [%]'; cnam{11,1} = 'tikh'; cnam{12,1} = 'div'; cnam{13,1} = 'state'; itable = []; Ninc = length(D.cor); for inc = 1:Ninc; if isfield(D.cor(inc),'cg') Ncg = length(D.cor(inc).cg); for icg = 1:Ncg if isfield(D.cor(inc).cg,'itable') itable = [itable ; D.cor(inc).cg(icg).itable ; zeros(1,13)]; end end end end rnam = 'numbered'; cwidth = {40,40,40,40,50,50,60,60,60,60,60,40,40}; cformat{1,1} = 'short'; cformat{1,2} = 'short'; cformat{1,3} = 'short'; cformat{1,4} = 'short'; cformat{1,5} = 'short'; cformat{1,6} = 'short'; cformat{1,7} = 'short'; cformat{1,8} = 'short'; cformat{1,9} = 'short'; cformat{1,10} = 'short'; cformat{1,11} = 'short'; cformat{1,12} = 'short'; cformat{1,13} = 'short'; set(S.infocorrelation,'Data',itable,... 'RowName',rnam,... 'ColumnName',cnam,... 'ColumnWidth',cwidth,... 'ColumnFormat',cformat); end % Info panel 2: Status set(S.status,'String',D.gui.stat); end % ============================== function waithandles = waithandlesfun(S) % A list of handles fo all controls (buttons etc) which will be temporarily % disabled during computations. This is important since most computations % depend on the state of the controls, and thus changing them during the % computations may lead to strange results. % Comment those lines of the controls you want to remain always active waithandles = []; % waithandles = [waithandles, S.secbut9]; waithandles = [waithandles, S.secbut8]; % waithandles = [waithandles, S.secbut7]; % waithandles = [waithandles, S.secbut6]; % waithandles = [waithandles, S.secbut5]; % waithandles = [waithandles, S.secbut4]; % waithandles = [waithandles, S.secbut3]; % waithandles = [waithandles, S.secbut2]; % waithandles = [waithandles, S.secbut1]; waithandles = [waithandles, S.resslider]; waithandles = [waithandles, S.resid]; waithandles = [waithandles, S.resclim2]; waithandles = [waithandles, S.resclim1]; waithandles = [waithandles, S.corslider]; waithandles = [waithandles, S.corid]; waithandles = [waithandles, S.phislider]; waithandles = [waithandles, S.phiid]; waithandles = [waithandles, S.iguessslider]; waithandles = [waithandles, S.iguessid]; waithandles = [waithandles, S.roislider]; waithandles = [waithandles, S.roiid]; waithandles = [waithandles, S.patslider]; waithandles = [waithandles, S.patid]; waithandles = [waithandles, S.imageslider]; waithandles = [waithandles, S.imageid]; waithandles = [waithandles, S.infoload]; waithandles = [waithandles, S.infosave]; waithandles = [waithandles, S.inforeset]; % waithandles = [waithandles, S.infobut3]; % waithandles = [waithandles, S.infobut2]; % waithandles = [waithandles, S.infobut1]; waithandles = [waithandles, S.rescrosssection]; waithandles = [waithandles, S.ressave]; waithandles = [waithandles, S.resstraindef]; waithandles = [waithandles, S.resunit]; waithandles = [waithandles, S.respixelsize]; waithandles = [waithandles, S.resarrowscaleslider]; waithandles = [waithandles, S.resarrowscale]; waithandles = [waithandles, S.resarrows]; waithandles = [waithandles, S.resalphaslider]; waithandles = [waithandles, S.resalpha]; waithandles = [waithandles, S.resoverlay]; waithandles = [waithandles, S.ressofteningslider]; waithandles = [waithandles, S.ressoftening]; waithandles = [waithandles, S.resunderlay]; % waithandles = [waithandles, S.corstatus]; waithandles = [waithandles, S.corliveview]; waithandles = [waithandles, S.cor2iguess]; waithandles = [waithandles, S.corclear]; waithandles = [waithandles, S.corclearinc]; waithandles = [waithandles, S.correstart]; waithandles = [waithandles, S.correstartinc]; % waithandles = [waithandles, S.corstop]; % waithandles = [waithandles, S.corcontinue]; % waithandles = [waithandles, S.corgo]; waithandles = [waithandles, S.dicload]; waithandles = [waithandles, S.dicsave]; waithandles = [waithandles, S.dicusegpu]; waithandles = [waithandles, S.dicprecision]; waithandles = [waithandles, S.dicmemsave]; waithandles = [waithandles, S.dicautosave]; waithandles = [waithandles, S.diclagrangeslider]; waithandles = [waithandles, S.diclagrange]; waithandles = [waithandles, S.dicinciguess]; waithandles = [waithandles, S.dicmaxdiv]; waithandles = [waithandles, S.dicbestit]; waithandles = [waithandles, S.dicconvparam]; waithandles = [waithandles, S.dicrelbasis]; waithandles = [waithandles, S.dicrelaxation]; waithandles = [waithandles, S.dicdimensions]; waithandles = [waithandles, S.basisload]; waithandles = [waithandles, S.basissave]; waithandles = [waithandles, S.basisalphaslider]; waithandles = [waithandles, S.basisalpha]; waithandles = [waithandles, S.basissoftenslider]; waithandles = [waithandles, S.basissoften]; waithandles = [waithandles, S.basisorder]; waithandles = [waithandles, S.basiscols]; waithandles = [waithandles, S.basisrows]; waithandles = [waithandles, S.basisboundary]; waithandles = [waithandles, S.basisname]; waithandles = [waithandles, S.basistype]; waithandles = [waithandles, S.basisduplicate]; waithandles = [waithandles, S.basisdel]; waithandles = [waithandles, S.basisnew]; waithandles = [waithandles, S.basislist]; waithandles = [waithandles, S.basisdefine]; waithandles = [waithandles, S.iguessload]; waithandles = [waithandles, S.iguesssave]; waithandles = [waithandles, S.iguessdelall]; waithandles = [waithandles, S.iguessdelbox]; waithandles = [waithandles, S.iguessdelone]; waithandles = [waithandles, S.iguesszoomsize]; waithandles = [waithandles, S.iguesszoomselect]; waithandles = [waithandles, S.iguessaddmanual]; waithandles = [waithandles, S.iguessaddauto]; waithandles = [waithandles, S.iguessimprocesstype]; waithandles = [waithandles, S.iguessblur]; waithandles = [waithandles, S.iguessimprocess]; waithandles = [waithandles, S.maskload]; waithandles = [waithandles, S.masksave]; waithandles = [waithandles, S.maskclear]; waithandles = [waithandles, S.maskinvert]; waithandles = [waithandles, S.maskintersect]; waithandles = [waithandles, S.maskdel]; waithandles = [waithandles, S.maskadd]; waithandles = [waithandles, S.masktool]; waithandles = [waithandles, S.roiset]; waithandles = [waithandles, S.patshowACF]; waithandles = [waithandles, S.patshowpat]; waithandles = [waithandles, S.patarea]; waithandles = [waithandles, S.filelist]; waithandles = [waithandles, S.filedown]; waithandles = [waithandles, S.fileup]; waithandles = [waithandles, S.filedel]; waithandles = [waithandles, S.fileadd]; waithandles = [waithandles, S.finaltikhsteps]; waithandles = [waithandles, S.finaltikhpar2]; waithandles = [waithandles, S.finaltikhpar1]; waithandles = [waithandles, S.finalgradient]; waithandles = [waithandles, S.finalmaxit]; waithandles = [waithandles, S.finalconvcrit]; waithandles = [waithandles, S.finalbasis]; waithandles = [waithandles, S.finalimprocess]; waithandles = [waithandles, S.finallevel]; waithandles = [waithandles, S.finalblur]; waithandles = [waithandles, S.prepAtikhsteps]; waithandles = [waithandles, S.prepAtikhpar2]; waithandles = [waithandles, S.prepAtikhpar1]; waithandles = [waithandles, S.prepAgradient]; waithandles = [waithandles, S.prepAmaxit]; waithandles = [waithandles, S.prepAconvcrit]; waithandles = [waithandles, S.prepAbasis]; waithandles = [waithandles, S.prepAimprocess]; waithandles = [waithandles, S.prepAlevel]; waithandles = [waithandles, S.prepAblur]; waithandles = [waithandles, S.prepBtikhsteps]; waithandles = [waithandles, S.prepBtikhpar2]; waithandles = [waithandles, S.prepBtikhpar1]; waithandles = [waithandles, S.prepBgradient]; waithandles = [waithandles, S.prepBmaxit]; waithandles = [waithandles, S.prepBconvcrit]; waithandles = [waithandles, S.prepBbasis]; waithandles = [waithandles, S.prepBimprocess]; waithandles = [waithandles, S.prepBlevel]; waithandles = [waithandles, S.prepBblur]; waithandles = [waithandles, S.prepCtikhsteps]; waithandles = [waithandles, S.prepCtikhpar2]; waithandles = [waithandles, S.prepCtikhpar1]; waithandles = [waithandles, S.prepCgradient]; waithandles = [waithandles, S.prepCmaxit]; waithandles = [waithandles, S.prepCconvcrit]; waithandles = [waithandles, S.prepCbasis]; waithandles = [waithandles, S.prepCimprocess]; waithandles = [waithandles, S.prepClevel]; waithandles = [waithandles, S.prepCblur]; end function basicgdic_defaults filename = 'basicgdic_defaults.ini'; if exist(filename,'file') return end str = {... '% These are all the GUI settings for the basicgdic tool.'... ''... '% This file will be automatically generated if it does not exist, i.e. delete it to reset the settings.'... ''... '% The settings consist of three parts: TAG:FIELD = VALUE, which correspond to the VALUE of the matlab uicontrol FIELD of the object with handle TAG. Lines starting with a "%", or a "[" are ignored and everything beyond a % or [ is ignored as well. The TAG and FIELD parts are case-insensitive, the VALUE part is usually case-sensitive. The order in which settings appear is not important.'... ''... '[Directories]'... '% the basedir option allows the specification of a directory where all save and load '... '% actions originate. This directory can be relative to the current matlab path, or '... '% absolute. Loading or saving something from a different path will change the basedir '... '% to the new path. The other paths (inputfile and autosavefile) can be specified '... '% relatively from the basedir or absolute. Leave these options empty to specify nothing.'... 'basedir:string = '... 'inputfile:string = '... 'autosavefile:string = '... ''... '[Init. Guess]'... 'iguessblur:string = 3'... 'iguessimprocesstype:value = 5 [1 none, 2 d|xy|, 3 d|x|, 4 d|y|, 5 d(xy), 6 d(x), 7 d(y)]'... 'iguesszoomselect:value = 1 [0 false, 1 true]'... 'iguesszoomsize:string = 150'... ''... 'iguesssubsetsize:string = 80'... 'iguesssearchsize:string = 160'... 'iguesssubsetrows:string = 5'... 'iguesssubsetcols:string = 5'... 'iguessupdated:string = true'... ''... '[Basis]'... '% this section only defines the defaults of an undefined basis, use the Load button in this section to load a full set of basis functions'... 'basistype:value = 4 [Polynomial,Harmonic,Zernike,B-Spline,FEM T3a,FEM T3b,FEM Q4]'... 'basisboundary:string = 1.4142'... 'basiscols:string = 1'... 'basisrows:string = 1'... 'basisorder:string = 2'... ''... '[Basis plot options]'... 'basissoften:string = 1 % between 0 and 1'... 'basisalpha:string = 0.8 % between 0 and 1'... ''... '[DIC options]'... 'dicdimensions:value = 1 [2D, Quasi 3D]'... 'dicrelaxation:value = 1 [none,constant,linear,quadratic,cubic]'... 'dicrelbasis:value = 1 [same as U, basis 1, etc.] % note that other bases have not been defined yet'... ''... 'dicconvparam:value = 1 [du,b,dp,dr]'... 'dicbestit:value = 1 [r,du,b,dp,dr,last it]'... 'dicmaxdiv:string = 5'... 'dicinciguess:value = 2 [zero,init. guess,prev. inc.,prev. inc., init. guess, reuse]'... 'diclagrange:string = 0 % between 0 and 1'... ''... 'dicautosave:value = 1 [0,1] % i.e. set to 2 to enable autosaving'... 'dicmemsave:value = 2 [0,1,2] % dont get confused, the value indicates the index of the list, a value of 2 means memsave 1'... 'dicprecision:value = 1 [single,double]'... 'dicusegpu:value = 1 [false,true] % remember, specify the index 1->false, 2->true'... ''... '[Preparation Step A]'... 'prepAon:value = 0 % 0 for false, 1 for true'... 'prepAblur:string = 10'... 'prepAlevel:string = 3'... 'prepAimprocess:value = 1 [none,d|xy|,d|x|,d|y|,d(xy),d(x),d(y)]'... 'prepAbasis:value = 1 % remember, there are no bases defined yet'... 'prepAconvcrit:string = 1e-2'... 'prepAmaxit:string = 10'... 'prepAgradient:value = 1 [auto,gradfg,gradf,gradg]'... 'prepAtikhpar1:string = 0.001'... 'prepAtikhpar2:string = 1e-8'... 'prepAtikhsteps:string = 5'... ''... '[Preparation Step B]'... 'prepBon:value = 1 % 0 for false, 1 for true'... 'prepBblur:string = 5'... 'prepBlevel:string = 2'... 'prepBimprocess:value = 1 [none,d|xy|,d|x|,d|y|,d(xy),d(x),d(y)]'... 'prepBbasis:value = 2 % remember, there are no bases defined yet'... 'prepBconvcrit:string = 1e-2'... 'prepBmaxit:string = 20'... 'prepBgradient:value = 1 [auto,gradfg,gradf,gradg]'... 'prepBtikhpar1:string = 0.001'... 'prepBtikhpar2:string = 1e-8'... 'prepBtikhsteps:string = 5'... ''... '[Preparation Step C]'... 'prepCon:value = 1 % 0 for false, 1 for true'... 'prepCblur:string = 1'... 'prepClevel:string = 1'... 'prepCimprocess:value = 1 [none,d|xy|,d|x|,d|y|,d(xy),d(x),d(y)]'... 'prepCbasis:value = 3 % remember, there are no bases defined yet'... 'prepCconvcrit:string = 1e-3'... 'prepCmaxit:string = 50'... 'prepCgradient:value = 1 [auto,gradfg,gradf,gradg]'... 'prepCtikhpar1:string = 0.0001'... 'prepCtikhpar2:string = 1e-9'... 'prepCtikhsteps:string = 10'... ''... '[Final Step]'... 'finalblur:string = 0'... 'finallevel:string = 0'... 'finalimprocess:value = 1 [none,d|xy|,d|x|,d|y|,d(xy),d(x),d(y)]'... 'finalbasis:value = 4 % remember, there are no bases defined yet'... 'finalconvcrit:string = 1e-4'... 'finalmaxit:string = 50'... 'finalgradient:value = 1 [auto,gradfg,gradf,gradg]'... 'finaltikhpar1:string = 0.0001'... 'finaltikhpar2:string = 1e-9'... 'finaltikhsteps:string = 10'... ''... '[Correlate]'... 'corliveview:value = 3 [0, 1, 2] % remember the value represents the index'... 'cor2iguessrows:string = 25'... 'cor2iguesscols:string = 25'... ''... '[Results]'... 'resunderlay:value = 1 [f,g,gtilde,r,none]'... 'ressoftening:string = 1 % between 0 and 1'... 'resoverlay:value = 1 [U1,U2,U3,U4,U5,U6,exx,eyy,exy,eyx,emaj,emin,eeq,r,q,none]'... 'resalpha:string = 0.8 % between 0 and 1'... 'resarrows:value = 1 [U (x,y),strain (xx,yy),strain (min,maj),none]'... 'resarrowscale:string = 1 % between 0 and 10'... 'resrenderer:value = 1 [OpenGL,Zbuffer,Painters]'... ''... 'respixelsize:string = 1'... 'resunit:value = 5 [nm,um,mm,m,km,px,inch,ft]'... 'resstraindef:value = 1 [small,log,Green-Lagrange,Euler-Almansi,membrane,none]'... ''... ''... '[Advanced]'... '% these options do not appear in the GUI'... 'iguessboxedge:value = 5 % the distance in px to the box edge, for the auto iguess points'... 'iguessreject:value = 0.3 % iguess rejected if disp. is bigger (rel. to Lsearch)'... 'cordofsupport:value = 0.1 % the minimum relative area of the support of a basis function'... 'corsparseness:value = 0.3 % use sparse matrices if the average relative support is less'... 'corgradcrit:value = 100 % stop updating auto grad when convcrit < corgradcrit*convcrit'... 'cordivtol:value = 1e-7 % consider diverging if: dr > cordivtol (dr is usually < 0)'... 'basisplotcol:value = 300 % number of pixels to use for the shown bases'... 'patnumfacet:value = 7 % number of facets used for evaluating the pattern'... 'cornquiver:value = 15 % number of arrows to show during correlation'... }; fid = fopen(filename,'w+t'); fprintf(fid,'%s\n',str{:}); fclose(fid); end function str = basicgdic_help str = {... '========================================================================'... ' Basic GDIC tool Help'... '========================================================================'... ''... 'What is the Basic GDIC tool?'... '--------------------------------------'... 'This program can be used to perform Global Digital Image Correlation (GDIC), with the goal to extract the displacement (field) which occurred during the capturing of the (sequence of) images. The program is named basic because it only touches on the most general applications of Global DIC. The main purpose of this tool is to provide an informative platform, such that, the user can get a direct sense of the impact of the various options on the correlation process. The programming is oriented to maximize freedom and understanding at the cost of memory and computational efficiency. Especially, in the current implementation, the heavy requirements on the memory will require user awareness.'... ''... 'This program 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 BSD Open-Source License for more details.'... ''... 'Global DIC in general'... '--------------------------------------'... 'Global DIC refers to DIC methods that solve the displacement field of the entire Region Of Interest (ROI), instead of local Zones Of Interest (ZOI). For this reason the displacement field is approximated with a set of basis functions, (e.g. FEM shape functions) with corresponding degrees of freedom (p). The optimal value for the degrees of freedom is then found by iteratively solving the brightness conservation equation using a Newton-Raphson algorithm. When using a mesh in a FEM simulation, more elements (i.e. more Degrees of Freedom DOF) will give a more accurate result (at the cost of computation time). With DIC this is not always true, more DOF will allow the correlation of a more complex displacement field, however, it will also make the procedure more sensitive to noise, and therefore less accurate. The main take-home-message is then, to use enough DOF required to describe the displacement field of your experiment but use as few as possible to limit noise sensitivity (see also [1,2]). Within the framework of Global DIC it is possible to choose any type of basis with which to discretize the displacement field, this GUI provides a few, selecting the optimum basis is challenging since it depends largely on the case at hand. '... ''... ''... 'Quick Help'... '--------------------------------------'... 'run basicgdic.m with matlab, and the graphical user interface (GUI) will appear.'... ''... 'The basic GDIC tool is organized in three panels:'... ' Panel 1: selection panel (top left)'... ' Panel 2: control panel (bottom left)'... ' Panel 3: figure panel (right)'... ' '... 'Panel 1 is constant, and allows the selection of the 9 sections of the tool. Pressing one of the buttons will switch the other two panels to show the controls and figures related to that particular section. The general procedure is then to start in Section 1 (Images) and work through all the sections ending in Section 8 (Results).'... ''... '- Section 1: Images'... ' Select image files using <Add files>'... ' Put them in order using the <Up> and <Down> buttons'... ' The first image will be the reference (undeformed)'... ' Use the slider bar (or mouse wheel) to view the images'... ' '... '- Section 2: Pattern Eval.'... ' This section can be used to evaluate the correlation length of the images, however, it is not required to preform correlation, see more details below.'... ' '... '- Section 3: ROI and Mask'... ' Set a Region Of Interest (ROI) by pressing <Set ROI>'... ' drag/resize the blue box and confirm by double clicking on the blue box'... ' All material points within the ROI (in image 1) should remain visible in all other images.'... ' Masking is optional, see details below.'... ' '... '- Section 4: Init. Guess'... ' Press <Image Processing> to create images which are more friendly for the automatic initial guess routine.'... ' Press <Add auto> to start the automatic initial guess routine'... ' Drag/Resize the blue box and confirm by double clicking on the blue box'... ' Wait while the initial guess points are computed'... ' Use the slider bar (or mouse wheel) to confirm that the results are acceptable'... ' Use the delete buttons to remove bad initial guess points.'... ' '... '- Section 5: Basis'... ' Select the first basis <Basis 1>'... ' Select the basis family (Polynomial, T3, etc) and other options'... ' Select <Define Basis>'... ' Use the slider bar (or mouse wheel) to evaluate the produced basis functions'... ' Preferably, create three basis sets increasing in number of degrees of freedom'... ' '... '- Section 6: DIC options'... ' On the left are general DIC options, the defaults are reasonable, '... ' see below for more details.'... ' In the right are four panels related to three preparation steps and a fourth and final'... ' step. The goal of the preparation steps is to find an initial guess with less demanding'... ' settings (blurred images and few degrees of freedom). Each consecutive step starts with'... ' the result of the previous step as initial guess.'... ' For each step:'... ' Select the Coarsegrain level N, which will superpixel the image (average N^2 pixels)'... ' Select the basis used in this CG step in order of complexity,'... ' '... '- Section 7: Correlate'... ' Press <Go> to start the correlation process'... ' On the right the residual field is shown, this should decrease to zero if no'... ' acquisition noise is present'... ' The shown arrows display the displacement field'... ' Press <Stop> to abort the correlation process'... ' Pressing <Go> again will continue the previous correlation and skip any increments'... ' which are already done'... ' To start fresh, select <Clear All>'... ' To start from the current results, select <Restart All>'... ' '... '- Section 8: Results'... ' Select a strain definition and wait until the strain fields are computed'... ' Select a pattern to show (lowest plot level)'... ' Select an overlay, e.g. x-displacement or strain-xx (intermediate plot level)'... ' Select a vector field (highest plot level)'... ' Save to .png using <Save>'... ''... '- Section 9: Info'... ' Go back to this help, or show general info or status info produced during the various steps.'... ''... ''... ''... '========================================================================'... ' Detailed Explanation per Section'... '========================================================================'... ''... 'Starting the basicgdic application'... '--------------------------------------'... 'The Graphical User Interface will start after running the basicgdic.m file with matlab.'... ''... 'It is also possible to start the application with an inputfile by running basicgdic(''myinputfile.mat''), where myinputfile.mat should be a file such as saved with the <Save> button in the info section (section 9). This will start the GUI and load the inputfile in the same way as it would be loaded by the <Load> button in the same section. Instead of an inputfile the tool also accepts the D structure as input e.g. basisgdic(D).'... ''... 'Optionally, it is possible to run the basicgdic application in headless mode by also specifying an outputfile e.g. basicgdic(''myinputfile.mat'',''myoutputfile.mat''). This will start the GUI in invisible mode, load the inputfile like before, start the correlation process, save everything to myinputfile.mat, and close the application. The file created can be loaded in the GUI by using the <Load> button of section 9 to evaluate the results. The headless mode is intended such, that you can prepare a correlation using the GUI, providing all the necessities such as initial guess and DIC options on a lightweight machine, say your laptop. Then save everything and start the correlation on a more powerful machine, say a cluster, which may not have a display. Currently, the headless mode is not well tested and care should be taken when running on clusters. For instance, matlab will use more CPU cores then strictly claimed, ask for help if you don''t know what this means. Additionally, the basicgdic application will still generate pop-up error messages when encountered, which may cause problems on the cluster, please test on your own machine first.'... ''... 'The basisgdic tool will also return the D structure. However, in normal GUI mode, the output is returned early in the process, i.e. directly after the tool is loaded. Consequently, the contents of D are not very interesting. However, when in headless mode a full D structure is returned, as if the <Guidata to D> button is pressed just before the tool closes.'... ''... ''... 'Changing the basicgdic defaults'... '--------------------------------------'... 'The basisgdic tool will look for a file named "defaults.ini", stored in the same folder as basicgdic.m. This ini file allows the specification of default settings that will precede the build-in defaults. Be careful, the listed settings must exist in the GUI, i.e. typos will generate an error. Have a look in the lib_bgdic/basicgdic_defaults.ini file for examples, but do not edit that file directly. '... ''... 'The settings consist of three parts: TAG:FIELD = VALUE, which correspond to the VALUE of the matlab uicontrol FIELD of the object with handle TAG. Lines starting with a "%", or a "[" are ignored and everything beyond a % or [ is ignored as well. The TAG and FIELD parts are case-insensitive, the VALUE part is usually case-sensitive. The order in which settings appear is not important.'... ''... ''... 'Section 1. Images'... '--------------------------------------'... 'The first (or top) image will always be considered as the reference configuration. And the order of appearance will also be considered chronological. Therefore, it is important to sort the files correctly. After loading, the images are shown in the right panel, with the image number shown in the lower left corner. It is possible to view all images after loading by dragging the slider bar (or using the mouse wheel) below the figure. The x and y axes will be in pixels throughout the tool, however in the results section they can be converted to physical dimensions.'... ''... 'It is possible to re-order the images at any stage by revisiting this section. However, if the reference image is changed, by either removing it or moving it to another frame, then all computed results are reset. If new images are added, they are added to the bottom of the list, after which they can be moved to the right location in the list. It should be noted that, new images start with an initial guess of zero. In the initial guess section (section 4) this can be fixed using the <Single frame operations>, see below.'... ''... 'Currently a limited number of file-types are supported (basically those supported by the imread command). After loading, all images are stored as double precision floating point matrices. Extending the tool to allow additional file formats should be relatively easy, have a look at the fileadd function in the basicgdic.m file.'... ''... ''... 'Section 2. Pattern Eval.'... '--------------------------------------'... 'Besides the image histogram, shown in bottom of the control panel, this section allows the computation of the Auto Correlation Function (ACF) and the correlation length, or correlation radius (zeta). Press <Evaluate> to start the computation, after which a 7x7 grid of circles is shown in the <Show Pattern> window, and the ACF is shown in the <Show ACF> window. The correlation radius is defined as the radial distance at which the ACF intersects 0.5. The correlation radius can be seen as the allowable distance of your initial guess from the real solution in order to have proper convergence. Since the correlation radius depends on the evaluated area, it is different for each degree of freedom, since they all have a different support. A small correlation radius is detrimental for the robustness. However, a small correlation radius also means that the image gradients are large, which results in improved accuracy. This is the reason why DIC methods (and this tool) usually apply a step-wise procedure where first a correlation is performed on a blurred image (or coarse grained image), the result of which is used as the initial guess for a finer image etc. until finally the image is evaluated in full detail.'... ''... ''... 'Section 3. ROI and Mask'... '--------------------------------------'... 'The Region Of Interest (ROI) is required and defines the area (rectangle) over which the displacement field is computed. Any material point within the ROI in the first image should remain visible in all other images. Otherwise it is not possible to compute a residual (i.e. brightness conservation).'... ''... 'Areas within the ROI which negatively influence the DIC procedure can be excluded from the minimization algorithm by masking them. These are usually areas where there is no sample, no pattern, or a loss of brightness conservation (shadows, reflections, paint loss, etc.).'... ''... 'The displacement field is computed for masked pixels, they just do not have any influence on the solution. If certain degrees of freedom have become ill-supported because most of their supported pixels are masked (more then 80%), then these DOF are also removed from the minimization and the update in those DOF (dp) is set to zero.'... ''... ''... ''... 'Section 4. Init. Guess'... '--------------------------------------'... 'Most DIC procedures are challenged when large displacements are present. In the internal algorithms the pattern is linearized, and due to the high non-linearity of the pattern, this linearization only has a limited range. Therefore it is important to initialize the DIC routine with a good initial guess. This section allows for generating automatic initial guesses using a local DIC (cross-correlation) algorithm. And if this does not work, a manual selection of material points is also possible.'... ''... 'The first options are related to <Image Processing>, where the images can be blurred using a Gaussian kernel with a chosen standard deviation (sigma), remember that the radius of the kernel is approximately 3*sigma. If the blur value is smaller than 0.3, the image is not blurred. The second option is "coarsegrain", which also blurs the image but now by averaging groups of pixels (N^2 x N^2) into superpixels. This option also reduces the image matrix size, thereby reducing the computational cost. The third option <Im. process> creates a new image by computing the image gradients and combining them.'... 'if f is the image:'... 'none => results in the normal image, i.e. no processing'... 'grad|xy| => abs(df/dx) + abs(df/dy)'... 'grad|x| => abs(df/dx)'... 'grad|y| => abs(df/dy)'... 'grad(xy) => (df/dx) + (df/dy)'... 'grad(x) => (df/dx)'... 'grad(y) => (df/dy)'... ''... 'Pressing <Add auto> starts the automated initial guess routine. As said above a local DIC algorithm is used. After pressing the button a popup dialog appears where the parameters of the method can be set (detailed below). Thereafter a blue rectangle is presented in the top left figure which can be resized and repositioned. The location is confirmed by double clicking on the rectangle. After confirmation, the initial guess points are set and the displacement for each subset is computed for all images.'... ''... 'Add auto parameters:'... '<Subset size> => the width (and height) of the square subset in the reference image which is searched for in the deformed images.'... '<Search size> => the width (and height) of the square search area in the deformed images where the reference subset is compared to. The location of the search area is centered around the reference subset location. The search area should be larger than the subset plus the expected displacement. Computed displacements which are at the edge of the search window are automatically discarded.'... '<Subset rows> => Number of subsets rows'... '<Subset cols> => Number of subset columns'... '<Updated> => type "true" to switch the local DIC algorithm between correlating between consecutive images (i.e. updated Lagrange) or "false" to correlate each image with the first image (i.e. total Lagrange).'... ''... 'Afterwards the slider bar (or mouse wheel) can be used to evaluate the generated initial guess points. Any bad initial guess points should be removed before continuing, use the Delete <One>. <Area> or <All> buttons in the bottom of the control panel to delete initial guess points.'... ''... 'If the auto initial guess procedure does not work, a manual procedure is provided by the <Add manual> button. After pressing this button a material point should be selected with the mouse in the top left figure. After which the same material point should be selected for each consecutive image in the top right figure. However some images can be skipped by using the right mouse button. The initial guess will be linearly interpolated/extrapolated for the skipped images.'... ''... 'The box below the <Add manual> button specifies the zoomed area in pixels. If zoomselect is checked (advised) then the first mouse click (in the top left figure) zooms the figures, the second click (in the top left figure) then defines the reference material point. Subsequently, the same material point should be selected in the top right window for each consecutive image as described in the previous paragraph.'... ''... 'The <Single frame operations> allow, as the name suggests, operations in a single frame where:'... '<Zero> sets the (displacements) initial guess points to zero for the current frame.'... '<Auto> performs the same automated initial guess routine as above, except only on the current frame.'... '<Interpolate> interpolates the initial guesses for each point for the current frame based on the initial guesses of all other frames. A linear interpolation scheme in time is used per point, which can also extrapolate. This method assumes a constant time spacing of the image frames, and actually does not use any information from the image itself.'... ''... ''... 'Section 5. Basis'... '--------------------------------------'... 'The power of Global DIC is in the wide range of choices for basis functions. As discussed before, too few DOF will restrict the kinematics too much resulting in reduced accuracy, and too many DOF will make the method noise sensitive, resulting in reduced accuracy. Consequently there is an optimum, which is the minimum number of DOF which include the (yet unknown) displacement field. Obviously, this minimum depends in the experiment at hand. Less obviously, this minimum also depends on the type of basis, i.e. the family of shape functions.'... ''... 'Usually, a new basis set is defined per coarse grain step, however it is possible to define as many as you like in this section. In most cases 3 coarse grain steps, and thus 3 basis sets, will suffice for the correlation process. All coarse grain steps except the last are only used to as an initial guess for the next coarse grain step. Therefore, their displacement fields (and thus their basis) only has to be good enough to give a adequate initial guess. Consequently, using Polynomial or Harmonic basis sets for the these CG steps tends to work better since these functions are more robust (due to their wide support).'... ''... 'To define a basis set use the <New> button to start a new set, or the <Del> button to remove a set, or make a copy of a set using the <Dupl.> button. Depending on the selected <Type> (more details below) the <Boundary ratio>, <Rows>, <Cols> and <Order> options will be available. The <Basis name> option can be used to give the basis set a custom name. After setting all of these options, the <Define Basis> button can be used to generate the basis functions, which will appear on the right for evaluation. Obviously, it is possible to redefine any of the defined basis sets by just going back to the basis set, changing some options and pressing <Define Basis> again.'... ''... 'Polynomial:'... 'These functions have support over the entire ROI making them highly robust, but not well suited for highly localized deformations. The zero order functions allow constant displacements (i.e. rigid body translation), first order functions allow constant strain, etc. The 2D shapes are computed from the dyadic product of two 1D Legendre polynomials. The polynomials are computed on normalized coordinates which span from -1 to 1 over the ROI in both directions. Consequently, these basis functions are always 1, or -1 in the corners of the ROI.'... ''... 'Harmonic:'... 'Similar to the polynomials, these also have wide support over the entire ROI. They are created by the dyadic product of 1D sine and cosine functions. The zero order is a (non-harmonic) constant function, i.e. a zero order polynomial. Each consecutive order introduces a pair of harmonic functions with one wavelength (a sine and a cosine), with decreasing wavelength for increasing order. The wave lengths are chosen such that they fit "k" times in 1.5 times the width and height of the ROI, centered in the ROI.'... ''... 'Zernike:'... 'These 2D orthogonal pseudo Zernike polynomials are defined on circular coordinates. They are particularly useful for describing lens aberrations.'... ''... 'B-Spline:'... 'With the <Rows> and <Cols> a rectangular grid (control net) is defined in which regular 1D B-Spline functions are used to compute 2D shapes. Zero order B-Splines result in local DIC like behavior, i.e. subsets. First order B-Splines are equal to bi-linear (Q4) FEM shape-functions. And higher order B-Splines are also possible. Strain is the first derivative of the displacement, therefore, to have continues smooth strain fields, second order B-Splines are recommended. The <boundary ratio> option changes the spacing of the boundary knots relative to the spacing of the internal knots. If unsure about which basis fits the best for your case, try the second order B-splines, and play with the number of rows and cols.'... ''... 'FEM Triangle:'... 'This generates a FE mesh of triangular elements. The mesh is generated by initiating a set of nodes in a grid which are connected by Delauney triangulation. The difference between "Triangle (a)" and "Triangle (b)" is the way the nodes are positioned before triangulation. Note that even if the nodes are in a constant grid, that there is some variation in the size of the support for each DOF, depending on the connectivity. The <boundary ratio> option changes the spacing of the boundary nodes relative to the spacing of the internal nodes. This mesh type accepts <order = 1> for linear 3-noded (T3) elements, or <order = 2> for quadratic 6-noded (T6) elements.'... ''... 'FEM Quad:'... 'This generates a FE mesh of quadrilateral elements in a regular grid. The <boundary ratio> option changes the spacing of the boundary nodes relative to the spacing of the internal nodes. This mesh type accepts <order = 1> for bi-linear 4-noded (Q4) elements, or <order = 2> for serendipity 8-noded (Q8) elements. The regular mesh generation is only a limitation of the mesh generator, the GUI can deal with irregular meshes. Although, obtaining the FEM shape-functions requires a reverse mapping operation which can be unstable at the element corners if the elements are too distorted (e.g. more than 15% distortion).'... ''... 'Custom meshes:'... 'The basis functions can be saved to a .mat file, and loaded back into to tool. This also provides a means to load custom meshes. Have a look at the way the .mat file is structured by saving the mesh and loading it in matlab using the "load" command. '... 'For example (assuming a FEM Q4 mesh loaded in basis 1):'... ' use the <save> button (in section 5) to save the basis.mat file then run:'... ' >> load basis.mat'... ' >> bgdic.basis(1).coordinates = bgdic.basis(1).coordinates + 3*randn(size(bgdic.basis(1).coordinates,1),2)'... ' >> save(''basis.mat'',''bgdic'')'... ' then load the .mat file using the <load> button (in section 5).'... ''... 'Section 6. DIC Options (General Options)'... '--------------------------------------'... 'On the left are the general DIC options:'... ''... '<Dimen.> "2D" or "Quasi 3D", the latter switches to Quasi 3D, which means that the image gray values are interpreted as height values. Use this method if the images are surface topographies.'... ''... '<Relax.> This option allows the relaxation of the brightness equation, select "none" to disable relaxation. Otherwise, set the desired order of relaxation. The brightness conservation equation will be enriched with a number of terms (equal to the chosen order) i.e. r = f - (g + U3*g^0 + U4*g^1 + U5*g^2 + U6*g^3). It is important to realize that U3,U4,U5 and U6 are fields which require basis functions and degrees of freedom, similarly as the in-plane displacement fields (U1,U2). The basis for the relaxation fields can be set in the next option <Rel. Basis>. Brightness relaxation is essential when there have been irregularities in the image intensity during the experiment. Examples are, changes in lighting conditions or reflections on the sample surface. Typically, "Constant" or "Linear" brightness relaxation is sufficient. '... ''... '<Rel. Basis> Select the basis set, used to describe the additional brightness (and/or contrast) fields. The "same as U" option uses the same basis set as used for the displacement field, which may vary for each coarse grain step. The other items in the list are basis sets defined in section 5, selecting one of those will cause the same basis set to be used for all coarse grain steps.'... ''... '<Conv. Cr.> Which parameter to use to test convergence on. "Change in disp." is the maximum of the iterative change in the displacement fields, in pixels. "The right hand member" is the norm of b, which is the object the DIC algorithm is actually reducing to zero. "update in dof" is the norm of dp, which is the iterative change in the degrees of freedom. "change in residual" is the change in the norm of r, in GV. Due to acquisition noise and interpolation errors, the residual usually does not really go to zero, therefore the change in the residual is offered as a convergence parameter.'... ''... '<Best iter.> After convergence is reached, instead of using the last iteration, it is also possible to use a previous iteration as final result. Select which <Best iter.> parameter to use to identify the best iteration. "residual" uses the iteration with the lowest (mean, absolute) residual. The following four are the same ones as discussed for the convergence criterion. The last option is "last it." simply uses the last computed iteration.'... ''... '<Max div.> If the correlation procedure causes the residual to increase N consecutive times the coarse grain step is stopped. For each iteration which decreases the residual the counter is reduced by 0.5.'... ''... '<Next inc.> This option selects how the initial guess is computed for the next increment. "Zero" causes all DOF to be initiated at zero for each increment (only for the first coarse grain step). "init. guess" uses the initial guess points as defined in section 4 for each increment. "prev. inc." uses the displacement field of the previous increment as initial guess for this increment (zero for the first increment). "prev. inc. and init. guess" averages between the second and third option. The "reuse" option re-uses the data currently present in the GUI, i.e. the data from a previous correlation result. This option reverts to "prev. inc." if no previous data for an increment is found.'... ''... '<Total/Updated Lagrange> A Total DIC scheme always correlates between the first image and the current (i) image. An Updated scheme always correlates between two consecutive images (i-1 and i). The advantage of a total scheme is that it is more accurate since each increment is minimized individually. However, if the pattern changes during the experiment due to shadows, reflection, paint loss, etc. then the current image may be too different from the first image for successful correlation. Consequently an updated scheme is more robust, but errors in the displacement scheme are accumulated over the increments. Beware, using a non-zero value here will make the correlation of the current increment depend on the quality of the correlation of the previous increment. If the previous increment is not converged, the algorithm will skip the current increment, and probably all following ones.'... ''... '<Auto save> This option causes the correlation results to be saved at the end of each increment. Upon pressing <Go> in section 7, a file selection popup appears to select the location for the autosave file. The file is overwritten after each increment.'... ''... '<Mem. save> This particular DIC tool is very memory hungry. This is because internally, a matrix L is required to compute M (the correlation matrix) and b (the right hand member). The number of rows in this L matrix is equal to the number of unmasked pixels within the ROI, the number of columns in this L matrix is equal to the number of DOF. For example a 1 Megapixel image with a T3 mesh with 100 nodes will require an L matrix of 1e6*100*2*8 = 1.6 Gb for 2D and even more for Quasi 3D or brightness and contrast relaxation. Choosing <Mem. save = 0> causes exactly this behavior, which is the fastest option if your computer has enough memory. Choosing <Mem. save = 1> partitions the L (and M) matrix into parts separated per dimension (2 for 2D, 3 for 3D or 2D+B, 4 for 2D+B+C). This is slower but halves (or more) the required memory space. Choosing <Mem. save = 2> partitions the L (and M) matrix per DOF, this greatly reduces the memory requirements but these L partitions need to computed over and over since they cannot be stored in memory, this last option is very slow. Instead of using the last option, in most cases using a coarse-grained final image can give faster but slightly les accurate results. Whenever possible (e.g. FEM or B-Spline basis) L is stored sparsely, which will save a lot of memory, however this complicates the prediction of the required memory.'... ''... '<Precision> This option sets the internal precision to "single" (32-bit) or "double" (64-bit). Setting the precision to single causes the memory requirement to be halved, and greatly improves the computation speed on graphics cards. However, the floating point precision will be reduced from approximately 16 digits to 6 digits behind the decimal. Moreover, Matlab cannot handle single precision sparse matrices, therefore, sparse matrices are disabled when the precision is set to single.'... ''... '<use GPU> Enabling this transfers some computations to the GPU (Graphics Card) instead of the CPU. The code is not optimized for GPU computing, it merely utilizes the Matlab built-in CUDA capabilities, and therefore requires a CUDA (NVidia) video card. Typically, the video card has less memory than the CPU, which will be limiting when correlating larger images (e.g. 1 Mpx) with many DOF. Additionally, current Matlab versions (2013b) cannot deal with sparse matrices on the GPU, making the problem worse.'... ''... ''... 'Section 6. DIC Options (Preparation Steps and Final Steps)'... '--------------------------------------'... 'On the right are the options for each step. Three optional preparation steps and one mandatory final step can be configured. The result of each step will serve as the initial guess to the next step. In most DIC cases 2 coarse preparation steps should be sufficient, therefore, the fest step is disabled by default. '... ''... 'The goal of these preparation steps is to perform DIC using less accurate but more forgiving settings. This way the algorithm can converge more easily. The result only needs to be accurate enough to serve as a initial guess for the next step which will have more demanding settings. This mostly boils down to two things: Smoothing the image (blur/coarsegrain) and reducing the number of DOF of the basis (selecting an easier basis e.g. bigger elements).'... ''... 'Blurring an image results in a larger correlation radius, i.e. allows the algorithm to converge without getting stuck in a local minimum. However, blurring also removes information from the image, which reduces the accuracy, but also limits the number of DOF that can be found. The better the provided initial guess, the less coarse graining is required. '... ''... 'Each step has the same options:'... ''... '<On/Off> Enable, disable this step. '... ''... '<Blur> Blur the image with a Gaussian kernel with standard radius (sigma) N, remember that the support of the kernel is approximately 3*N. Blurring removes fine detail to allow for longer distance correlation but does not reduce the number of pixels. Consequently, this method has no speed gain, but is less likely to produce singularity problems.'... ''... '<Coarsegrain> This option creates a new image with superpixels. The superpixels are computed by averaging groups of (N^2 x N^2) pixels. This has the combined effect of blurring and reducing the matrix size. This is the preferred method of coarse graining. Remember that a CG level of 4 will create superpixels of size 16x16 which reduces a 1 Megapixel image to roughly 4000 pixels (62x62), setting the CG level higher is usually not useful.'... ''... '<Image Process> This option allows the computation of a gradient image, which is then used instead of the real image to correlate with. Gradient images highlight edges, which may be useful for cases with large variations in grayvalues from image to image, e.g. shadows or reflections. Such detrimental features usually have less influence on the gradient images. For most cases this is not recommended.'... ''... '<Basis> Select one of the bases defined in section 5. Make sure to set the basis with the least DOF for the first step and the basis with the most DOF for the final step.'... ''... '<Convcrit.> The convergence criteria, i.e. when to consider the step converged. For the first two steps a relatively coarse criteria can be used (e.g. 1e-2) since the obtained results are only initial guesses for the final step.'... ''... '<Maxit.> Maximum number of iterations in this step. Similar to the <Convcrit.> the first steps do not require perfect convergence, the result only needs to be "good enough" as an initial guess for the next step.'... ''... '<Image Gradient> This is the image gradient used in the iterative (Newton-Raphson) algorithm, see [3] for more details.'... 'gradf: the classical DIC gradient, the cheapest to compute, but limited to small displacements.'... 'gradg: the consistent DIC gradient, expensive to compute, compatible with large displacements.'... 'gradfg: the average of the above two, expensive to compute, has an advantage when far from the solution, i.e. for bad initial guesses, suited for intermediate displacements (e.g. rotations up to 45?).'... 'auto: starts the routine with gradfg, but stops updating the gradient when close to convergence to reduce the computational cost. The transition occurs when the chosen convergence parameter is smaller than 100 times the set convergence criteria.'... ''... '<Tikhonov Regularization> This method adds a second potential to the minimization potential which increases when the DOFs move away from their initial guess. The strength of this potential is controlled with the Tikhonov parameter (alpha). It is implemented such that alpha can change in each iteration moving from <alpha(1)> to <alpha(2)> in N logarithmic steps (set by <steps>). The Tikhonov parameter is specified relative to the largest eigenvalue of M. Consequently, setting alpha higher than 1 strongly restricts the DOF to move away from their initial value. The regularization is stronger for the weak eigenmodes of the problem, which is why it is so well suited for DIC problems. It tends to limit the motion of DOFs which can not be identified anyway. However, it also moves the solution away from the true solution, therefore well defined problems are best solved with low alpha values (e.g. 1e-6). Setting the number of steps to zero causes Tikhonov regularization to be disabled.'... ''... ''... 'Section 7. Correlate'... '--------------------------------------'... '<Go> start the correlation process. '... ''... '<Stop> abort the correlation process, this may take some time before the tool evaluates this action, please be patient. '... ''... 'The <Continue> button sets the current iteration to be converged (regardless of the value of the convergence criteria) and continues to the next CG step.'... ''... 'The status view below the <stop> button shows the correlation progress. In particular it shows which CG step of which increment is currently running, and the value of the convergence parameter for each iteration. Note the "( x/ x) free dof" line, which shows if all DOF are actually used. If due to masking certain basis functions have become ill-supported (less than 20% unmasked) then they are excluded from the DIC algorithm and locked at their initial value.'... ''... 'If the <Live view level> is set to "2", the residual field will be plotted for each iteration. The residual field should reduce to (close to) zero. If a particular area in the ROI has difficulty converging consider adding an initial guess point to that location, or increase the size of the basis functions supported by that area.'... ''... 'Pressing <Go> again starts the correlation process again, however, increments which are complete are not correlated again. To re-correlate an increment it needs to be cleared using the <Clear Inc.> button, which clears the currently visible increment, or the <Clear All> button. Alternatively, use <Restart Inc.> or <Restart All> to the request reusing the previous correlation result as an initial guess to the current correlation, as if it was computed in a previous coarse grain step.'... ''... 'The <to iguess> button takes a complete correlation and converts it to initial guess points, which are added to the existing initial guess points. Typically, it is better to remove the old initial guess points before pressing <to iguess>. After pressing <to iguess> a dialog appears asking to specify how many initial guess points need to be stored (as an x-y grid). It is advised to make sure that the number of initial guess points is more than twice the number of DOF in the coarsest basis. This is to make sure the conversion from initial guess points to DOF is well defined. Otherwise, the tool will approximate the DOF by first fitting a polynomial of adequate order (max 4th order) through the initial guess points.'... ''... ''... 'Section 8. Results'... '--------------------------------------'... 'The first time this section is selected, the strain fields are computed after selection of the strain definition. Selecting a different strain definition will cause the strain fields to be re-computed.'... ''... 'Three levels of plotting are defined: "Pattern", "Overlay", and "Vectors", which can be plotted simultaneously.'... ''... 'The lowest level is the "Pattern", selecting "f", "gtilde", or "r" (residual) will show the other layers in the undeformed configuration. Selecting "g" will deform the other fields such that they follow the material points. The slider bar below the pattern allows softening of the pattern, i.e. reducing the intensity.'... ''... 'The intermediate level "Overlay", allows plotting of a scalar field, for instance the x-displacement, where the scalar values are displayed as a color. '... '- U1, and U2 are the x- and y-displacement respectively,'... '- when using Quasi-3D DIC, U3 is the z-displacement,'... '- when in 2D, U3, U4, U5 and U6 are constant, linear, quadratic and cubic corrections in'... ' brightness respectively (with respect to the intensity)'... '- q is the combined result of all brightness corrections '... ' q = U3 + U4*gt + U5*gt^2 + U6*gt^3'... '- r is the residual'... 'The overlay slider bar controls the alpha value of the overlay (0 = transparent, 1 = opaque). On the right side of the colorbar (in the figure panel) are two edit boxes, these allow manual selection of the color limits. If both are 0, then the color limits are automatically scaled.'... ''... 'The top most plot level "Vectors" allows displaying of vector fields, for instance the displacement vectors. The "strain (min,maj)" option shows the major strains and minor strains in their corresponding directions. The slider scales the arrows, if set to 1, then their lengths is to scale.'... ''... 'On the bottom the pixel size (and unit) can be given, such that the displacements are shown in physical quantities. For the strain measures this pixel calibration is not relevant.'... ''... 'The <strain definitions> below are all 2D, switching to a different definition causes the strain tensors to be computed for each pixel in the ROI. Especially the "logarithmic strain" and "Euler-Almansi strain" are slow since they require a tensor spectral decomposition per pixel. The "membrane strain" is for Quasi 3D use, where the 2D strain along the membrane tangent plane is given using a small deformation formulation.'... ''... 'The <Save> button will copy the current figure window and ask where to save the .png file. The copied window is very similar to a normal matlab figure window, thus normal matlab operations are possible. For instance note the "Plot Tools" icon in the top toolbar, which allows changing of almost anything in the figure.'... ''... 'The <Cross-section> button is not implemented yet.'... ''... 'If Arithmetic on these fields is desired the tool can be tricked. In section 9, there are two buttons which allow you to put all the data to the matlab workspace <Guidata to D> and read the (modified) data structure back to the gui <D to Guidata>.'... ''... 'Example:'... ' <Guidata to D>'... ' >> D.res(1).Eeq = sqrt(D.res(1).Emin.^2 + D.res(1).Emaj.^2);'... ' <D to Guidata>'... ''... 'this example reads the data from the gui, computes the equivalent strain field for all pixels for the first increment, and writes the data back to the gui. If the gui now updates its figure (for instance by re-selecting "strain eq." in the Overlay) then the new equivalent strain is shown.'... ''... ''... 'Section 9. Info'... '--------------------------------------'... 'This Section houses the <Info>, <Status>, <Help> panels. The first to will be filled by using the tool. The data is also stored in D.gui.stat and D.gui.info.'... ''... '========================================================================'... ' General Tips and Tricks'... '========================================================================'... ''... 'Tip 1: Initial Guess'... '--------------------------------------'... 'Spend time on the initial guess, having a good initial guess will make a big difference during correlation.'... ''... 'Tip 2: Coarse basis functions'... '--------------------------------------'... 'Use full support basis functions (polynomial, harmonic, zernike) for the first two CG steps. These functions are more robust, but have problems capturing the fine details in the deformation fields. The polynomials seem to work well up to 5th order, above, the harmonic basis is recommended.'... ''... 'Tip 3: Use B-Splines'... '--------------------------------------'... 'Especially the second order B-Splines seem to be a good choice for the final coarse grain step.'... ''... 'Tip 4: Correlate, Learn, Improve, Correlate'... '--------------------------------------'... 'Start with a quick correlation with simple basis functions and coarse grained images, this makes the correlation fast, and allows identification of the problem areas. Add initial guess points in those problem areas, and try again. The results will not be accurate but will provide an excellent initial guess for the final high detail correlation.'... ''... 'Tip 5: All data is in D'... '--------------------------------------'... 'Have a look at the guidata structure in the tool <guidata to D>. This structure contains all the data you see in the tool. For instance all the correlation results are stored in "D.cor(inc)" where inc is the increment number. The extra result fields, such as strain are stored in "D.res(inc)", etc.'... ''... ''... ''... '========================================================================'... ' Back matter'... '========================================================================'... ''... 'References'... '--------------------------------------'... '[1] J. Neggers, J.P.M. Hoefnagels, F. Hild, S.G. Roux and M.G.D. Geers, Direct stress-strain measurements from bulged membranes using topography image correlation, Experimental Mechanics, 2014'... '[2] Hild F, Roux S. Comparison of Local and Global Approaches to Digital Image Correlation. Experimental Mechanics. 2012 13;52(9):1503?19.'... '[3] J. Neggers, B. Blaysat, J.P.M. Hoefnagels, M.G.D. Geers, On image gradients in digital image correlation, Int. J. Numer. Meth. Engng, 2015 doi:10.1002/nme.4971'... ''... ''... 'Changelog'... '--------------------------------------'... 'version 1.00, JN: compiled version of 0.29'... 'version 0.28, JN: the last CG step is now mandatory for more robust correlation, fixed a bug in prev. inc., fixed a bug in updated-lagrange, optimized the plotting code for speed, implemented a new selection tool to replace imrect'... 'version 0.26, JN: improved the dof conversion: masking for pprev, rank test for piguess '... 'version 0.25, JN: added the du convergence parameter'... 'version 0.24, JN: remember save/load locations'... 'version 0.23, JN: added the zernike polynomial basis, correlation reuse and a new defaults implementation'... 'version 0.22, JN: fixed a fundamental flaw in the brightness relaxation (and added up to cubic relaxation)'... 'version 0.21, JN: corrected the green-lagrange strain, and some minor bugs'... 'version 0.20, JN: bug fix release, also updated all the popup messages to better support a multimonitor setup'... 'version 0.19, JN: changed the basis section to allow an unlimited number of basis sets. Added a fourth (extra fine) coarse grain step. Added automatic gradient selection, changed the correlation length algorithm'... 'version 0.18, JN: bugfix release, also reduced the size of save files'... 'version 0.17, JN: improved file management to allow adding and removing of images at any stage in the tool. basicgdic now accepts two optional variables, basicgdic(inputfile,outputfile) to allow it to run headless.'... 'version 0.16, JN: added T6, Q4 and Q8 element types'... 'version 0.14, JN: added autosave feature, modified bestit feature.'... 'version 0.12, JN: bug fixes (many found by Johan)'... 'version 0.10, JN: first beta, all features complete, '... 'version 0.07, JN: alpha state, many changes'... 'version 0.01, JN: initial version, incomplete'... ''... 'Contact Information'... '--------------------------------------'... '[email protected]'... ''... ''... 'Information about the Code Structure'... '--------------------------------------'... ''... 'The most interesting files are:'... 'basicgdic.m --> contains most of the functions directly connected to a control'... 'lib_bgdic/basicgdic_uicontrols.m --> creates all the controls (buttons,axes,etc.)'... 'lib_bgdic/corsequence.m --> Controls the correlation sequence (pre-processing)'... 'lib_bgdic/correlate.m --> Correlates two images'... 'lib_bgdic/rescompute.m --> Compute the results (strain fields)'... ''... 'Related to the GUI:'... 'The main window of the graphical user interface (GUI) is a matlab figure window. The figure window can be identified programmatically by it''s handle. If it is the first window you open after starting matlab, the handle will be 1. Throughout the code this handle is stored in the variable H. Any matlab figure window can also contain data. This data can be stored and loaded using the guidata function. This mechanism is used throughout the code to transfer the data from one function to the next. Therefore, most functions start with, <D = guidata(H)> which reads the data from figure window, and end with, <guidata(H,D)> to store the data back to the figure window. Functions which do not have the <D = guidata(H)> line simply do not require any data, and functions which do not have the <guidata(H,D)> line simply do not change any data.'... ''... 'Each control (button/axes/etc.) has a list of properties connected to it, two of which are interesting: ''Tag'' and ''Call''. The Tag of a control is used to generate an automatic structure of handles using the <S = guihandles(H)> command. These handles can then be used to modify all properties of the control such as the ''Value'' or the ''String''. The Call property specifies a function which is called when that particular control is activated (e.g. pressing a button). All the (smaller) callback functions are inside the basicgdic.m file, and are grouped per section, with the general functions listed before the first section.'... ''... 'The m-file lib_bgdic/basicgdic_uicontrols.m is called in the beginning of the basicgidc.m function. In this m-file all the panels, buttons, axes, etc. are defined. They are organized per section, with the general definitions in the top (for the panels and the sections itself). So if you wish to find the properties of a certain button, look for the big comment indication it''s section, and then the particular button is nearby. This GUI contains three panels, which seem to switch content. This is not actually true, the way this is programmed is that concurrently 9 versions of the control panel and figure panel exist, but 8 of them are invisible. Pressing the buttons in the section selection panel only changes the visibility state such that the correct panel is now visible. Every object which is a child (or grandchild) of a panel is automatically set to the same visibility state as the panel. Therefore, setting the panel to invisible causes every object inside the panel to become invisible if it''s parent property is set correctly. Consequently, if you wish to add a button to a panel you need to set the parent property correctly such that it''s visibility state is handled correctly.'... ''... 'Have a look at the lib_btgdic/plot<something>.m functions to see how the figures in the various figure panels are created.'... ''... 'Related to DIC:'... 'A DIC code, which correlates the displacement field between two images is really very simple and rather short. Including the code to deal with all the options in this tool, the lib_bgdic/correlate.m function is still less than 1000 lines. Strip it to the basics and you can write a GDIC code in less than 20 lines. However, more work needs to be done before a correlation can start. How to transfer the results from one correlation to the next, considering that the previous correlation can be a different coarse grain step, or a different increment, or the first increment, or etc? All this work is handled by the lib_bgdic/corsequence.m file, with some helper functions. It processes the previous results and the settings for the next correlation and prepares the new basis functions and the initial values of the corresponding DOF. Afterwards, some post-processing is required (computing the strain fields) which is performed in the lib_bgdic/rescompute.m file.'... ''... 'Please do not hesitate to email me if you plan to modify this program and need some help.'... ''... ''... 'Copyright'... '--------------------------------------'... ''... ''... 'Copyright 2017 Jan Neggers'... ''... 'This program is free software; you can redistribute it and/or modify it under the terms of the BSD Open-Source License supplied with this software.'... ''... 'This program 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.'... ''... ''... ''... ''... ''... ''... }; end
github
Jann5s/BasicGDIC-master
quiverjn.m
.m
BasicGDIC-master/lib_bgdic/quiverjn.m
9,790
utf_8
1917f7f867d9e0c5d9134f4b0aa0059e
function hh = quiverjn(varargin) %QUIVER Quiver plot. % QUIVER(X,Y,U,V) plots velocity vectors as arrows with components (u,v) % at the points (x,y). The matrices X,Y,U,V must all be the same size % and contain corresponding position and velocity components (X and Y % can also be vectors to specify a uniform grid). QUIVER automatically % scales the arrows to fit within the grid. % % QUIVER(U,V) plots velocity vectors at equally spaced points in % the x-y plane. % % QUIVER(U,V,S) or QUIVER(X,Y,U,V,S) automatically scales the % arrows to fit within the grid and then stretches them by S. Use % S=0 to plot the arrows without the automatic scaling. % % QUIVER(...,LINESPEC) uses the plot linestyle specified for % the velocity vectors. Any marker in LINESPEC is drawn at the base % instead of an arrow on the tip. Use a marker of '.' to specify % no marker at all. See PLOT for other possibilities. % % QUIVER(...,'filled') fills any markers specified. % % QUIVER(AX,...) plots into AX instead of GCA. % % H = QUIVER(...) returns a quivergroup handle. % % Example: % [x,y] = meshgrid(-2:.2:2,-1:.15:1); % z = x .* exp(-x.^2 - y.^2); [px,py] = gradient(z,.2,.15); % contour(x,y,z), hold on % quiver(x,y,px,py), hold off, axis image % % See also FEATHER, QUIVER3, PLOT. % Clay M. Thompson 3-3-94 % Copyright 1984-2010 The MathWorks, Inc. % $Revision: 5.21.6.22 $ $Date: 2011/04/04 22:59:11 $ % First we check which HG plotting API should be used. if ishg2parent( varargin{:} ) [~, cax, args] = parseplotapi(varargin{:},'-mfilename',mfilename); h = quiverHGUsingMATLABClasses(cax, args{:}); else [v6, args] = usev6plotapi(varargin{:},'-mfilename',mfilename); [cax, args] = axescheck(args{:}); if v6 h = Lquiverv6(cax, args{:}); else nargs = length(args); error(nargchk(2,inf,nargs,'struct')); % Parse remaining args try pvpairs = quiverparseargs(args); catch ME throw(ME) end if isempty(cax) || isa(handle(cax),'hg.axes') cax = newplot(cax); parax = cax; hold_state = ishold(cax); else parax = cax; cax = ancestor(cax,'Axes'); hold_state = true; end [ls,c] = nextstyle(cax); h = specgraph.quivergroup('Color',c,'LineStyle',ls,... 'parent',parax,pvpairs{:}); if ~any(strcmpi('color',pvpairs(1:2:end))) set(h,'CodeGenColorMode','auto'); end set(h,'refreshmode','auto'); if ~hold_state, box(cax,'on'); end plotdoneevent(cax,h); h = double(h); end end if nargout>0, hh = h; end function h = Lquiverv6(cax, varargin) args = varargin; nargs = length(args); % Arrow head parameters alpha = 0.33; % Size of arrow head relative to the length of the vector beta = 0.5; % Width of the base of the arrow head relative to the length autoscale = 1; % Autoscale if ~= 0 then scale by this. plotarrows = 1; % Plot arrows filled = 0; ls = '-'; ms = ''; col = ''; nin = nargs; % Parse the string inputs while ischar(args{nin}), vv = args{nin}; if ~isempty(vv) && strcmpi(vv(1),'f') filled = 1; nin = nin-1; else [l,c,m,msg] = colstyle(vv); if ~isempty(msg), error(id('UnknownOption'),'Unknown option "%s".',vv); end if ~isempty(l), ls = l; end if ~isempty(c), col = c; end if ~isempty(m), ms = m; plotarrows = 0; end if isequal(m,'.'), ms = ''; end % Don't plot '.' nin = nin-1; end end error(nargchk(2,5,nin,'struct')); % Check numeric input arguments if nin<4, % quiver(u,v) or quiver(u,v,s) [msg,x,y,u,v] = xyzchk(args{1:2}); % "xyzchk(Z,C)" else [msg,x,y,u,v] = xyzchk(args{1:4}); % "xyzchk(X,Y,Z,C)" end if ~isempty(msg), if isstruct(msg) % make the xyzchk message match quiver's help string: msg.message = strrep(msg.message, 'Z', 'U'); msg.message = strrep(msg.message, 'C', 'V'); msg.identifier = strrep(msg.identifier, 'Z', 'U'); msg.identifier = strrep(msg.identifier, 'C', 'V'); else msg = strrep(msg, 'Z', 'U'); msg = strrep(msg, 'C', 'V'); end error(msg); end if nin==3 || nin==5, % quiver(u,v,s) or quiver(x,y,u,v,s) autoscale = args{nin}; end % Scalar expand u,v if numel(u)==1, u = u(ones(size(x))); end if numel(v)==1, v = v(ones(size(u))); end if autoscale, % Base autoscale value on average spacing in the x and y % directions. Estimate number of points in each direction as % either the size of the input arrays or the effective square % spacing if x and y are vectors. if min(size(x))==1, n=sqrt(numel(x)); m=n; else [m,n]=size(x); end delx = diff([min(x(:)) max(x(:))])/n; dely = diff([min(y(:)) max(y(:))])/m; del = delx.^2 + dely.^2; if del>0 len = sqrt((u.^2 + v.^2)/del); maxlen = max(len(:)); else maxlen = 0; end if maxlen>0 autoscale = autoscale*0.9 / maxlen; else autoscale = autoscale*0.9; end u = u*autoscale; v = v*autoscale; end cax = newplot(cax); next = lower(get(cax,'NextPlot')); hold_state = ishold(cax); % Make velocity vectors x = x(:).'; y = y(:).'; u = u(:).'; v = v(:).'; uu = [x;x+u;repmat(NaN,size(u))]; vv = [y;y+v;repmat(NaN,size(u))]; % QUIVER calls the 'v6' version of PLOT, and temporarily modifies global % state by turning the MATLAB:plot:DeprecatedV6Argument and % MATLAB:plot:IgnoringV6Argument warnings off and on again. oldWarn(1) = warning('off','MATLAB:plot:DeprecatedV6Argument'); oldWarn(2) = warning('off','MATLAB:plot:IgnoringV6Argument'); try h1 = plot('v6',uu(:),vv(:),[col ls],'parent',cax); if plotarrows, % Make arrow heads and plot them hu = [x+u-alpha*(u+beta*(v+eps));x+u; ... x+u-alpha*(u-beta*(v+eps));repmat(NaN,size(u))]; hv = [y+v-alpha*(v-beta*(u+eps));y+v; ... y+v-alpha*(v+beta*(u+eps));repmat(NaN,size(v))]; hold(cax,'on') h2 = plot('v6',hu(:),hv(:),[col ls],'parent',cax); else h2 = []; end if ~isempty(ms), % Plot marker on base hu = x; hv = y; hold(cax,'on') h3 = plot('v6',hu(:),hv(:),[col ms],'parent',cax); if filled, set(h3,'markerfacecolor',get(h1,'color')); end else h3 = []; end catch err warning(oldWarn); %#ok<WNTAG> rethrow(err); end warning(oldWarn); %#ok<WNTAG> if ~hold_state, hold(cax,'off'), view(cax,2); set(cax,'NextPlot',next); end h = [h1;h2;h3]; % function [pvpairs,args,nargs,msg] = parseargs(args) % % separate pv-pairs from opening arguments % [args,pvpairs] = parseparams(args); % n = 1; % extrapv = {}; % % check for 'filled' or LINESPEC % while length(pvpairs) >= 1 && n < 3 && ischar(pvpairs{1}) % arg = lower(pvpairs{1}); % if arg(1) == 'f' % pvpairs(1) = []; % extrapv = {'MarkerFaceColor','auto',extrapv{:}}; % else % [l,c,m,tmsg]=colstyle(pvpairs{1}); % if isempty(tmsg) % pvpairs(1) = []; % if ~isempty(l) % extrapv = {'linestyle',l,extrapv{:}}; % end % if ~isempty(c) % extrapv = {'color',c,extrapv{:}}; % end % if ~isempty(m) % extrapv = {'ShowArrowHead','off',extrapv{:}}; % if ~isequal(m,'.') % extrapv = {'marker',m,extrapv{:}}; % end % end % end % end % n = n+1; % end % pvpairs = [extrapv pvpairs]; % msg = checkpvpairs(pvpairs); % nargs = length(args); % if isa(args{nargs},'double') && (length(args{nargs}) == 1) && ... % (nargs == 3 || nargs == 5) % if args{nargs} > 0 % pvpairs = {pvpairs{:},'autoscale','on',... % 'autoscalefactor',args{nargs}}; % else % pvpairs = {pvpairs{:},'autoscale','off'}; % end % nargs = nargs - 1; % end % x = []; % y = []; % u = []; % v = []; % if (nargs == 2) % u = datachk(args{1}); % v = datachk(args{2}); % pvpairs = {pvpairs{:},'udata',u,'vdata',v}; % elseif (nargs == 4) % x = datachk(args{1}); % y = datachk(args{2}); % u = datachk(args{3}); % v = datachk(args{4}); % pvpairs = {pvpairs{:},'xdata',x,'ydata',y,'udata',u,'vdata',v}; % end % % if isempty(x) % % Deal with quiver(U,V) syntax % if ~isempty(u) % if ~isequal(size(u),size(v)) % msg.identifier = id('UVSizeMismatch'); % msg.message = 'U and V must be the same size.'; % end % end % else % % Deal with quiver(X,Y,U,V) syntax. % if ~isvector(u) % msg = xyzcheck(x,y,u,'U'); % else % % If all four are vectors, xyzcheck is not used as it assumes the % % third argument should be a matrix. % if ~isequal(size(u),size(v)) % msg.identifier = id('UVSizeMismatch'); % msg.message = 'U and V must be the same size.'; % elseif ~isequal(size(y),size(u)); % msg.identifier = id('YUSizeMismatch'); % msg.message = 'The size of Y must match the size of U or the number of rows of U.'; % elseif ~isequal(size(x),size(u)); % msg.identifier = id('XUSizeMismatch'); % msg.message = 'The size of X must match the size of U or the number of columns of U.'; % end % end % if isempty(msg) && ~isequal(size(u),size(v)) % msg = []; % msg.identifier = id('UVSizeMismatch'); % msg.message = 'U and V must be the same size.'; % end % end function str=id(str) str = ['MATLAB:quiver:' str];
github
Jann5s/BasicGDIC-master
rescompute.m
.m
BasicGDIC-master/lib_bgdic/rescompute.m
5,171
utf_8
a56cc7d2f385f0c6e029915a8ecefb39
% ================================================== function [] = rescompute(varargin) % compute result fields H = varargin{3}; S = guihandles(H); D = guidata(H); % if D.usegpu % D.gpu = gpuDevice; % guidata(H,D); % end if ~isfield(D,'files') return; end if ~isfield(D,'cor') return; end % get the popupmenu values str = get(S.resstraindef,'String'); straindef = str{get(S.resstraindef,'Value')}; % quiver positions Ncg = 4; Ninc = length(D.cor); for inc = 1:Ninc if D.cor(inc).done ~= Ncg; continue end dx = mean(diff(D.cor(inc).xroi)); dy = mean(diff(D.cor(inc).yroi)); % get data to cpu (if using gpu) U1 = gather(D.cor(inc).U1); U2 = gather(D.cor(inc).U2); % use the mask to set some NaN's Imask = D.cor(inc).Imask; U1(Imask) = NaN; U2(Imask) = NaN; % deformation gradient tensor [Fxx, Fxy] = gradient(U1,dx,dy); [Fyx, Fyy] = gradient(U2,dx,dy); Fxx = Fxx + 1; Fyy = Fyy + 1; [n, m] = size(Fxx); ZERO = zeros(n,m,'int8'); % Cauchy Green deformation tensor Cxx = Fxx .* Fxx + Fyx .* Fyx; Cxy = Fxx .* Fxy + Fyx .* Fyy; Cyx = Fyy .* Fyx + Fxy .* Fxx; Cyy = Fyy .* Fyy + Fxy .* Fxy; % Finger deformation tensor Bxx = Fxx .* Fxx + Fxy .* Fxy; Bxy = Fxx .* Fyx + Fxy .* Fyy; Byx = Fyx .* Fxx + Fyy .* Fxy; Byy = Fyx .* Fyx + Fyy .* Fyy; if strcmp(straindef,'none') % Do not compute strain Exx = ZERO; Eyy = ZERO; Exy = ZERO; Eyx = ZERO; elseif strcmp(straindef,'membrane strain') % Membrane Strain % assuming flat initial situation [X, Y] = meshgrid(D.cor(inc).xroi,D.cor(inc).yroi); [n, m] = size(X); Z = zeros(n,m); if ~isfield(D.cor(inc),'U3') || isempty(D.cor(inc).U3) U3 = Z; else U3 = gather(D.cor(inc).U3); end U3(Imask) = NaN; [dXx, dXy] = gradient(X+U1,dx,dy); [dYx, dYy] = gradient(Y+U2,dx,dy); [dZx, dZy] = gradient(Z+U3,dx,dy); % this strain definition works for stretched membranes, but is far from % universal, test, check, and verify, before using. Exx = hypot(dXx,dZx) - 1; Eyy = hypot(dYy,dZy) - 1; Exy = hypot(dXy,dZx); Eyx = hypot(dYx,dZy); elseif strcmp(straindef,'small strain') Exx = Fxx - 1; Eyy = Fyy - 1; Exy = 0.5*(Fxy + Fyx); Eyx = 0.5*(Fxy + Fyx); elseif strcmp(straindef,'logarithmic strain') C = {Cxx,Cxy;Cyx,Cyy}; [v, d] = eig2d(C); Exx = log(sqrt(d{1})) .* v{1,1} .* v{1,1} ... + log(sqrt(d{2})) .* v{2,1} .* v{2,1} ; Exy = log(sqrt(d{1})) .* v{1,1} .* v{1,2} ... + log(sqrt(d{2})) .* v{2,1} .* v{2,2} ; Eyx = log(sqrt(d{1})) .* v{1,2} .* v{1,1} ... + log(sqrt(d{2})) .* v{2,2} .* v{2,1} ; Eyy = log(sqrt(d{1})) .* v{1,2} .* v{1,2} ... + log(sqrt(d{2})) .* v{2,2} .* v{2,2} ; elseif strcmp(straindef,'Green-Lagrange strain') % Green Lagrange Strain tensor Exx = 0.5 * (Cxx - 1); Exy = 0.5 * (Cxy); Eyx = 0.5 * (Cyx); Eyy = 0.5 * (Cyy - 1); elseif strcmp(straindef,'Euler-Almansi strain') B = {Bxx,Bxy;Byx,Byy}; [v, d] = eig2d(B); Exx = (1./d{1}) .* v{1,1} .* v{1,1} ... + (1./d{2}) .* v{2,1} .* v{2,1} ; Exy = (1./d{1}) .* v{1,1} .* v{1,2} ... + (1./d{2}) .* v{2,1} .* v{2,2} ; Eyx = (1./d{1}) .* v{1,2} .* v{1,1} ... + (1./d{2}) .* v{2,2} .* v{2,1} ; Eyy = (1./d{1}) .* v{1,2} .* v{1,2} ... + (1./d{2}) .* v{2,2} .* v{2,2} ; Exx = 0.5*(1-Exx); Exy = 0.5*(0-Exy); Eyx = 0.5*(0-Eyx); Eyy = 0.5*(1-Eyy); end if ~strcmp(straindef,'none') % major and minor strain E = {Exx,Exy;Eyx,Eyy}; [v, d] = eig2d(E); Q11 = v{1,1}; Q12 = v{1,2}; Q21 = v{2,1}; Q22 = v{2,2}; Emin = d{1,1}; Emaj = d{2,1}; Eeq = sqrt(Emin.^2 + Emaj.^2); else Emaj = ZERO; Emin = ZERO; Eeq = ZERO; Q11 = ZERO; Q12 = ZERO; Q21 = ZERO; Q22 = ZERO; end % use the mask to set some NaN's Imask = D.cor(inc).Imask; Exx(Imask) = NaN; Eyy(Imask) = NaN; Exy(Imask) = NaN; Eyx(Imask) = NaN; Emaj(Imask) = NaN; Emin(Imask) = NaN; Eeq(Imask) = NaN; res(inc).Exx = Exx; res(inc).Eyy = Eyy; res(inc).Exy = Exy; res(inc).Eyx = Eyx; res(inc).Emaj = Emaj; res(inc).Emin = Emin; res(inc).Eeq = Eeq; res(inc).Q11 = Q11; res(inc).Q12 = Q12; res(inc).Q21 = Q21; res(inc).Q22 = Q22; % update status stat = sprintf('[8] Results recomputed for increment %d',inc); D.gui.stat = appendstatus(D.gui.stat,stat); bcwaitbar(H,inc/Ninc,sprintf('computing strain (%d/%d)',inc,Ninc)); end D.res = res; % update the application data guidata(H,D); bcwaitbar(H);
github
Jann5s/BasicGDIC-master
ginputjn.m
.m
BasicGDIC-master/lib_bgdic/ginputjn.m
9,140
utf_8
c4d5714f00e7e828e17f2cd9602967ee
function [out1,out2,out3] = ginputjn(arg1) %GINPUT Graphical input from mouse. % [X,Y] = GINPUT(N) gets N points from the current axes and returns % the X- and Y-coordinates in length N vectors X and Y. The cursor % can be positioned using a mouse. Data points are entered by pressing % a mouse button or any key on the keyboard except carriage return, % which terminates the input before N points are entered. % % [X,Y] = GINPUT gathers an unlimited number of points until the % return key is pressed. % % [X,Y,BUTTON] = GINPUT(N) returns a third result, BUTTON, that % contains a vector of integers specifying which mouse button was % used (1,2,3 from left) or ASCII numbers if a key on the keyboard % was used. % % Examples: % [x,y] = ginput; % % [x,y] = ginput(5); % % [x, y, button] = ginput(1); % % See also GTEXT, WAITFORBUTTONPRESS. % Copyright 1984-2011 The MathWorks, Inc. % $Revision: 5.32.4.18 $ $Date: 2011/05/17 02:35:09 $ out1 = []; out2 = []; out3 = []; y = []; c = computer; if ~strcmp(c(1:2),'PC') tp = get(0,'TerminalProtocol'); else tp = 'micro'; end if ~strcmp(tp,'none') && ~strcmp(tp,'x') && ~strcmp(tp,'micro'), if nargout == 1, if nargin == 1, out1 = trmginput(arg1); else out1 = trmginput; end elseif nargout == 2 || nargout == 0, if nargin == 1, [out1,out2] = trmginput(arg1); else [out1,out2] = trmginput; end if nargout == 0 out1 = [ out1 out2 ]; end elseif nargout == 3, if nargin == 1, [out1,out2,out3] = trmginput(arg1); else [out1,out2,out3] = trmginput; end end else fig = gcf; figure(gcf); if nargin == 0 how_many = -1; b = []; else how_many = arg1; b = []; if ischar(how_many) ... || size(how_many,1) ~= 1 || size(how_many,2) ~= 1 ... || ~(fix(how_many) == how_many) ... || how_many < 0 error(message('MATLAB:ginput:NeedPositiveInt')) end if how_many == 0 % If input argument is equal to zero points, % give a warning and return empty for the outputs. warning (message('MATLAB:ginput:InputArgumentZero')); end end % Setup the figure to disable interactive modes and activate pointers. initialState = setupFcn(fig); % onCleanup object to restore everything to original state in event of % completion, closing of figure errors or ctrl+c. c = onCleanup(@() restoreFcn(initialState)); % We need to pump the event queue on unix % before calling WAITFORBUTTONPRESS drawnow char = 0; while how_many ~= 0 % Use no-side effect WAITFORBUTTONPRESS waserr = 0; try keydown = wfbp; catch %#ok<CTCH> waserr = 1; end if(waserr == 1) if(ishghandle(fig)) cleanup(c); error(message('MATLAB:ginput:Interrupted')); else cleanup(c); error(message('MATLAB:ginput:FigureDeletionPause')); end end % g467403 - ginput failed to discern clicks/keypresses on the figure it was % registered to operate on and any other open figures whose handle % visibility were set to off figchildren = allchild(0); if ~isempty(figchildren) ptr_fig = figchildren(1); else error(message('MATLAB:ginput:FigureUnavailable')); end % old code -> ptr_fig = get(0,'CurrentFigure'); Fails when the % clicked figure has handlevisibility set to callback if(ptr_fig == fig) if keydown char = get(fig, 'CurrentCharacter'); button = abs(get(fig, 'CurrentCharacter')); else button = get(fig, 'SelectionType'); if strcmp(button,'open') button = 1; elseif strcmp(button,'normal') button = 1; elseif strcmp(button,'extend') button = 2; elseif strcmp(button,'alt') button = 3; else error(message('MATLAB:ginput:InvalidSelection')) end end axes_handle = gca; drawnow; pt = get(axes_handle, 'CurrentPoint'); how_many = how_many - 1; if(char == 13) % & how_many ~= 0) % if the return key was pressed, char will == 13, % and that's our signal to break out of here whether % or not we have collected all the requested data % points. % If this was an early breakout, don't include % the <Return> key info in the return arrays. % We will no longer count it if it's the last input. break; end out1 = [out1;pt(1,1)]; %#ok<AGROW> y = [y;pt(1,2)]; %#ok<AGROW> b = [b;button]; %#ok<AGROW> end end % Cleanup and Restore cleanup(c); if nargout > 1 out2 = y; if nargout > 2 out3 = b; end else out1 = [out1 y]; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = wfbp %WFBP Replacement for WAITFORBUTTONPRESS that has no side effects. fig = gcf; current_char = []; %#ok<NASGU> % Now wait for that buttonpress, and check for error conditions waserr = 0; try h=findall(fig,'Type','uimenu','Accelerator','C'); % Disabling ^C for edit menu so the only ^C is for set(h,'Accelerator',''); % interrupting the function. keydown = waitforbuttonpress; current_char = double(get(fig,'CurrentCharacter')); % Capturing the character. if~isempty(current_char) && (keydown == 1) % If the character was generated by the if(current_char == 3) % current keypress AND is ^C, set 'waserr'to 1 waserr = 1; % so that it errors out. end end set(h,'Accelerator','C'); % Set back the accelerator for edit menu. catch %#ok<CTCH> waserr = 1; end drawnow; if(waserr == 1) set(h,'Accelerator','C'); % Set back the accelerator if it errored out. error(message('MATLAB:ginput:Interrupted')); end if nargout>0, key = keydown; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end function initialState = setupFcn(fig) % Store Figure Handle. initialState.figureHandle = fig; % Suspend figure functions initialState.uisuspendState = uisuspend(fig); % Disable Plottools Buttons initialState.toolbar = findobj(allchild(fig),'flat','Type','uitoolbar'); if ~isempty(initialState.toolbar) initialState.ptButtons = [uigettool(initialState.toolbar,'Plottools.PlottoolsOff'), ... uigettool(initialState.toolbar,'Plottools.PlottoolsOn')]; initialState.ptState = get (initialState.ptButtons,'Enable'); set (initialState.ptButtons,'Enable','off'); end % Setup FullCrosshair Pointer without warning. oldwarnstate = warning('off', 'MATLAB:hg:Figure:Pointer'); % set(fig,'Pointer','fullcrosshair'); % set(fig,'Pointer','cross'); % set(fig,'Pointer','crosshair'); % set(fig,'Pointer','circle'); % custom Pointer P = nan(16,16); xc = 8; yc = 8; % white horizontal bars P(yc,[1:5, 11:15]) = 2; P([1:5, 11:15],xc) = 2; % black diagonal bars P([1 15],[1 15]) = 1; P([2 14],[2 14]) = 1; P([3 13],[3 13]) = 1; P([4 12],[4 12]) = 1; P([5 11],[5 11]) = 1; % corners P([2 14],[1 15]) = 1; P([1 15],[2 14]) = 1; P([yc-2 yc-1 yc+1 yc+2],[1 15]) = 2; P([1 15],[xc-2 xc-1 xc+1 xc+2]) = 2; % remove extra (even row and col) P(16,:) = NaN; P(:,16) = NaN; set(fig,'Pointer','custom','PointerShapeCData',P,'PointerShapeHotSpot',[xc yc]); warning(oldwarnstate); % Adding this to enable automatic updating of currentpoint on the figure set(fig,'WindowButtonMotionFcn',@(o,e) dummy()); % Get the initial Figure Units initialState.fig_units = get(fig,'Units'); end function restoreFcn(initialState) if ishghandle(initialState.figureHandle) % Figure Units set(initialState.figureHandle,'Units',initialState.fig_units); set(initialState.figureHandle,'WindowButtonMotionFcn',''); % Plottools Icons if ~isempty(initialState.toolbar) && ~isempty(initialState.ptButtons) set (initialState.ptButtons(1),'Enable',initialState.ptState{1}); set (initialState.ptButtons(2),'Enable',initialState.ptState{2}); end % UISUSPEND uirestore(initialState.uisuspendState); end end function dummy() % do nothing, this is there to update the GINPUT WindowButtonMotionFcn. end function cleanup(c) if isvalid(c) delete(c); end end
github
Jann5s/BasicGDIC-master
plotbasis.m
.m
BasicGDIC-master/lib_bgdic/plotbasis.m
7,256
utf_8
2fbccbed4c74578ab8112fdcaa2777b7
% ================================================== function [] = plotbasis(varargin) % plot the current basis H = varargin{3}; S = guihandles(H); D = guidata(H); if isfield(D,'outputfile') % headless mode return end % test if there are images if ~isfield(D,'files') return; end % Region of interest if ~isfield(D,'roi') return; end roi = D.roi; % Region of interest k = get(S.basislist,'Value'); if isfield(D,'basis') && (length(D.basis) >= k) && ~isempty(D.basis(k).name) && isfield(D.basis,'plotphi') && ~isempty(D.basis(k).plotphi) basis = D.basis(k); else return; end soften = get(S.basissoftenslider,'Value'); soften = round(soften*100)/100; set(S.basissoftenslider,'Value',soften); set(S.basissoften,'String',num2str(soften)); alpha = get(S.basisalphaslider,'Value'); alpha = round(alpha*100)/100; set(S.basisalphaslider,'Value',alpha); set(S.basisalpha,'String',num2str(alpha)); % get current basis function (i.e. slider position) id = str2double(get(S.phiid,'String')); n = D.files(1).size(1); m = D.files(1).size(2); x = 1:m; y = 1:n; Img = D.files(1).image; xlim = [1 m]; ylim = [1 n]; % Plot the background image % ============================================= hi = findobj(H,'Tag','basis_image'); if isempty(hi) % color scale Img = 255*(Img - min(Img(:))) / (max(Img(:)) - min(Img(:))); RGB(:,:,1) = uint8(soften*Img);%+(1-soften)*255; RGB(:,:,2) = uint8(soften*Img);%+(1-soften)*255; RGB(:,:,3) = uint8(soften*Img);%+(1-soften)*255; % plot image set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes4) set(gca,'NextPlot','replacechildren') imagesc(x,y,RGB,'Parent',S.axes4,'Tag','basis_image'); xlabel('x [px]') ylabel('y [px]') set(gca,'ydir','reverse') set(gca,'xlim',xlim) set(gca,'ylim',ylim) daspect([1 1 1 ]) else Img = 255*(Img - min(Img(:))) / (max(Img(:)) - min(Img(:))); RGB(:,:,1) = uint8(soften*Img);%+(1-soften)*255; RGB(:,:,2) = uint8(soften*Img);%+(1-soften)*255; RGB(:,:,3) = uint8(soften*Img);%+(1-soften)*255; set(hi,'CData',RGB); end [X, Y] = meshgrid(basis.plotx,basis.ploty); Iroi = find(X >= roi(1) & X <= roi(2) & Y >= roi(3) & Y <= roi(4)); % plot overlay % =============================== plotn = length(basis.ploty); plotm = length(basis.plotx); P = reshape(basis.plotphi(:,id),plotn,plotm); plim(1) = min(P(~isnan(P))); plim(2) = max(P(~isnan(P))); if plim(1) == plim(2); if plim(1) == 0 plim = [-0.01, 0.01]; elseif plim(1) == 1 plim = [0, 1]; else plim = plim(1) + 0.01*[-plim(1), plim(1)]; end end set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes4) hi = findobj(H,'Tag','basis_overlay'); if isempty(hi) colormap(D.gui.color.cmapoverlay) set(gca,'NextPlot','add') imagesc(basis.plotx,basis.ploty,P,'Parent',S.axes4,'AlphaData',alpha,'Tag','basis_overlay'); colorbar; hc = colorbar; set(hc,'Xcolor',[0 0 0],'Ycolor',[0 0 0],'FontSize',D.gui.fontsize(3)) else set(hi,'CData',P,'XData',basis.plotx([1,end]),'YData',basis.ploty([1,end]),'AlphaData',alpha); end % corner text Nphi = basis.Nphi; str = sprintf('%s, %d/%d',basis.name,id,Nphi); hi = findobj(H,'Tag','basis_text'); if isempty(hi) ht = text(0.02,0.02,str,'units','normalized','Tag','basis_text'); set(ht,'color',D.gui.color.fg) set(ht,'FontSize',D.gui.fontsize(4)) set(ht,'FontWeight','bold') else set(hi,'String',str); end title(str) % plot mesh % =============================== set(gca,'NextPlot','add') if strcmp(basis.type,'bspline') % If mesh type is B-spline % set the color limits clim(1) = 0; clim(2) = 1; [X, Y] = meshgrid(basis.xknot,basis.yknot); % create the connectivity Nn = numel(X); [n,m] = size(X); Ne = (n-1)*(m-1); In = reshape(1:Nn,n,m); Ie = reshape(1:Ne,n-1,m-1); conn = zeros(Ne,4); for ki = 1:n-1 for kj = 1:m-1 ke = Ie(ki,kj); con = In(ki:ki+1,kj:kj+1); conn(ke,:) = con([1 2 4 3]); end end FV.Vertices = [X(:),Y(:)]; FV.Faces = conn; hi = findobj(H,'Tag','basis_mesh'); if isempty(hi) patch(FV,'FaceColor','none','EdgeColor','k','LineWidth',0.5,'Marker','.','Tag','basis_mesh'); else set(hi,'EdgeColor','k','FaceColor','none','Vertices',FV.Vertices,'Faces',FV.Faces,'Marker','.'); end elseif strcmp(basis.type,'zernike') % set the color limits clim = plim; % plot the zernike circle w = roi(2)-roi(1); h = roi(4)-roi(3); R = 0.5*sqrt(w^2 + h^2); xc = mean(roi(1:2)); yc = mean(roi(3:4)); tz = linspace(0,2*pi,60); X = R*cos(tz) + xc; Y = R*sin(tz) + yc; FV.Vertices = [X(:),Y(:)]; FV.Faces = 1:60; hi = findobj(H,'Tag','basis_mesh'); if isempty(hi) patch(FV,'FaceColor','none','EdgeColor','k','LineWidth',0.5,'Marker','none','Tag','basis_mesh'); else set(hi,'EdgeColor','k','FaceColor','none','Vertices',FV.Vertices,'Faces',FV.Faces,'Marker','None'); end % corner text Zp = id - 1; Zn = floor(sqrt(Zp)); % Pseudo Zernike Zm = Zp - Zn.^2 - Zn; % Pseudo Zernike % Zn = ceil((-3+sqrt(9+8*Zp))/2); % Zernike % Zm = 2*Zp - Zn.*(Zn+2); % Zernike str = sprintf('n = %d, m = %d',Zn,Zm); hi = findobj(H,'Tag','basis_text'); str = [get(hi,'String') ' -- ' str]; set(hi,'String',str); elseif strcmp(basis.type,'FEM-T') % If mesh type is FEM-T FV.Vertices = basis.coordinates; FV.Faces = basis.connectivity; order = basis.order; clim = [0,1]; if order == 2 clim = [-2/8,1]; Ipatch = [1 4 2 5 3 6]; FV.Faces = FV.Faces(:,Ipatch); end hi = findobj(H,'Tag','basis_mesh'); if isempty(hi) patch(FV,'FaceColor','none','EdgeColor','k','LineWidth',0.5,'Marker','s','Tag','basis_mesh'); else set(hi,'EdgeColor','k','FaceColor','none','Vertices',FV.Vertices,'Faces',FV.Faces,'Marker','s'); end elseif strcmp(basis.type,'FEM-Q') % If mesh type is FEM-Q FV.Vertices = basis.coordinates; FV.Faces = basis.connectivity; order = basis.order; clim = [0,1]; if order == 2 clim = [-2/8,1]; Ipatch = [1 5 2 6 3 7 4 8]; FV.Faces = FV.Faces(:,Ipatch); end hi = findobj(H,'Tag','basis_mesh'); if isempty(hi) patch(FV,'FaceColor','none','EdgeColor','k','LineWidth',0.5,'Marker','s','Tag','basis_mesh'); else set(hi,'EdgeColor','k','FaceColor','none','Vertices',FV.Vertices,'Faces',FV.Faces,'Marker','s'); end else clim = [-1,1]; % hide the mesh hi = findobj(H,'Tag','basis_mesh'); if ~isempty(hi) set(hi,'EdgeColor','none','Marker','none'); end end % plot the evaluation area roi = D.roi; X = [roi(1) roi(2) roi(2) roi(1)]; Y = [roi(3) roi(3) roi(4) roi(4)]; FV.Vertices = [X(:),Y(:)]; FV.Faces = 1:4; set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes4) hi = findobj(H,'Tag','basis_roi'); if isempty(hi) patch(FV,'FaceColor','none','FaceColor','none','EdgeColor','k','LineWidth',0.5,'Marker','none','Tag','basis_roi'); else set(hi,'Vertices',FV.Vertices,'Faces',FV.Faces,'Marker','none'); end caxis(clim); drawnow
github
Jann5s/BasicGDIC-master
bcwaitbar.m
.m
BasicGDIC-master/lib_bgdic/bcwaitbar.m
1,348
utf_8
bd2b5f811191b0c8d3be69f2b75037da
% ================================================== function [] = bcwaitbar(H,varargin) % Button Callback: update the waitbar % bcwaitbar(H,A) % H = gui handle % A = relative part of the waitbar which is full S = guihandles(H); D = guidata(H); if isfield(D,'outputfile') % headless mode, don't plot anything return end C1 = D.gui.color.waitbar1; C2 = D.gui.color.waitbar2; % get patch handle hp = findobj(S.waitbar,'Type','patch'); if ~isempty(hp) delete(hp) end % get text handle ht = findobj(S.waitbar,'Type','text'); if nargin == 1 % only H is specified, clear the wait bar if ~isempty(ht) delete(ht) end end if nargin >= 2 % H and A are specified, update the waitbar to show the status A = varargin{1}; A = max([0 A]); A = min([1 A]); set(0,'CurrentFigure',H); set(H,'CurrentAxes',S.waitbar); C(1,1,:) = C1; C(1,2,:) = C2; X = [0 A;A 1;A 1;0 A]; Y = [0 0;0 0;1 1;1 1]; patch(X,Y,C,'edgecolor','none'); % put the text back on top uistack(ht,'top'); end if nargin == 3 % replace the text if ~isempty(ht) delete(ht) end txt = varargin{2}; ht = text(0.05,0.55,txt,'units','normalized'); set(ht,'Fontsize',D.gui.fontsize(3)) set(ht,'VerticalAlignment','Middle') set(ht,'HorizontalAlignment','Left') end drawnow;
github
Jann5s/BasicGDIC-master
pateval.m
.m
BasicGDIC-master/lib_bgdic/pateval.m
4,783
utf_8
0ebe529ab37f1b92d3b5e2da8779839a
% ================================================== function [] = pateval(varargin) % Button Callback: Evaluate the pattern H = varargin{3}; S = guihandles(H); D = guidata(H); if ~isfield(D,'files') msgstr = {'This action requires loaded images,';'load images in section 1'}; msgdlgjn(msgstr,dlgposition(H)); return; end % load previous pattern evaluations if isfield(D,'pateval'); pateval = D.pateval; else pateval = []; end % disable gui controls set(D.gui.waithandles,'Enable','off');drawnow % update status D.gui.stat = appendstatus(D.gui.stat,'[2] Pattern evaluation started'); % get current frame id = str2double(get(S.patid,'String')); % get the image A = D.files(id).image; [n, m] = size(A); x = 1:m; y = 1:n; [X, Y] = meshgrid(x,y); % set the pattern if D.gui.activepatview ~= 1 set(S.patshowpat,'BackgroundColor',D.gui.color.hl); set(S.patshowACF,'BackgroundColor',D.gui.color.bg); plotpattern(H); D.gui.activepatview = 1; end % Select an area set(S.patshowpat,'BackgroundColor',D.gui.color.hl); set(S.patshowACF,'BackgroundColor',D.gui.color.bg); set(H,'CurrentAxes',S.axes2) h = title('position the rectangle, confirm with a doubleclick'); set(h,'color',D.gui.color.axeshl); % reuse rectangle if isfield(pateval,'box') box = pateval(1).box; rect = [box(1),box(3) ; box(2),box(4)]; elseif isfield(D,'roi') rect = [D.roi(1),D.roi(3) ; D.roi(2),D.roi(4)]; else rect = [0.1*m,0.1*n ; 0.9*m,0.9*n]; end % load interactive rectangle tool position = selectarea(rect); % reset the title set(h,'color','k'); title(''); box(1) = min(position(:,1)); box(2) = max(position(:,1)); box(3) = min(position(:,2)); box(4) = max(position(:,2)); pateval(1).box = box; % Crop the image xlim = [ceil(box(1)) floor(box(2))]; ylim = [ceil(box(3)) floor(box(4))]; A = A(ylim(1):ylim(2),xlim(1):xlim(2)); X = X(ylim(1):ylim(2),xlim(1):xlim(2)); Y = Y(ylim(1):ylim(2),xlim(1):xlim(2)); [n, m] = size(A); % compute scalar measures imrms = sqrt(mean((A(:).^2))); imstd = std(A(:)); imrange = max(A(:)) - min(A(:)); immean = mean(A(:)); acfthreshold = 0.5;%1/exp(1); [zeta, theta, acf] = correlationlength2d(A,acfthreshold); % fourier filter fourierorder = 10; [four, zeta] = fourier(theta,zeta,fourierorder); [zetalim(1,1), I] = min(zeta); zetalim(2,1) = theta(I); [zetalim(1,2), I] = max(zeta); zetalim(2,2) = theta(I); % ZOI auto correlation function (normalized) % ============================= % number of subsets (Nsub x Nsub) Nsub = D.gui.ini.patnumfacet.value; % subset edge indices In = round(linspace(1,n,Nsub+1)); Im = round(linspace(1,m,Nsub+1)); % subset edge locations subsetedge.X = X(1,Im); subsetedge.Y = Y(In,1)'; % evaluate each subset Z = zeros(60,Nsub*Nsub); T = zeros(60,Nsub*Nsub); cnt = 0; bcwaitbar(H); for kn = 1:Nsub for km = 1:Nsub cnt = cnt + 1; % get subset image Asub = A(In(kn):In(kn+1),Im(km):Im(km+1)); Xsub = X(In(kn):In(kn+1),Im(km):Im(km+1)); Ysub = Y(In(kn):In(kn+1),Im(km):Im(km+1)); % get correlation contour [Z(:,cnt), T(:,cnt)] = correlationlength2d(Asub,acfthreshold); % fourier filter [four, Z(:,cnt)] = fourier(T(:,cnt),Z(:,cnt),fourierorder); % store subset data subset.xc(cnt) = mean(Xsub(1,:)); subset.yc(cnt) = mean(Ysub(:,1)); subset.zeta(cnt) = mean(Z(:,cnt)); subset.std(cnt) = std(Asub(:)); subset.mean(cnt) = mean(Asub(:)); end bcwaitbar(H,cnt/(Nsub*Nsub)); end subset.Z = Z; subset.T = T; % store evaluation results to data structure pateval(id).acf = acf.A; pateval(id).ux = acf.x; pateval(id).uy = acf.x; pateval(id).xlim = xlim; pateval(id).ylim = ylim; pateval(id).position = position; pateval(id).imrms = imrms; pateval(id).imstd = imstd; pateval(id).imrange = imrange; pateval(id).immean = immean; pateval(id).zeta = zeta; pateval(id).theta = theta; pateval(id).zetamean = mean(zeta); pateval(id).zetalim = zetalim; pateval(id).subset = subset; pateval(id).subsetedge = subsetedge; D.pateval = pateval; % update info info(1).str = 'image rms'; info(1).val = imrms; info(2).str = 'image std'; info(2).val = imstd; info(3).str = 'image mean'; info(3).val = immean; info(4).str = 'image range'; info(4).val = imrange; info(5).str = 'avg. zeta'; info(5).val = mean(zeta); info(6).str = 'min. zeta'; info(6).val = zetalim(1,1); info(7).str = 'max. zeta'; info(7).val = zetalim(1,2); D.gui.info = appendinfo(D.gui.info,info); % set section indicator on set(S.secind2,'BackgroundColor',D.gui.color.on) set(D.gui.waithandles,'Enable','on');drawnow % update status D.gui.stat = appendstatus(D.gui.stat,'[2] Pattern evaluation done'); bcwaitbar(H); % update the application data guidata(H,D); plotpattern(H);
github
Jann5s/BasicGDIC-master
inputdlgjn.m
.m
BasicGDIC-master/lib_bgdic/inputdlgjn.m
3,028
utf_8
e01c55ac10d34f02181b98bcb50499f3
function Answer=inputdlgjn(Prompt, Title, NumLines, DefAns, Position) % function similar to inputdlg, except simpler and with the option to % position it. fontsize = 12; N = length(Prompt); M = max(cellfun('length',Prompt)); Figheight = N*2.0*fontsize + 6*fontsize + 2.5*fontsize; Figwidth = M*1*fontsize + 10*1*fontsize + 2.5*fontsize; Figpos(3:4) = [Figwidth Figheight]; Figpos(1:2) = Position - 0.5*Figpos(3:4); FigColor=get(0,'DefaultUicontrolBackgroundColor'); WindowStyle='modal'; Interpreter='none'; Resize = 'off'; H = dialog( ... 'Visible' ,'on' , ... 'Name' ,Title , ... 'Pointer' ,'arrow' , ... 'Units' ,'pixels' , ... 'UserData' ,'Cancel' , ... 'Tag' ,Title , ... 'HandleVisibility' ,'callback' , ... 'Color' ,FigColor , ... 'NextPlot' ,'add' , ... 'WindowStyle' ,WindowStyle, ... 'Resize' ,Resize, ... 'Position' ,Figpos ... ); xpos = linspace(0.03,0.98,3); ypos = linspace(0.18,0.75,N+1); height = 0.98*mean(diff(ypos)); width = 0.9*mean(diff(xpos)); % Create title uicontrol('String',Title,... 'Style','text',... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',[xpos(1) ypos(end)+0.02 xpos(end)-xpos(1) 1-(ypos(end)+0.02)],... 'FontSize',fontsize,... 'Parent',H); % Create the input boxes for k = 1:N uicontrol('String',Prompt{k},... 'Style','text',... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[xpos(1) ypos(1+N-k) width height],... 'FontSize',fontsize,... 'Parent',H); h(k) = uicontrol('String',DefAns{k},... 'Style','edit',... 'BackgroundColor','w',... 'units','normalized',... 'Position',[xpos(2) ypos(1+N-k) width height],... 'FontSize',fontsize,... 'Parent',H); end uicontrol('String','Ok',... 'ToolTipString','confirm input',... 'Style','pushbutton',... 'units','normalized',... 'Position',[xpos(1) 0.02 width height],... 'FontSize',fontsize,... 'Parent',H,... 'call',{@pressOk,H,h}); uicontrol('String','Cancel',... 'ToolTipString','cancel input',... 'Style','pushbutton',... 'units','normalized',... 'Position',[xpos(2) 0.02 width height],... 'FontSize',fontsize,... 'Parent',H,... 'call',{@pressCancel,H,h}); set(H,'KeyPressFcn',{@doFigureKeyPress,H,h}) uiwait(H) if ishandle(H) Answer = guidata(H); delete(H); else Answer = []; end function doFigureKeyPress(obj, evd, H ,h) %#ok switch(evd.Key) case {'return','space'} pressOk([],[],H,h); case {'escape'} pressCancel([],[],H,h); end function pressOk(varargin) H = varargin{3}; h = varargin{4}; for k = 1:length(h) answer{k} = get(h(k),'String'); end guidata(H,answer); uiresume(H); function pressCancel(varargin) H = varargin{3}; answer=[]; guidata(H,answer); uiresume(H);
github
Jann5s/BasicGDIC-master
buildphi_legendre.m
.m
BasicGDIC-master/lib_bgdic/buildphi_legendre.m
4,414
utf_8
8a9ef7c76a829963ab23f166e409ff97
function phi = buildphi_legendre(x,y,phi_list,roi,varargin) %BUILDPHI_LEGENDRE creates the basis function matrix phi, which has one % row for each pixel and one column for each basis function. The created % 2D basis functions are based on the Legendre polynomials by % Adrien-Marie Legendre. % % phi = buildphi_legendre(x,y,phi_list,roi,phi_list) % % INPUTS: % n,m : the image dimentions of the ROI, the shape functions will % be cacluated on a domain -1 <= x,y < 1 with n steps in y % direction and m steps in x direction % phi_list : a list of basis functions of size (N x 3) where N is the % number of basis functions and each row contains the three % parameters, [a b c], where [a b] are the polynomial orders: % P = (x^a)*(y^b), and [c] is the direction in which the basis % function is applied, 1=x, 2=y, and 3=z. % % OPTIONAL INPUTS: % phi = buildphi_legendre(x,y,phi_list,roi,'single') % By default BUILDPHI_LEGENDRE uses double precision floating point % values for the the phi matrix, however when running into memory issues % it is possible to use singe precision, nevertheless this will % influence the DIC accuracy greatly and is not recommended. % % OUTPUT: % The basis function matrix is split into a parts according to the % application direction, i.e. phi.x, phi.y, phi.z. In other words, this % function returns a structure with one matrix per dimension. % % EXAMPLE: % roi = [-5 5 -4 4]; % [n m] = deal(120,150); % phi_list(1,:) = [0 0 1]; % x-translation % phi_list(2,:) = [0 0 2]; % y-translation % phi_list(3,:) = [0 0 3]; % z-translation % phi_list(4,:) = [0 1 1]; % strain-xx % phi_list(5,:) = [0 1 2]; % shear-xy % phi_list(6,:) = [0 1 3]; % tilt around y-axis % phi_list(7,:) = [1 0 1]; % shear-yx % phi_list(8,:) = [1 0 2]; % strain-yy % phi_list(9,:) = [1 0 3]; % tilt around x-axis % phi = buildphi_legendre(x,y,phi_list,roi); % phiplot(x,y,phi); % % See also JNDIC, PHIPLOT, BUILDPHI_POLY, BUILDPHI_CHEBYSHEV, % BUILDPHI_FEMT3. % %copyright: Jan Neggers, 2013 precision = 'double'; if nargin == 5 if strcmpi(varargin{1},'single') precision = 'single'; elseif strcmpi(varargin{1},'double') precision = 'double'; else error('buildphi_legendre: unknown precision options') end end if length(roi) == 1 roi = [min(x)+roi max(x)-roi min(y)+roi max(y)-roi]; end Im = find(x < roi(1) | x > roi(2)); In = find(y < roi(3) | y > roi(4)); % create a space x = 2*(x - 0.5*(roi(1)+roi(2))) / (roi(2) - roi(1)); y = 2*(y - 0.5*(roi(3)+roi(4))) / (roi(4) - roi(3)); m = length(x); n = length(y); % number of shape functions N = size(phi_list,1); % split list into directions listx = phi_list(phi_list(:,3)==1,:); listy = phi_list(phi_list(:,3)==2,:); listz = phi_list(phi_list(:,3)==3,:); % number of DOF per direction Nx = size(listx,1); Ny = size(listy,1); Nz = size(listz,1); % initiate matrices phi.x = zeros(n*m,Nx,precision); phi.y = zeros(n*m,Ny,precision); phi.z = zeros(n*m,Nz,precision); % store image size phi.n = n; phi.m = m; % build phi.x % ====================== for k = 1:Nx a = listx(k,1); b = listx(k,2); Lx = legendre1D(x,a); Ly = legendre1D(y,b); % Lx(Im) = 0; % Ly(In) = 0; P = Ly' * Lx; phi.x(:,k) = P(:); end % build phi.y % ====================== for k = 1:Ny a = listy(k,1); b = listy(k,2); Lx = legendre1D(x,a); Ly = legendre1D(y,b); % Lx(Im) = 0; % Ly(In) = 0; P = Ly' * Lx; phi.y(:,k) = P(:); end % build phi.z % ====================== for k = 1:Nz a = listz(k,1); b = listz(k,2); Lx = legendre1D(x,a); Ly = legendre1D(y,b); % Lx(Im) = 0; % Ly(In) = 0; P = Ly' * Lx; phi.z(:,k) = P(:); end % delete(hwait); function L = legendre1D(x,p) % this function builds the 1D polynomial of order p for n points n = length(x); % initiate the first two polynomials Ln = ones(1,n); Lk = x; % loop until the required order for a = 0:p if a == 0 L = Ln; elseif a == 1 L = Lk; else % calculate the new polynomial L = ((2*a + 1)*x.*Lk - a*Ln) ./ (a + 1); % update the previous two Ln = Lk; Lk = L; end end
github
Jann5s/BasicGDIC-master
plotimage.m
.m
BasicGDIC-master/lib_bgdic/plotimage.m
1,340
utf_8
64fab9dd9435e37bf42e2ca5c3c6ee18
% ================================================== function [] = plotimage(H) % plot the current image to figpanel1 S = guihandles(H); D = guidata(H); if isfield(D,'outputfile') % headless mode return end % test if there are images if ~isfield(D,'files') return; end Nim = length(D.files); % get current image (i.e. slider position) id = str2double(get(S.imageid,'String')); n = D.files(1).size(1); m = D.files(1).size(2); A = D.files(id).image; [n, m] = size(A); xlim = [1 m]; ylim = [1 n]; x = 1:m; y = 1:n; % plot image set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes1) title(sprintf('image:%d name:%s',id,D.files(id).name),'Interpreter','none') hi = findobj(H,'Tag','image_image'); if isempty(hi) colormap(D.gui.color.cmap) set(gca,'NextPlot','replacechildren') imagesc(x,y,A,'Parent',S.axes1,'Tag','image_image'); xlabel('x [px]') ylabel('y [px]') set(gca,'ydir','reverse') set(gca,'xlim',xlim) set(gca,'ylim',ylim) daspect([1 1 1 ]) else set(hi,'CData',A); end ht = findobj(H,'Tag','image_text'); if isempty(ht) ht = text(0.02,0.02,sprintf('%d/%d',id,Nim),'units','normalized','Tag','image_text'); set(ht,'color',D.gui.color.fg) set(ht,'FontSize',D.gui.fontsize(4)) set(ht,'FontWeight','bold') else set(ht,'String',sprintf('%d/%d',id,Nim)); end drawnow
github
Jann5s/BasicGDIC-master
questdlgjn.m
.m
BasicGDIC-master/lib_bgdic/questdlgjn.m
2,890
utf_8
8636f53e071e35582654e368715ea7da
function Button=questdlgjn(Question,Title,Btn1,Btn2,Default,Position) % function similar to questdlg, except simpler and with the option to % position it. if ~iscell(Question) Question = {Question}; end fontsize = 14; N = length(Question); M = max(cellfun('length',Question)); Figheight = N*2*fontsize + 2*fontsize; Figwidth = M*0.6*fontsize + 2*fontsize; Figpos(3:4) = [Figwidth Figheight]; Figpos(1:2) = Position - 0.5*Figpos(3:4); FigColor=get(0,'DefaultUicontrolBackgroundColor'); WindowStyle='modal'; Interpreter='none'; Resize = 'off'; H = dialog( ... 'Visible' ,'on' , ... 'Name' ,Title , ... 'Pointer' ,'arrow' , ... 'Units' ,'pixels' , ... 'UserData' ,'Cancel' , ... 'Tag' ,Title , ... 'HandleVisibility' ,'callback' , ... 'Color' ,FigColor , ... 'NextPlot' ,'add' , ... 'WindowStyle' ,WindowStyle, ... 'Resize' ,Resize, ... 'Position' ,Figpos ... ); xpos = linspace(0.08,0.92,4); ypos(1) = 0.08; ypos(2) = ypos(1) + 0.05 + 2/(2*N+2); height = 1.8/(1.5*N+2); width = 0.9*mean(diff(xpos)); % Create title uicontrol('String',Question,... 'Style','text',... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[xpos(1) ypos(2) xpos(end)-xpos(1) 1-(ypos(2)+0.06)],... 'FontSize',fontsize,... 'Parent',H); uicontrol('String',Btn1,... 'Style','pushbutton',... 'units','normalized',... 'Position',[xpos(1) ypos(1) width height],... 'FontSize',fontsize,... 'Parent',H,... 'call',{@pressBut1,H}); uicontrol('String',Btn2,... 'Style','pushbutton',... 'units','normalized',... 'Position',[xpos(2) ypos(1) width height],... 'FontSize',fontsize,... 'Parent',H,... 'call',{@pressBut2,H}); uicontrol('String','Cancel',... 'ToolTipString','cancel input',... 'Style','pushbutton',... 'units','normalized',... 'Position',[xpos(3) ypos(1) width height],... 'FontSize',fontsize,... 'Parent',H,... 'call',{@pressCancel,H}); set(H,'KeyPressFcn',{@doFigureKeyPress,H}) uiwait(H) if ishandle(H) Button = guidata(H); if Button == 1 Button = Btn1; elseif Button == 2 Button = Btn2; elseif Button == 3 Button = Default; end delete(H); else Button = []; end function doFigureKeyPress(obj, evd, H) %#ok switch(evd.Key) case {'return','space'} pressDefault([],[],H); case {'escape'} pressCancel([],[],H); end function pressBut1(varargin) H = varargin{3}; guidata(H,1); uiresume(H); function pressBut2(varargin) H = varargin{3}; guidata(H,2); uiresume(H); function pressCancel(varargin) H = varargin{3}; guidata(H,[]); uiresume(H); function pressDefault(varargin) H = varargin{3}; guidata(H,3); uiresume(H);
github
Jann5s/BasicGDIC-master
jnmap.m
.m
BasicGDIC-master/lib_bgdic/jnmap.m
2,969
utf_8
c9fcfad5111ee46345c8780e2368ef92
function cmap = jnmap(varargin) % Create Colormaps with monotomic change in Luminace and change in % GrayValue (if converted). % % cmap = jnmap(N) : produces and Nx3 matrix as do the default matlab % colormaps % % cmap = jnmap(N,colorname) : same but selects a color scheme with name % colorname % % currently available colorschemes are % - Blueish (b) % - Greenish (g) % - Redish (r) % % examples: % cmap = jnmap(64,'Greenish') % cmap = jnmap(64,'g') if nargin == 0 N = 64; cname = 'blueish'; elseif nargin == 1 if isnumeric(varargin{1}) N = varargin{1}; cname = 'blueish'; else N = 64; cname = varargin{1}; end else N = varargin{1}; cname = varargin{2}; end % get the colormap if any(strcmpi(cname,{'blueish','blue','b'})) % Blueish A = 24/36; B = 15/36; C = .5; elseif any(strcmpi(cname,{'greenish','green','g'})) % Greenish A = 19/36; B = 6/36; C = .5; elseif any(strcmpi(cname,{'redish','red','r'})) % Redish A = 30/36; B = 45/36; C = .5; else error('unknown colormap'); end H = linspace(A,B,N); H = H - floor(H); S = linspace(C,C,N); L = linspace(0,1,N); HSL = [H(:) S(:) L(:)]; RGB = hsl2rgb(HSL); cmap = RGB; function rgb=hsl2rgb(hsl) %Converts Hue-Saturation-Luminance Color value to Red-Green-Blue Color value % %Usage % RGB = hsl2rgb(HSL) % % converts HSL, a M X 3 color matrix with values between 0 and 1 % into RGB, a M X 3 color matrix with values between 0 and 1 % %See also rgb2hsl, rgb2hsv, hsv2rgb %Suresh E Joel, April 26,2003 if nargin<1, error('Too few arguements for hsl2rgb'); return; elseif nargin>1, error('Too many arguements for hsl2rgb'); return; end; if max(max(hsl))>1 | min(min(hsl))<0, error('HSL values have to be between 0 and 1'); return; end; for i=1:size(hsl,1), if hsl(i,2)==0,%when sat is 0 rgb(i,1:3)=hsl(i,3);% all values are same as luminance end; if hsl(i,3)<0.5, temp2=hsl(i,3)*(1+hsl(i,2)); else temp2=hsl(i,3)+hsl(i,2)-hsl(i,3)*hsl(i,2); end; temp1=2*hsl(i,3)-temp2; temp3(1)=hsl(i,1)+1/3; temp3(2)=hsl(i,1); temp3(3)=hsl(i,1)-1/3; for j=1:3, if temp3(j)>1, temp3(j)=temp3(j)-1; elseif temp3(j)<0, temp3(j)=temp3(j)+1; end; if 6*temp3(j)<1, rgb(i,j)=temp1+(temp2-temp1)*6*temp3(j); elseif 2*temp3(j)<1, rgb(i,j)=temp2; elseif 3*temp3(j)<2, rgb(i,j)=temp1+(temp2-temp1)*(2/3-temp3(j))*6; else rgb(i,j)=temp1; end; end; end; rgb=round(rgb.*100000)./100000; %Sometimes the result is 1+eps instead of 1 or 0-eps instead of 0 ... so to get rid of this I am rounding to 5 decimal places)
github
Jann5s/BasicGDIC-master
plotiguess.m
.m
BasicGDIC-master/lib_bgdic/plotiguess.m
6,535
utf_8
7854d77a8c9160559cd34f3ac7adb6d8
% ================================================== function [] = plotiguess(H) % plot the current image to figpanel1 S = guihandles(H); D = guidata(H); if isfield(D,'outputfile') % headless mode return end % test if there are images if ~isfield(D,'files') return; end % get current image (i.e. slider position) Nim = length(D.files); id = str2double(get(S.iguessid,'String')); n = D.files(1).size(1); m = D.files(1).size(2); x = 1:m; y = 1:n; xlim = [1 m]; ylim = [1 n]; % original images Aref = D.files(1).image; Acur = D.files(id).image; % processed images if isfield(D.files,'imageproc') Bref = D.files(1).imageproc; Bcur = D.files(id).imageproc; else Bref = Aref; Bcur = Acur; end for k = 1:4 if k == 1 A = Aref; ha = S.axes41; titlestr = sprintf('image:%d %s',1,'original'); tag = 'iguess_image1'; elseif k == 2 A = Acur; ha = S.axes42; titlestr = sprintf('image:%d %s',id,'original'); tag = 'iguess_image2'; elseif k == 3 A = Bref; ha = S.axes43; titlestr = sprintf('image:%d %s',1,'processed'); tag = 'iguess_image3'; elseif k == 4 A = Bcur; ha = S.axes44; titlestr = sprintf('image:%d %s',id,'processed'); tag = 'iguess_image4'; end set(0,'CurrentFigure',H) set(H,'CurrentAxes',ha) hi = findobj(H,'Tag',tag); title(titlestr) if isempty(hi) colormap(D.gui.color.cmap) set(gca,'NextPlot','replacechildren') hi = imagesc(x,y,A,'Parent',ha,'Tag',tag); xlabel('x [px]') ylabel('y [px]') set(gca,'ydir','reverse') set(gca,'xlim',xlim) set(gca,'ylim',ylim) daspect([1 1 1 ]) else set(hi,'CData',A); end clim(1) = min(A(:)); clim(2) = max(A(:)); if clim(1) == clim(2); clim = clim(1) + [-0.01 0.01]; end caxis(clim); % If mask is set % =============================== if ~isempty(D.mask) && any(k == [1 3]) mask = D.mask; % maskimage Im = maskimage(mask,n,m); % mask border Mb = Im & ~image_erode(Im,1); alpha = 0.7; % alphadata AlphaData = zeros(n,m); AlphaData(Im) = alpha; % the part in the mask is semi-transparent AlphaData(~Im) = 1; % the part outside the mask is transparent AlphaData(Mb) = 0.5; % the border is opaque set(hi,'AlphaData',AlphaData); else set(hi,'AlphaData',1) end ht = findobj(H,'Tag','iguess_text'); if isempty(ht) ht = text(0.01,0.03,sprintf('%d/%d',id,Nim),'units','normalized','Tag','iguess_text'); set(ht,'color',D.gui.color.fg) set(ht,'FontSize',D.gui.fontsize(3)) set(ht,'FontWeight','bold') else set(ht,'String',sprintf('%d/%d',id,Nim)); end end % If ROI is set % =============================== if isfield(D,'roi') % plot the evaluation area roi = D.roi; FV.Vertices = [roi([1 2 2 1])',roi([3 3 4 4])']; FV.Faces = [1 2 3 4]; set(0,'CurrentFigure',H) linestyle = '-'; hp = findobj(H,'Tag','iguess_roi'); if isempty(hp) set(H,'CurrentAxes',S.axes41) set(gca,'NextPlot','add') hp = patch(FV,'EdgeColor',D.gui.color.fg,'FaceColor','none','LineWidth',D.gui.linewidth,'LineStyle',linestyle,'Tag','iguess_roi'); set(H,'CurrentAxes',S.axes43) set(gca,'NextPlot','add') hp = patch(FV,'EdgeColor',D.gui.color.fg,'FaceColor','none','LineWidth',D.gui.linewidth,'LineStyle',linestyle,'Tag','iguess_roi'); else set(hp,'Vertices',FV.Vertices,'LineStyle',linestyle); end end if isfield(D,'iguess') && ~isempty(D.iguess.x) iguess = D.iguess; if isfield(iguess,'subset') % plot subsets hp = findobj(H,'Tag','iguess_subsets'); if isempty(hp) set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes41) set(gca,'NextPlot','add') patch(iguess.subset.X,iguess.subset.Y,1,'EdgeColor',D.gui.color.fg,'FaceColor','none','LineWidth',D.gui.linewidth,'Tag','iguess_subsets') set(H,'CurrentAxes',S.axes43) set(gca,'NextPlot','add') patch(iguess.subset.X,iguess.subset.Y,1,'EdgeColor',D.gui.color.fg,'FaceColor','none','LineWidth',D.gui.linewidth,'Tag','iguess_subsets') end end % Plot the reference href = findobj(H,'Tag','iguess_pointsref'); set(0,'CurrentFigure',H) if ~isempty(href); set(href,'XData',iguess.x,'YData',iguess.y); else set(H,'CurrentAxes',S.axes41) set(gca,'NextPlot','add') plot(iguess.x,iguess.y,'.','Color',D.gui.color.fg,'Markersize',1.5*D.gui.markersize,'Tag','iguess_pointsref') set(H,'CurrentAxes',S.axes42) set(gca,'NextPlot','add') plot(iguess.x,iguess.y,'.','Color',D.gui.color.fg,'Markersize',1.5*D.gui.markersize,'Tag','iguess_pointsref') set(H,'CurrentAxes',S.axes43) set(gca,'NextPlot','add') plot(iguess.x,iguess.y,'.','Color',D.gui.color.fg,'Markersize',1.5*D.gui.markersize,'Tag','iguess_pointsref') set(H,'CurrentAxes',S.axes44) set(gca,'NextPlot','add') plot(iguess.x,iguess.y,'.','Color',D.gui.color.fg,'Markersize',1.5*D.gui.markersize,'Tag','iguess_pointsref') drawnow end % Plot the deformed hdef = findobj(H,'Tag','iguess_pointsdef'); set(0,'CurrentFigure',H) if ~isempty(hdef); set(hdef,'XData',iguess.x+iguess.ux(:,id),'YData',iguess.y+iguess.uy(:,id)); else set(H,'CurrentAxes',S.axes42) set(gca,'NextPlot','add') plot(iguess.x+iguess.ux(:,id),iguess.y+iguess.uy(:,id),'o','Color',D.gui.color.fg,'Markersize',1.5*D.gui.markersize,'Tag','iguess_pointsdef') set(H,'CurrentAxes',S.axes44) set(gca,'NextPlot','add') plot(iguess.x+iguess.ux(:,id),iguess.y+iguess.uy(:,id),'o','Color',D.gui.color.fg,'Markersize',1.5*D.gui.markersize,'Tag','iguess_pointsdef') drawnow end % set section indicator on set(S.secind4,'BackgroundColor',D.gui.color.on) else hs = findobj(H,'Tag','iguess_subsets'); if ~isempty(hs) delete(hs); end href = findobj(H,'Tag','iguess_pointsref'); if ~isempty(href) delete(href); end hdef = findobj(H,'Tag','iguess_pointsdef'); if ~isempty(hdef) delete(hdef); end end drawnow
github
Jann5s/BasicGDIC-master
buildphi_chebyshev.m
.m
BasicGDIC-master/lib_bgdic/buildphi_chebyshev.m
4,453
utf_8
5affe03bc22d62613537b2d203d68770
function phi = buildphi_chebyshev(x,y,phi_list,roi,varargin) %BUILDPHI_CHEBYSHEV creates the basis function matrix phi, which has one % row for each pixel and one column for each basis function. The created % 2D basis functions are based on the Chebyshev polynomials of the first % kind by Pafnuty Chebyshev (alternatively transliterated as Chebychev, % Chebysheff, Chebyshov, Tchebychev or Tchebycheff, Tschebyschev or % Tschebyscheff). % % phi = buildphi_chebyshev(x,y,phi_list,roi) % % INPUTS: % n,m : the image dimentions of the ROI, the shape functions will % be cacluated on a domain -1 <= x,y < 1 with n steps in y % direction and m steps in x direction % phi_list : a list of basis functions of size (N x 3) where N is the % number of basis functions and each row contains the three % parameters, [a b c], where [a b] are the polynomial orders: % P = (x^a)*(y^b), and [c] is the direction in which the basis % function is applied, 1=x, 2=y, and 3=z. % % OPTIONAL INPUTS: % phi = buildphi_chebyshev(x,y,phi_list,roi,'single') % By default BUILDPHI_CHEBYSHEV uses double precision floating point % values for the the phi matrix, however when running into memory issues % it is possible to use singe precision, nevertheless this will % influence the DIC accuracy greatly and is not recommended. % % OUTPUT: % The basis function matrix is split into a parts according to the % application direction, i.e. phi.x, phi.y, phi.z. In other words, this % function returns a structure with one matrix per dimension. % % EXAMPLE: % roi = [-5 5 -4 4]; % [n m] = deal(120,150); % phi_list(1,:) = [0 0 1]; % x-translation % phi_list(2,:) = [0 0 2]; % y-translation % phi_list(3,:) = [0 0 3]; % z-translation % phi_list(4,:) = [0 1 1]; % strain-xx % phi_list(5,:) = [0 1 2]; % shear-xy % phi_list(6,:) = [0 1 3]; % tilt around y-axis % phi_list(7,:) = [1 0 1]; % shear-yx % phi_list(8,:) = [1 0 2]; % strain-yy % phi_list(9,:) = [1 0 3]; % tilt around x-axis % phi = buildphi_chebyshev(x,y,phi_list,roi); % phiplot(x,y,phi); % % See also JNDIC, PHIPLOT, BUILDPHI_POLY, BUILDPHI_LEGENDRE, % BUILDPHI_FEMT3. % %copyright: Jan Neggers, 2013 precision = 'double'; if nargin == 5 if strcmpi(varargin{1},'single') precision = 'single'; elseif strcmpi(varargin{1},'double') precision = 'double'; else error('buildphi_chebyshev: unknown precision options') end end if length(roi) == 1 roi = [min(x)+roi max(x)-roi min(y)+roi max(y)-roi]; end % create a space x = 2*(x - 0.5*(roi(1)+roi(2))) / (roi(2) - roi(1)); y = 2*(y - 0.5*(roi(3)+roi(4))) / (roi(4) - roi(3)); m = length(x); n = length(y); % number of shape functions N = size(phi_list,1); % split list into directions listx = phi_list(phi_list(:,3)==1,:); listy = phi_list(phi_list(:,3)==2,:); listz = phi_list(phi_list(:,3)==3,:); % number of DOF per direction Nx = size(listx,1); Ny = size(listy,1); Nz = size(listz,1); % initiate matrices phi.x = zeros(n*m,Nx,precision); phi.y = zeros(n*m,Ny,precision); phi.z = zeros(n*m,Nz,precision); % store image size phi.n = n; phi.m = m; % build phi.x % ====================== for k = 1:Nx a = listx(k,1); b = listx(k,2); Tx = chebyshev1D(x,a); Ty = chebyshev1D(y,b); % Tx(Im) = 0; % Ty(In) = 0; P = Ty' * Tx; phi.x(:,k) = P(:); end % build phi.y % ====================== for k = 1:Ny a = listy(k,1); b = listy(k,2); Tx = chebyshev1D(x,a); Ty = chebyshev1D(y,b); % Tx(Im) = 0; % Ty(In) = 0; P = Ty' * Tx; phi.y(:,k) = P(:); end % build phi.z % ====================== for k = 1:Nz a = listz(k,1); b = listz(k,2); Tx = chebyshev1D(x,a); Ty = chebyshev1D(y,b); % Tx(Im) = 0; % Ty(In) = 0; P = Ty' * Tx; phi.z(:,k) = P(:); end function T = chebyshev1D(x,p) % this function builds the 1D polynomial of order p for n points n = length(x); % initiate the first two polynomials Tn = ones(1,n); Tk = x; % loop until the required order for a = 0:p if a == 0 T = Tn; elseif a == 1 T = Tk; else % calculate the new polynomial T = 2*x.*Tk - Tn; % update the previous two Tn = Tk; Tk = T; end end
github
Jann5s/BasicGDIC-master
plotroimask.m
.m
BasicGDIC-master/lib_bgdic/plotroimask.m
2,619
utf_8
1beb9f85fc948c232e153393a9bf8242
% ================================================== function [] = plotroimask(H) % plot funtion for the evaluated pattern S = guihandles(H); D = guidata(H); if isfield(D,'outputfile') % headless mode return end if ~isfield(D,'files') return; end Nim = length(D.files); id = str2double(get(S.roiid,'String')); n = D.files(1).size(1); m = D.files(1).size(2); A = D.files(id).image; x = 1:m; y = 1:n; xlim = [1 m]; ylim = [1 n]; set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes3) title('ROI and Mask') hi = findobj(H,'Tag','roi_image'); if isempty(hi) % plot the pattern colormap(D.gui.color.cmap) set(gca,'NextPlot','replacechildren') hi = imagesc(x,y,A,'Parent',S.axes3,'Tag','roi_image'); xlabel('x [px]') ylabel('y [px]') set(gca,'ydir','reverse') set(gca,'xlim',xlim) set(gca,'ylim',ylim) daspect([1 1 1 ]) else set(hi,'CData',A); end ht = findobj(H,'Tag','roi_text'); if isempty(ht) ht = text(0.02,0.02,sprintf('%d/%d',id,Nim),'units','normalized','Tag','roi_text'); set(ht,'color',D.gui.color.fg) set(ht,'FontSize',D.gui.fontsize(4)) set(ht,'FontWeight','bold') else set(ht,'String',sprintf('%d/%d',id,Nim)); end % If mask is set % =============================== if ~isempty(D.mask) mask = D.mask; % maskimage Im = maskimage(mask,n,m); % mask border Mb = Im & ~image_erode(Im,1); if id == 1 alpha = 0.6; else alpha = 0.8; end % alphadata AlphaData = zeros(n,m); AlphaData(Im) = alpha; % the part in the mask is semi-transparent AlphaData(~Im) = 1; % the part outside the mask is transparent AlphaData(Mb) = 0.3; % the border is opaque set(hi,'AlphaData',AlphaData); else set(hi,'AlphaData',1); end % If ROI is set % =============================== if isfield(D,'roi') % plot the evaluation area roi = D.roi; FV.Vertices = [roi([1 2 2 1])',roi([3 3 4 4])']; FV.Faces = [1 2 3 4]; if id == 1 linestyle = '-'; else linestyle = '-.'; end set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes3) hp = findobj(H,'Tag','roi_roi'); if isempty(hp) set(gca,'NextPlot','add') hp = patch(FV,'EdgeColor',D.gui.color.fg,'FaceColor','none','LineWidth',D.gui.linewidth,'LineStyle',linestyle,'Tag','roi_roi'); else set(hp,'Vertices',FV.Vertices,'LineStyle',linestyle); end % set section indicator on set(S.secind3,'BackgroundColor',D.gui.color.on) end clim(1) = min(A(:)); clim(2) = max(A(:)); caxis(clim) drawnow
github
Jann5s/BasicGDIC-master
correlate.m
.m
BasicGDIC-master/lib_bgdic/correlate.m
26,394
utf_8
6f3b921fd49ba1ae7149f491543f5835
function dic = correlate(H,S,cg,phi12,phi34) D = guidata(H); usegpu = get(S.dicusegpu,'Value')-1; if isfield(D,'outputfile') headlessmode = true; else headlessmode = false; end % Prepare DIC % ======================== dic = []; % image space f = cg.f; g = cg.g; x = cg.x; y = cg.y; [X, Y] = meshgrid(x,y); if usegpu f = gpuArray(f); g = gpuArray(g); phi12 = gpuArray(phi12); phi34 = gpuArray(phi34); end % region of interest roi = cg.roi; Im = find(x >= roi(1) & x <= roi(2)); In = find(y >= roi(3) & y <= roi(4)); Iroi = find(X(:) >= roi(1) & X(:) <= roi(2) & Y(:) >= roi(3) & Y(:) <= roi(4)); xroi = x(Im); yroi = y(In); mroi = length(xroi); nroi = length(yroi); froi = f(In,Im); [Xroi,Yroi] = meshgrid(xroi,yroi); % advanced options cornquiver = D.gui.ini.cornquiver.value; cordofsupport = D.gui.ini.cordofsupport.value; corsparseness = D.gui.ini.corsparseness.value; corgradcrit = D.gui.ini.corgradcrit.value; cordivtol = D.gui.ini.cordivtol.value; % tikhonov parameters cg.tikhpar = logspace(log10(cg.tikhpar1),log10(cg.tikhpar2),cg.tikhsteps); % initial guess p = cg.p; Ndof = length(p); % number of dimensions Ndims = cg.Ndims; Idims{1} = 1:cg.Nphi(1); Idims{2} = Idims{1}(end) + (1:cg.Nphi(2)); if Ndims >= 3 Idims{3} = Idims{2}(end) + (1:cg.Nphi(3)); end if Ndims >= 4 Idims{4} = Idims{3}(end) + (1:cg.Nphi(4)); end if Ndims >= 5 Idims{5} = Idims{4}(end) + (1:cg.Nphi(5)); end if Ndims >= 6 Idims{6} = Idims{5}(end) + (1:cg.Nphi(6)); end Idofdim = []; % lists which dimension this dof is for Idofdof = []; % lists which subdof in phi12 or phi23 for k = 1:length(cg.Nphi) Idofdim = [Idofdim k*ones(1,cg.Nphi(k))]; Idofdof = [Idofdof 1:cg.Nphi(k)]; end % image gradients dx = mean(diff(xroi)); dy = mean(diff(yroi)); [dfdx, dfdy] = gradient(f(In,Im),dx,dy); [dgdx, dgdy] = gradient(g,dx,dy); % get total support support = sum(abs(phi12(Iroi,:)),2); if Ndims >= 3 support = support + sum(abs(phi34(Iroi,:)),2); end support = reshape(support,nroi,mroi); % get mask Imask = find(cg.maskimg(In,Im) == 1 | support == 0); Iunmask = find(cg.maskimg(In,Im) ~= 1 & support > 0); Npx = length(Iunmask); % Quiver Nq = cornquiver; Iqn = round(linspace(2,nroi-1,Nq)); Iqm = round(linspace(2,mroi-1,Nq)); [IQm, IQn] = meshgrid(Iqm,Iqn); Iq = sub2ind([nroi mroi],IQn(:),IQm(:)); Iq = intersect(Iq,Iunmask); % liveviewdata lview.xlim = [x(1) x(end)]; lview.ylim = [y(1) y(end)]; lview.xroi = xroi; lview.yroi = yroi; lview.X = Xroi(Iq); lview.Y = Yroi(Iq); lview.r = froi; lview.U1 = zeros(length(Iq),1); lview.U2 = zeros(length(Iq),1); lview.inc = cg.inc; lview.Ninc = cg.Ninc; lview.icg = cg.icg; lview.it = 0; % Check for ill-supported dof (as cons. of masking) Ntot(Idims{1}) = sum(phi12(Iroi,:)~=0); Nsup(Idims{1}) = sum(phi12(Iroi(Iunmask),:)~=0); Ntot(Idims{2}) = Ntot(Idims{1}); Nsup(Idims{2}) = Nsup(Idims{1}); if Ndims >= 3 Ntot(Idims{3}) = sum(phi34(Iroi,:)~=0); Nsup(Idims{3}) = sum(phi34(Iroi(Iunmask),:)~=0); end if Ndims >= 4 Ntot(Idims{4}) = Ntot(Idims{3}); Nsup(Idims{4}) = Nsup(Idims{3}); end if Ndims >= 5 Ntot(Idims{5}) = Ntot(Idims{3}); Nsup(Idims{5}) = Nsup(Idims{3}); end if Ndims == 6 Ntot(Idims{6}) = Ntot(Idims{3}); Nsup(Idims{6}) = Nsup(Idims{3}); end % indices of the well supported shape functions Isup = find(Nsup./Ntot > cordofsupport); Iunsup = find(Nsup./Ntot <= cordofsupport); % update status stat = get(S.corstatus,'String'); stat = [sprintf('(%3d/%3d) free dof',length(Isup),sum(cg.Nphi)) ; stat]; set(S.corstatus,'String',stat);drawnow if ~isempty(Iunsup) for k = 1:length(Iunsup); if k == 1 unsupportedstr = num2str(Iunsup(k)); else unsupportedstr = [unsupportedstr, ',' num2str(Iunsup(k))]; end if mod(k,10) == 0 unsupportedstr = [unsupportedstr ' ']; end end str = sprintf('(%3d/%3d) free dof, unsupported: [%s]',length(Isup),sum(cg.Nphi),unsupportedstr); statstr = appendstatus({''},str); if cg.headlessmode headlessstatus(str); end else str = sprintf('(%3d/%3d) free dof',length(Isup),sum(cg.Nphi)); statstr = appendstatus({''},str); end % how sparse is each dof sparseness = Ntot / Npx; usesparse = mean(sparseness) < corsparseness; if (cg.precision == 1) precision = 'single'; usesparse = false; else precision = 'double'; end % memory allocation U1 = zeros(nroi,mroi,precision); U2 = zeros(nroi,mroi,precision); U3 = 0; U4 = 0; U5 = 0; U6 = 0; if Ndims >= 3 U3 = zeros(nroi,mroi,precision); end if Ndims >= 4 U4 = zeros(nroi,mroi,precision); end if Ndims >= 5 U5 = zeros(nroi,mroi,precision); end if Ndims >= 6 U6 = zeros(nroi,mroi,precision); end if cg.memsave == 0 % full L matrix definition if usegpu L = gpuArray.zeros(Npx,Ndof,precision); elseif usesparse L = spalloc(Npx,Ndof,sum(Ntot)); else L = zeros(Npx,Ndof,precision); end elseif cg.memsave == 1 % per dimension L matrix definition if usegpu Li = gpuArray.zeros(Npx,cg.Nphi(1),precision); Lj = gpuArray.zeros(Npx,cg.Nphi(1),precision); elseif usesparse Li = spalloc(Npx,cg.Nphi(1),max(Ntot(Idims{1}))*cg.Nphi(1)); Lj = spalloc(Npx,cg.Nphi(1),max(Ntot(Idims{1}))*cg.Nphi(1)); else Li = zeros(Npx,cg.Nphi(1),precision); Lj = zeros(Npx,cg.Nphi(1),precision); end elseif cg.memsave == 2 % per dof L matrix definition if usegpu Li = gpuArray.zeros(Npx,1,precision); Lj = gpuArray.zeros(Npx,1,precision); elseif usesparse Li = spalloc(Npx,1,max(Ntot(Idims{1}))); Lj = spalloc(Npx,1,max(Ntot(Idims{1}))); else Li = zeros(Npx,1,precision); Lj = zeros(Npx,1,precision); end end % old displacements (to compute the incremental displacement) Uo1 = zeros(nroi,mroi,precision); Uo2 = zeros(nroi,mroi,precision); Uo3 = zeros(nroi,mroi,precision); % counters conv = false; it = 0; div = 0; % initialize ndu = Inf; nb = Inf; ndp = Inf; dr = -Inf; convcrit = [ndu ; nb ; ndp ; dr]; convparstr{1,1} = '|du|'; convparstr{2,1} = '|b|'; convparstr{3,1} = '|dp|'; convparstr{4,1} = '|dr|'; str = sprintf('%3s, %10s, %10s, %10s, %10s, %4s, %3s','it',convparstr{1},convparstr{2},convparstr{3},convparstr{4},'div','sp'); statstr = appendstatus(statstr,str); if headlessmode headlessstatus(str); end stat = get(S.corstatus,'String'); stat = [sprintf('%2s,%9s,%13s,%4s','it',convparstr{cg.convparam},'mean|r|','div') ; stat]; set(S.corstatus,'String',stat);drawnow while ~conv it = it + 1; % Check for stop button drawnow if get(S.corstop,'Value') dic.converged = 4; return end if cg.memsave == 0 if issparse(L) sprs = 1; else sprs = 0; end else if issparse(Li) sprs = 1; else sprs = 0; end end % update displacement field U1 = reshape(phi12(Iroi,:) * p(Idims{1}),nroi,mroi); U2 = reshape(phi12(Iroi,:) * p(Idims{2}),nroi,mroi); if Ndims >= 3 U3 = reshape(phi34(Iroi,:) * p(Idims{3}),nroi,mroi); end if Ndims >= 4 U4 = reshape(phi34(Iroi,:) * p(Idims{4}),nroi,mroi); end if Ndims >= 5 U5 = reshape(phi34(Iroi,:) * p(Idims{5}),nroi,mroi); end if Ndims >= 6 U6 = reshape(phi34(Iroi,:) * p(Idims{6}),nroi,mroi); end % update gtilde if usegpu gt = gpuArray(interp2(X,Y,gather(g),X(In,Im)+gather(U1),Y(In,Im)+gather(U2),'spline',0)) ; % correct the brightness q = gather(U3) + gather(U4).*gt + gather(U5).*gt.^2 + gather(U6).*gt.^3; else gt = interp2(X,Y,g,X(In,Im)+U1,Y(In,Im)+U2,'spline',0); % correct the brightness q = U3 + U4.*gt + U5.*gt.^2 + U6.*gt.^3; end if it == 1 du = [ndu ndu ndu]; else % maximum delta displacements du(1) = max(abs(U1(:) - Uo1(:))); du(2) = max(abs(U2(:) - Uo2(:))); du(3) = max(abs(q(:) - Uo3(:))); end % update the old displacements Uo1 = U1; Uo2 = U2; Uo3 = q; % update residual r = froi - (gt + q); % set masked residual to zero r(Imask) = 0; % update the liveview if cg.liveview == 2 lview.it = it; lview.r = r; lview.U1 = U1(Iq); lview.U2 = U2(Iq); plotliveview(H,S,lview); elseif (cg.liveview == 1) && (it == 1) lview.it = it; lview.r = r; lview.U1 = U1(Iq); lview.U2 = U2(Iq); plotliveview(H,S,lview); end % update image gradient if cg.gradient == 2 %gradfg if usegpu gradx = 0.5*gpuArray(dfdx + interp2(X,Y,gather(dgdx),X(In,Im)+gather(U1),Y(In,Im)+gather(U2),'spline',0)); grady = 0.5*gpuArray(dfdy + interp2(X,Y,gather(dgdy),X(In,Im)+gather(U1),Y(In,Im)+gather(U2),'spline',0)); else gradx = 0.5*(dfdx + interp2(X,Y,dgdx,X(In,Im)+U1,Y(In,Im)+U2,'spline',0)); grady = 0.5*(dfdy + interp2(X,Y,dgdy,X(In,Im)+U1,Y(In,Im)+U2,'spline',0)); end Lupdate = true; elseif cg.gradient == 3 %gradf if it == 1 gradx = dfdx; grady = dfdy; Lupdate = true; else Lupdate = false; end elseif cg.gradient == 4 %gradg if usegpu gradx = gpuArray(interp2(X,Y,gather(dgdx),X(In,Im)+gather(U1),Y(In,Im)+gather(U2),'spline',0)); grady = gpuArray(interp2(X,Y,gather(dgdy),X(In,Im)+gather(U1),Y(In,Im)+gather(U2),'spline',0)); else gradx = interp2(X,Y,dgdx,X(In,Im)+U1,Y(In,Im)+U2,'spline',0); grady = interp2(X,Y,dgdy,X(In,Im)+U1,Y(In,Im)+U2,'spline',0); end Lupdate = true; elseif cg.gradient == 1 %auto % auto grad threshold if (it > 2) && (convcrit(cg.convparam) < corgradcrit*cg.convcrit) % close to convergence stop updating the gradient Lupdate = false; else % far from convergence use gradfg if usegpu gradx = 0.5*gpuArray(dfdx + interp2(X,Y,gather(dgdx),X(In,Im)+gather(U1),Y(In,Im)+gather(U2),'spline',0)); grady = 0.5*gpuArray(dfdy + interp2(X,Y,gather(dgdy),X(In,Im)+gather(U1),Y(In,Im)+gather(U2),'spline',0)); else gradx = 0.5*(dfdx + interp2(X,Y,dgdx,X(In,Im)+U1,Y(In,Im)+U2,'spline',0)); grady = 0.5*(dfdy + interp2(X,Y,dgdy,X(In,Im)+U1,Y(In,Im)+U2,'spline',0)); end Lupdate = true; end end % update L, M and B % ================================= if Lupdate if usegpu M = gpuArray.zeros(Ndof,Ndof); b = gpuArray.zeros(Ndof,1); else M = zeros(Ndof,Ndof); b = zeros(Ndof,1); end Nsup = zeros(Ndof,1); Ntot = zeros(Ndof,1); end % Check for stop button drawnow if get(S.corstop,'Value') dic.converged = 4; return end if cg.memsave == 0 % full L matrix definition (most memory and fastest) % update status stat = get(S.corstatus,'String'); stat = ['computing L, M and b (fast)' ; stat]; set(S.corstatus,'String',stat);drawnow if Lupdate % x L(:,Idims{1}) = repmat(gradx(Iunmask),1,cg.Nphi(1)) .* phi12(Iroi(Iunmask),:); % y L(:,Idims{2}) = repmat(grady(Iunmask),1,cg.Nphi(2)) .* phi12(Iroi(Iunmask),:); % z (or constant relaxation) if Ndims >= 3 L(:,Idims{3}) = phi34(Iroi(Iunmask),:); end % linear relaxation if Ndims >= 4 L(:,Idims{4}) = repmat(froi(Iunmask),1,cg.Nphi(4)) .* phi34(Iroi(Iunmask),:); end % quadratic relaxation if Ndims >= 5 L(:,Idims{5}) = repmat(froi(Iunmask).^2,1,cg.Nphi(5)) .* phi34(Iroi(Iunmask),:); end % cubic relaxation if Ndims == 6 L(:,Idims{6}) = repmat(froi(Iunmask).^3,1,cg.Nphi(6)) .* phi34(Iroi(Iunmask),:); end end % update b b = L' * r(Iunmask); % update M if Lupdate M = L' * L; end % Check for stop button drawnow if get(S.corstop,'Value') dic.converged = 4; return end elseif cg.memsave == 1 % per dimension L matrix definition (reduced memory by factor Ndims but slower) % update status stat = get(S.corstatus,'String'); stat = [sprintf('computing L, M and b (%3d/%3d)',0,Ndims) ; stat]; set(S.corstatus,'String',stat);drawnow for i = 1:Ndims I = Idims{i}; idim = Idofdim(I); idof = Idofdof(I); if idim == 1 Li(:,1:cg.Nphi(i)) = repmat(gradx(Iunmask),1,cg.Nphi(i)) .* phi12(Iroi(Iunmask),idof); elseif idim == 2 Li(:,1:cg.Nphi(i)) = repmat(grady(Iunmask),1,cg.Nphi(i)) .* phi12(Iroi(Iunmask),idof); elseif idim == 3 Li(:,1:cg.Nphi(i)) = phi34(Iroi(Iunmask),idof); elseif idim == 4 Li(:,1:cg.Nphi(i)) = repmat(froi(Iunmask),1,cg.Nphi(i)) .* phi34(Iroi(Iunmask),idof); elseif idim == 5 Li(:,1:cg.Nphi(i)) = repmat(froi(Iunmask).^2,1,cg.Nphi(i)) .* phi34(Iroi(Iunmask),idof); elseif idim == 6 Li(:,1:cg.Nphi(i)) = repmat(froi(Iunmask).^3,1,cg.Nphi(i)) .* phi34(Iroi(Iunmask),idof); end % update b b(I) = Li(:,1:cg.Nphi(i))' * r(Iunmask); % Check for stop button drawnow if get(S.corstop,'Value') dic.converged = 4; return end if Lupdate for j = 1:Ndims J = Idims{j}; jdim = Idofdim(J); jdof = Idofdof(J); if jdim == 1 Lj(:,1:cg.Nphi(j)) = repmat(gradx(Iunmask),1,cg.Nphi(j)) .* phi12(Iroi(Iunmask),jdof); elseif jdim == 2 Lj(:,1:cg.Nphi(j)) = repmat(grady(Iunmask),1,cg.Nphi(j)) .* phi12(Iroi(Iunmask),jdof); elseif jdim == 3 Lj(:,1:cg.Nphi(j)) = phi34(Iroi(Iunmask),jdof); elseif jdim == 4 Lj(:,1:cg.Nphi(j)) = repmat(froi(Iunmask),1,cg.Nphi(j)) .* phi34(Iroi(Iunmask),jdof); elseif jdim == 5 Lj(:,1:cg.Nphi(j)) = repmat(froi(Iunmask).^2,1,cg.Nphi(j)) .* phi34(Iroi(Iunmask),jdof); elseif jdim == 6 Lj(:,1:cg.Nphi(j)) = repmat(froi(Iunmask).^3,1,cg.Nphi(j)) .* phi34(Iroi(Iunmask),jdof); end % update M M(I,J) = Li(:,1:cg.Nphi(i))' * Lj(:,1:cg.Nphi(j)); end end % update status stat{1} = sprintf('computing L, M and b (%3d/%3d)',i,Ndims); set(S.corstatus,'String',stat);drawnow % Check for stop button drawnow if get(S.corstop,'Value') dic.converged = 4; return end end elseif cg.memsave == 2 % per dof L matrix definition (reduced memory by factor Ndof but super slow) % update status stat = get(S.corstatus,'String'); stat = [sprintf('computing L, M and b (%3d/%3d)',0,Ndof) ; stat]; set(S.corstatus,'String',stat);drawnow for i = 1:Ndof idim = Idofdim(i); idof = Idofdof(i); if idim == 1 Li(:,1) = gradx(Iunmask) .* phi12(Iroi(Iunmask),idof); elseif idim == 2 Li(:,1) = grady(Iunmask) .* phi12(Iroi(Iunmask),idof); elseif idim == 3 Li(:,1) = phi34(Iroi(Iunmask),idof); elseif idim == 4 Li(:,1) = froi(Iunmask) .* phi34(Iroi(Iunmask),idof); elseif idim == 5 Li(:,1) = froi(Iunmask).^2 .* phi34(Iroi(Iunmask),idof); elseif idim == 6 Li(:,1) = froi(Iunmask).^3 .* phi34(Iroi(Iunmask),idof); end % update b b(i) = Li' * r(Iunmask); % Check for stop button drawnow if get(S.corstop,'Value') dic.converged = 4; return end if Lupdate for j = 1:Ndof jdim = Idofdim(j); jdof = Idofdof(j); if jdim == 1 Lj(:,1) = gradx(Iunmask) .* phi12(Iroi(Iunmask),jdof); elseif jdim == 2 Lj(:,1) = grady(Iunmask) .* phi12(Iroi(Iunmask),jdof); elseif jdim == 3 Lj(:,1) = phi34(Iroi(Iunmask),jdof); elseif jdim == 4 Lj(:,1) = froi(Iunmask) .* phi34(Iroi(Iunmask),jdof); elseif jdim == 5 Lj(:,1) = froi(Iunmask).^2 .* phi34(Iroi(Iunmask),jdof); elseif jdim == 6 Lj(:,1) = froi(Iunmask).^3 .* phi34(Iroi(Iunmask),jdof); end % update M M(i,j) = Li' * Lj; end end % update status stat{1} = sprintf('computing L, M and b (%3d/%3d)',i,Ndof); set(S.corstatus,'String',stat);drawnow % Check for stop button drawnow if get(S.corstop,'Value') dic.converged = 4; return end end end % update status stat = stat(2:end); set(S.corstatus,'String',stat);drawnow % Thikonov regularization % ================================= if Lupdate % get the eigenvectors of M eigval = eig(M); end if cg.tikhsteps == 0; alpha = 0; elseif it <= cg.tikhsteps alpha = cg.tikhpar(it)*max(eigval); elseif it > cg.tikhsteps alpha = cg.tikhpar(end)*max(eigval); end % create tikhonov matrix and right hand Mt = alpha * eye(Ndof); bt = alpha * (cg.p - p); % Solve dp % ================================= if usegpu dp = gpuArray.zeros(Ndof,1); else dp = zeros(Ndof,1); end % only solve for those dof which have support dp(Isup) = (M(Isup,Isup) + Mt(Isup,Isup)) \ (b(Isup) + bt(Isup)); % update p p = p + dp; % store results nb = norm(b(Isup) + bt(Isup))/Npx; ndp = norm(dp(Isup)); mr = mean(abs(r(Iunmask))) * 100; ndu = norm(du); if it == 1 dr = mr; else dr = mr - itstore(it-1).mr; end convcrit = [ndu ; nb ; ndp ; dr]; % check for divergence (dr should always be negative) if (it > 3) && (convcrit(4) > cordivtol) div = div + 1; else div = div - 0.5; end div = max([div 0]); % use gather to force all arrays to be CPU (instead of GPU) itstore(it).it = gather(it); itstore(it).mr = gather(mr); itstore(it).convcrit = gather(convcrit); itstore(it).p = gather(p); itstore(it).div = gather(div); itstore(it).tikhonov = gather(alpha); % status update str = sprintf('%3d, %10.3e, %10.3e, %10.3e, %10.3e, %4.1f, %3d',it,convcrit,div,sprs); statstr = appendstatus(statstr,str); if headlessmode headlessstatus(str); end % corstatus update stat = get(S.corstatus,'String'); stat = [sprintf('%2d,%9.2e,%13.6e,%4.1f',it,convcrit(cg.convparam),mr,div) ; stat]; set(S.corstatus,'String',stat);drawnow % check for convergence if (it > 2) && (abs(convcrit(cg.convparam)) < abs(cg.convcrit)) converged = 1; break end % check for max divergence if div >= cg.maxdiv converged = 2; break end % check for maxit if it >= cg.maxit converged = 3; break end % Check for continue button drawnow if get(S.corcontinue,'Value') converged = 4; set(S.corcontinue,'Value',0) drawnow break end % Check for stop button drawnow if get(S.corstop,'Value') converged = 5; return end end % debugging % assignin('base','M',M) % assignin('base','L',L) convstr{1,1} = 'converged'; convstr{2,1} = 'diverged'; convstr{3,1} = 'max. it.'; convstr{4,1} = 'continued'; convstr{5,1} = 'stopped'; % choose the best iteration if strcmp(cg.bestit,'residual') bestlist = [itstore.mr]; [bestlist, I] = sort(bestlist); bestit = I(1); updatebestit = 1; elseif strcmp(cg.bestit,'change in disp.') bestlist = [itstore.convcrit]; [bestlist, I] = sort(bestlist(1,:)); bestit = I(1); updatebestit = 1; elseif strcmp(cg.bestit,'right hand member') bestlist = [itstore.convcrit]; [bestlist, I] = sort(bestlist(2,:)); bestit = I(1); updatebestit = 1; elseif strcmp(cg.bestit,'update in dof') bestlist = [itstore.convcrit]; [bestlist, I] = sort(bestlist(3,:)); bestit = I(1); updatebestit = 1; elseif strcmp(cg.bestit,'change in residual') bestlist = [itstore.convcrit]; [bestlist, I] = sort(abs(bestlist(4,:))); bestit = I(1); updatebestit = 1; else bestit = it; updatebestit = 0; end % update displacement on best it if updatebestit p = itstore(bestit).p; % update displacement field U1 = reshape(phi12(Iroi,:) * p(Idims{1}),nroi,mroi); U2 = reshape(phi12(Iroi,:) * p(Idims{2}),nroi,mroi); if Ndims >= 3 U3 = reshape(phi34(Iroi,:) * p(Idims{3}),nroi,mroi); end if Ndims >= 4 U4 = reshape(phi34(Iroi,:) * p(Idims{4}),nroi,mroi); end if Ndims >= 5 U5 = reshape(phi34(Iroi,:) * p(Idims{5}),nroi,mroi); end if Ndims == 6 U6 = reshape(phi34(Iroi,:) * p(Idims{6}),nroi,mroi); end % update gtilde if usegpu gt = gpuArray(interp2(X,Y,gather(g),X(In,Im)+gather(U1),Y(In,Im)+gather(U2),'spline',0)) ; % correct the brightness q = gather(U3) + gather(U4).*gt + gather(U5).*gt.^2 + gather(U6).*gt.^3; else gt = interp2(X,Y,g,X(In,Im)+U1,Y(In,Im)+U2,'spline',0); % correct the brightness q = U3 + U4.*gt + U5.*gt.^2 + U6.*gt.^3; end % update residual r = froi - (gt + q); r(Imask) = 0; end % test memory availability if usegpu D.gpu = gpuDevice; free = D.gpu.FreeMemory; else free = memfree; end % status str = sprintf('%s, using iteration %d (free memory: %g Mb)',convstr{converged},bestit,round(free*1e-6)); statstr = appendstatus(statstr,str); if headlessmode headlessstatus(str); end stat = get(S.corstatus,'String'); stat = [sprintf('%s, using iteration %d',convstr{converged},bestit) ; stat]; set(S.corstatus,'String',stat);drawnow % update final liveview if cg.liveview >= 1 lview.it = it; lview.r = r; lview.U1 = U1(Iq); lview.U2 = U2(Iq); plotliveview(H,S,lview); end % info table Nit = it; itable = zeros(Nit,9); for k = 1:Nit itable(k,1) = cg.inc; itable(k,2) = cg.icg; itable(k,3) = k; itable(k,4) = Ndof; itable(k,5) = Npx; itable(k,6) = itstore(k).mr; itable(k,7:10) = itstore(k).convcrit; itable(k,11) = itstore(k).tikhonov; itable(k,12) = itstore(k).div; if k == bestit; itable(k,13) = converged; else itable(k,13) = 0; end end if cg.dimensions == 3 % 3D % define the z displacment as positive to the top U3 = -U3; end dic.itstore = itstore; dic.itable = itable; dic.p = p; dic.U1 = U1; dic.U2 = U2; if Ndims >= 3 dic.U3 = U3; end if Ndims >= 4 dic.U4 = U4; end if Ndims >= 5 dic.U5 = U5; end if Ndims == 6 dic.U6 = U6; end dic.froi = froi; dic.gt = gt; dic.xroi = xroi; dic.yroi = yroi; dic.r = r; dic.q = q; dic.In = In; dic.Im = Im; dic.Imask = Imask; dic.Iunmask = Iunmask; dic.statstr = statstr; dic.converged = converged; function [] = plotliveview(H,S,lview) D = guidata(H); % assignin('base','lview',lview); % plot image set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes7) colormap(D.gui.color.cmap) title(sprintf('residual [%%], inc %d, cg %d, it %d',lview.inc,lview.icg,lview.it)) hi = findobj(H,'Tag','cor_image'); if isempty(hi) set(gca,'NextPlot','replacechildren') imagesc(lview.xroi,lview.yroi,lview.r*100,'Parent',S.axes7,'cor_image'); set(gca,'color','k') xlabel('x [px]') ylabel('y [px]') set(gca,'ydir','reverse') daspect([1 1 1 ]) hc = colorbar; set(hc,'Xcolor',[0 0 0],'Ycolor',[0 0 0],'FontSize',D.gui.fontsize(3)) else set(hi,'CData',lview.r*100,'XData',lview.xroi([1,end]),'YData',lview.yroi([1,end])); end set(gca,'xlim',lview.xlim) set(gca,'ylim',lview.ylim) clim = mean(lview.r(:)) + [-3 3]*std(lview.r(:)); clim = clim*100; if clim(1) == clim(2) clim = clim(1) + abs(clim(1))*[-0.01 0.01]; end set(gca,'NextPlot','add'); hq = findobj(H,'Tag','cor_quiver'); if isempty(hq) hq = quiver(lview.X,lview.Y,lview.U1,lview.U2,0,'Tag','cor_quiver'); set(hq,'color',D.gui.color.fg); else set(hq,'XData',lview.X,'YData',lview.Y,'UData',lview.U1,'VData',lview.U2); end ht = findobj(H,'Tag','cor_text'); if isempty(ht) ht = text(0.02,0.02,sprintf('%d/%d',lview.inc,lview.Ninc),'units','normalized','Tag','cor_text'); set(ht,'color',D.gui.color.fg) set(ht,'FontSize',D.gui.fontsize(3)) set(ht,'FontWeight','bold') else set(ht,'String',sprintf('%d/%d',lview.inc,lview.Ninc)); end caxis(gather(clim)); drawnow
github
Jann5s/BasicGDIC-master
dlgposition.m
.m
BasicGDIC-master/lib_bgdic/dlgposition.m
285
utf_8
7d1818cd97469cfdc8b55857acdcffa3
% ================================================== function dlgpos = dlgposition(H) % helper function to get the center position for the dialog box, used for % inputdlgjn guipos = get(H,'Position'); xc = guipos(1) + 0.3*guipos(3); yc = guipos(2) + 0.8*guipos(4); dlgpos = [xc yc];
github
Jann5s/BasicGDIC-master
selectarea.m
.m
BasicGDIC-master/lib_bgdic/selectarea.m
26,621
utf_8
85e621954221c3a26ee5debe319d648b
function varargout = selectarea(varargin) % A = selectarea, allows the user to interactively draw a shape in the % current axes. The default shape is a rectangle. The shape control points % are returned in matrix A, which for the case of the rectangle are the % positions of two diagonally opposed corners, see more details below. % Control points are moved by dragging them to a new position. The shape % curve is finalized/confirmed by double clicking anywhere in the figure. % Right clicking anywhere in the figure will present a context menu where % for instance the line color can be changed. % % [A, P] = selectarea, also return a position matrix: P = [x(:), y(:)] % % A = selectarea(B), initializes the rectangle using the control points % defined in B % % A = selectarea(B,shape), where shape is any of: % 'Point' : draw a point. B = [x,y]; % 'Square' : draw a square from the center point and a second point % on the square. B = [xc,yc;x2,y2]; % 'Rectangle' : draw a rectangle using two corners as control points, % B = [x1,y1;x2,y2]; % 'Circle' : draw a circle from the center point and a second point % on the circle. B = [xc,yc;x2,y2]; % 'Ellipse' : draw an ellipse from the center point and a two points % on the ellipse. The first point defines the major radius % and the angle of the central ellipse axes, the second % point only defines the minor radius. % B = [xc,yc;x2,y2;x3,y3]; % 'Polyline' : draw a polyline, if the first and the last control points % coinside the polyline is closed (i.e. its a polygon) % B = [x1,y1;...;xn,yn]; % 'BSpline' : draw a bspline of order 3, if the first and the last % control points coinside the bspline is closed. % B = [x1,y1;...;xn,yn]; % % A = selectarea(B,'BSpline',p), draw a bspline of order p % % A = selectarea(B,'BSpline',phi), draw a bspline using the shape function % matrix phi (i.e. P = C*phi). phi should be of size = [N, NB], Here N is % the number of points on the bspline and NB the number of control points. % the the current handles ha = gca; hf = gcf; % raise the current figure figure(hf); set(hf,'CurrentAxes',ha); % define a list of line colors linecol = {'r','Red';'g','Green';'b','Blue';'c','Cyan';'m','Magenta';'y','Yellow';'k','Black';'w','White'}; linewidth = [2,0.5]; markersize = 12; % number of points for most shapes UserData.N = 64; % default bspline order p = 3; % initiate the arguments xlim = get(ha,'xlim'); ylim = get(ha,'ylim'); rng(1) = diff(xlim); rng(2) = diff(ylim); if nargin == 0 B = [xlim(1)+0.1*rng(1), ylim(1)+0.1*rng(2); xlim(1)+0.9*rng(1), ylim(1)+0.9*rng(2)]; shape = 'rectangle'; elseif nargin == 1 B = varargin{1}; shape = 'rectangle'; elseif nargin == 2 B = varargin{1}; shape = varargin{2}; elseif nargin == 3 B = varargin{1}; shape = varargin{2}; p = varargin{3}; end % get the control point position data UserData.Closed = false; if strcmpi(shape,'square') shapefun = @ShapeSquare; B = B(1:2,:); elseif strcmpi(shape,'rectangle') shapefun = @ShapeRectangle; B = B(1:2,:); B = [mean(B) ; B]; elseif strcmpi(shape,'circle') shapefun = @ShapeCircle; B = B(1:2,:); elseif strcmpi(shape,'ellipse') shapefun = @ShapeEllipse; B = B(1:3,:); elseif strcmpi(shape,'polyline') shapefun = @ShapePolyLine; if hypot(B(end,1)-B(1,1),B(end,2)-B(1,2)) < mean(rng)*1e-6 UserData.Closed = true; B = B(1:end-1,:); else UserData.Closed = false; end % add the central rigid body motion point B = [mean(B) ; B]; elseif strcmpi(shape,'bspline') shapefun = @ShapeBSpline; if numel(p) == 1 % create the bspline shape functions Nb = size(B,1); if Nb < (p+1) error('Too few control points (%d) for p=%d order b-spline',Nb,p) end t = linspace(0,1,10*Nb-1); if hypot(B(end,1)-B(1,1),B(end,2)-B(1,2)) < mean(rng)*1e-6 % Closed curve UserData.Closed = true; knots = linspace(0,1,Nb); dk = diff(knots(1:2)); knots = [-(fliplr(dk:dk:p*dk)), knots, 1+(dk:dk:p*dk)]; phi = bsplines(t,knots,p); for k = 1:p phi(:,k) = phi(:,k)+phi(:,end-(p-k)); end phi = phi(:,1:Nb-1); B = B(1:end-1,:); else % Open Curve UserData.Closed = false; Nk = Nb - p + 1; knots = [zeros(1,p), linspace(0,1,Nk), ones(1,p)] ; phi = bsplines(t,knots,p); end UserData.phi = phi; UserData.phiprovided = false; else % shape functions are provided UserData.phi = p; UserData.phiprovided = true; end if size(B,1) ~= size(UserData.phi,2) error('the number of control points (%d) does not match the basis (phi)') end % add the central rigid body motion point B = [mean(B) ; B]; elseif strcmpi(shape,'point') shapefun = @ShapePoint; else shapefun = @ShapeRectangle; B = B(1:2,:); % add the central rigid body motion point B = [mean(B) ; B]; end % Store the current figure properties UserData.Pointer = get(gcf,'Pointer'); UserData.NextPlot = get(ha,'NextPlot'); % if an image is used, it normally prevents the context menu, this fixed % that hi = findobj(hf,'Type','image'); set(hi,'HitTest','off'); % set some figure properties set(hf,'Pointer','crosshair'); set(ha,'NextPlot','Add') set(ha,'Clipping','off'); set(hi,'Clipping','off'); % Plot the shape for the first time % --------------------------------------- % Compute the shape coordinates [x, y, B] = shapefun(B,UserData); set(0,'CurrentFigure',hf); set(hf,'CurrentAxes',ha); % the background line h1 = plot(x,y,'-','linewidth',linewidth(1)); % the foreground line h2 = plot(x,y,'-','linewidth',linewidth(2)); % the control points if UserData.Closed h3 = plot(B([2:end, 2],1),B([2:end, 2],2),'s'); else h3 = plot(B(2:end,1),B(2:end,2),'s'); end if strcmpi(shape,'bspline') set(h3,'LineStyle','--') end % the rigid body motion point h4 = plot(B(1,1),B(1,2),'o'); set([h3,h4],'MarkerSize',markersize); set([h1;h2;h3;h4],'Clipping','off') changecolor([],[],h1,h2,h3,h4,linecol(6,:)) % Store data which is used by the subfunctions UserData.B = B; UserData.h1 = h1; UserData.h2 = h2; UserData.h3 = h3; UserData.h4 = h4; UserData.ha = ha; UserData.hf = hf; UserData.shape = shape; UserData.shapefun = shapefun; UserData.Rsel = 0.02*mean(rng); UserData.lim = [xlim; ylim]; UserData.CurrentHandle = []; UserData.p = p; % setup the figure such that it will allow user control set(gcf,'UserData',UserData,... 'WindowButtonMotionFcn',@freemove,... 'WindowButtonDownFcn',@selecthandle,... 'WindowButtonUpFcn',@confirmhandle,... 'KeyPressFcn',@keyPressFcn,... 'DoubleBuffer','on'); % define the context menu c = uicontextmenu; set([ha;hf;h1;h2;h3;h4],'UIContextMenu',c); % Create top-level menu item uimenu('Parent',c,'Label','Confirm Selection','Callback',{@confirmselect,gcf}); m = uimenu('Parent',c,'Label','Line Color'); for k = 1:8 uimenu('Parent',m,'Label',linecol{k,2},'Callback',{@changecolor,h1,h2,h3,h4,linecol(k,:)}); end % add control points option if strcmpi(shape,'polyline') || strcmpi(shape,'bspline') && ~UserData.phiprovided uimenu('Parent',c,'Label','Add Control Point','Callback',{@addcontrolpoint,gcf}); uimenu('Parent',c,'Label','Del Control Point','Callback',{@delcontrolpoint,gcf}); uimenu('Parent',c,'Label','Open/Close Curve','Callback',{@openclosecurve,gcf}); end % Wait until the user has finished % ----------------------------------------------------- waitfor(h4) % Finalize after the user has finished % ----------------------------------------------------- if ~ishandle(hf) % if the user closed the figure varargout{1} = []; varargout{2} = []; return end % cleanup/restore figure properties set(ha,'NextPlot',UserData.NextPlot); set(hf,'Pointer',UserData.Pointer) set(hf,'WindowButtonMotionFcn','','WindowButtonDownFcn','','WindowButtonUpFcn','','DoubleBuffer','off'); set([ha,hf],'UIContextMenu',''); set(hi,'HitTest','on'); set(ha,'Clipping','on'); set(hi,'Clipping','on'); % get the latest state of the curve UserData = get(gcf,'UserData'); B = UserData.B; if nargout == 2 [x, y, B] = shapefun(B,UserData); end % Remove the extra center point from the control points list (if required) if strcmpi(shape,'rectangle') B = B(2:3,:); elseif strcmpi(shape,'polyline') B = B(2:end,:); elseif strcmpi(shape,'bspline') B = B(2:end,:); end % Get the function outputs if nargout >= 1 varargout{1} = B; end if nargout == 2 varargout{2} = [x(:), y(:)]; end % ===================================================== function [x, y, B] = ShapeSquare(B,UserData) % distance to the center R = hypot(B(2,2)-B(1,2),B(2,1)-B(1,1)); % angle (with horizon) a = atan2(B(2,2)-B(1,2),B(2,1)-B(1,1)); % make a rotated square Ix = [-1, 1, 1, -1, -1]; Iy = [-1, -1, 1, 1, -1]; x = B(1,1) + R*Ix.*cos(a) - R*Iy.*sin(a); y = B(1,2) + R*Ix.*sin(a) + R*Iy.*cos(a); % fix the control points B(2,1) = B(1,1) + R*cos(a); B(2,2) = B(1,2) + R*sin(a); % ===================================================== function [x, y, B] = ShapeRectangle(B,UserData) x = B([2,3,3,2,2],1); y = B([2,2,3,3,2],2); B(1,:) = mean(B(2:3,:)); % ===================================================== function [x, y, B] = ShapeCircle(B,UserData) a = linspace(0,2*pi,UserData.N); R = hypot(B(1,1)-B(2,1),B(1,2)-B(2,2)); x = B(1,1) + R.*cos(a); y = B(1,2) + R.*sin(a); % ===================================================== function [x, y, B] = ShapeEllipse(B,UserData) a = hypot(B(2,1)-B(1,1),B(2,2)-B(1,2)); b = hypot(B(3,1)-B(1,1),B(3,2)-B(1,2)); phi = atan2(B(2,2)-B(1,2),B(2,1)-B(1,1)) ; % ellipse angle t = linspace(0,2*pi,UserData.N); x = B(1,1) + a.*cos(t).*cos(phi) - b.*sin(t).*sin(phi); y = B(1,2) + a.*cos(t).*sin(phi) + b.*sin(t).*cos(phi); B(2,1) = B(1,1) + a*cos(phi); B(2,2) = B(1,2) + a*sin(phi); B(3,1) = B(1,1) + b*cos(phi+0.5*pi); B(3,2) = B(1,2) + b*sin(phi+0.5*pi); % ===================================================== function [x, y, B] = ShapePolyLine(B,UserData) if UserData.Closed x = B([2:end, 2],1); y = B([2:end ,2],2); else x = B(2:end,1); y = B(2:end,2); end B(1,:) = mean(B(2:end,:)); % ===================================================== function [x, y, B] = ShapeBSpline(B,UserData) x = UserData.phi*B(2:end,1); y = UserData.phi*B(2:end,2); B(1,:) = mean(B(2:end,:)); % ===================================================== function [x, y, B] = ShapePoint(B,UserData) x = B(1,1); y = B(1,2); % ===================================================== function openclosecurve(hObject, varargin) H = varargin{2}; UserData = get(H,'UserData'); B = UserData.B; B = B(2:end,:); if UserData.Closed == true UserData.Closed = false; if strcmpi(UserData.shape,'bspline') B = [B ; B(1,:)]; end else UserData.Closed = true; end if strcmpi(UserData.shape,'bspline') p = UserData.p; Nb = size(B,1); t = linspace(0,1,10*Nb-1); if UserData.Closed % Closed curve knots = linspace(0,1,Nb); dk = diff(knots(1:2)); knots = [-(fliplr(dk:dk:p*dk)), knots, 1+(dk:dk:p*dk)]; phi = bsplines(t,knots,p); for k = 1:p phi(:,k) = phi(:,k)+phi(:,end-(p-k)); end phi = phi(:,1:Nb-1); B = B(1:end-1,:); else % Open Curve Nk = Nb - p + 1; knots = [zeros(1,p), linspace(0,1,Nk), ones(1,p)] ; phi = bsplines(t,knots,p); end UserData.phi = phi; end B = [mean(B) ; B]; % update the curve coordinates [x, y, B] = UserData.shapefun(B,UserData); % update the userdata for possible changes in B UserData.B = B; set(H,'UserData',UserData); % change the coordinates of the plotted curves set(UserData.h1,'XData',x,'YData',y); set(UserData.h2,'XData',x,'YData',y); if UserData.Closed set(UserData.h3,'XData',B([2:end, 2],1),'YData',B([2:end, 2],2)); else set(UserData.h3,'XData',B(2:end,1),'YData',B(2:end,2)); end set(UserData.h4,'XData',B(1,1),'YData',B(1,2)); % ===================================================== function addcontrolpoint(hObject, varargin) H = varargin{2}; UserData = get(H,'UserData'); % get the current location p = get(UserData.ha,'CurrentPoint'); p = p(1,1:2); B = UserData.B; B = B(2:end,:); N = size(B,1); % distance from the mouse to each control point D = hypot(B(1:end,1)-p(1),B(1:end,2)-p(2)); % find the two closest control points [D, I] = sort(D); if UserData.Closed == true % was the mouse closer to the next point or the previous point if I(1) == 1 % the previous and next node Ip = [N, 1+1]; % compare the distance to the line L1 = B([I(1) Ip(1)],:); d1 = linepointdistance(L1,p); L2 = B([I(1) Ip(2)],:); d2 = linepointdistance(L2,p); % pick the one with the minimum difference if d1 < d2 B = [B(1:N,:) ; p]; else B = [B(1,:) ; p ; B(2:end,:)]; end elseif I(1) == N % the previous and next node Ip = [N-1, 1]; % compare the distance to the line L1 = B([I(1) Ip(1)],:); d1 = linepointdistance(L1,p); L2 = B([I(1) Ip(2)],:); d2 = linepointdistance(L2,p); % pick the one with the minimum difference if d1 < d2 B = [B(1:N-1,:) ; p ; B(N,:)]; else B = [B(1:N,:) ; p]; end else Ip = [I(1)-1, I(1)+1]; % compare the distance to the line L1 = B([I(1) Ip(1)],:); d1 = linepointdistance(L1,p); L2 = B([I(1) Ip(2)],:); d2 = linepointdistance(L2,p); % pick the one with the minimum difference if d1 < d2 B = [B(1:I(1)-1,:) ; p ; B(I(1):end,:)]; else B = [B(1:I(1),:) ; p ; B(I(1)+1:end,:)]; end end if strcmpi(UserData.shape,'bspline') B = [B ; B(1,:)]; end else if I(1) == 1 % the first point, inject a new point inbetween 1+1 and 1+2 B = [B(1,:) ; p ; B(2:end,:)]; elseif I(1) == N % the last point, inject a new point inbetween N and N+1 B = [B(1:N-1,:) ; p ; B(N,:)]; else % was the mouse closer to the next point or the previous point Ip = [I(1)-1, I(1)+1]; % compare the distance to the line L1 = B([I(1) Ip(1)],:); d1 = linepointdistance(L1,p); L2 = B([I(1) Ip(2)],:); d2 = linepointdistance(L2,p); % pick the one with the minimum difference if (d1 < d2) B = [B(1:I(1)-1,:) ; p ; B(I(1):end,:)]; else B = [B(1:I(1),:) ; p ; B(I(1)+1:end,:)]; end end end if strcmpi(UserData.shape,'bspline') p = UserData.p; Nb = size(B,1); t = linspace(0,1,10*Nb-1); if UserData.Closed % Closed curve knots = linspace(0,1,Nb); dk = diff(knots(1:2)); knots = [-(fliplr(dk:dk:p*dk)), knots, 1+(dk:dk:p*dk)]; phi = bsplines(t,knots,p); for k = 1:p phi(:,k) = phi(:,k)+phi(:,end-(p-k)); end phi = phi(:,1:Nb-1); B = B(1:end-1,:); else % Open Curve Nk = Nb - p + 1; knots = [zeros(1,p), linspace(0,1,Nk), ones(1,p)] ; phi = bsplines(t,knots,p); end UserData.phi = phi; end B = [mean(B) ; B]; % update the curve coordinates [x, y, B] = UserData.shapefun(B,UserData); % update the userdata for possible changes in B UserData.B = B; set(H,'UserData',UserData); % change the coordinates of the plotted curves set(UserData.h1,'XData',x,'YData',y); set(UserData.h2,'XData',x,'YData',y); if UserData.Closed set(UserData.h3,'XData',B([2:end, 2],1),'YData',B([2:end, 2],2)); else set(UserData.h3,'XData',B(2:end,1),'YData',B(2:end,2)); end set(UserData.h4,'XData',B(1,1),'YData',B(1,2)); % ===================================================== function d = linepointdistance(L,P) L2 = (L(2,1)-L(1,1))^2 + (L(2,2)-L(1,2))^2; if L2 == 0 d = hypot(L(1,1)-P(1),L(1,2)-P(2)); return end t = ((P(1) - L(1,1)) * (L(2,1) - L(1,1)) + (P(2) - L(1,2)) * (L(2,2) - L(1,2))) / L2; if (t < 0) d = hypot(L(1,1)-P(1),L(1,2)-P(2)); elseif (t > 1) d = hypot(L(2,1)-P(1),L(2,2)-P(2)); else d = abs( (L(2,2)-L(1,2))*P(1) - (L(2,1)-L(1,1))*P(2) + L(2,1)*L(1,2) - L(1,1)*L(2,2)); d = d / sqrt( (L(2,1)-L(1,1))^2 + (L(2,2)-L(1,2))^2 ); end % ===================================================== function delcontrolpoint(hObject, varargin) H = varargin{2}; UserData = get(H,'UserData'); % get the current location p = get(UserData.ha,'CurrentPoint'); p = p(1,1:2); B = UserData.B; R = UserData.Rsel; B = B(2:end,:); % distance from the mouse to each control point D = hypot(B(:,1)-p(1),B(:,2)-p(2)); if ~any(D <= R) return end [D, I] = min(abs(D-R)); N = length(I); if UserData.Closed == true if any(I == [1, N]) B = B(2:end,:); B(end,:) = B(1,:); else B(I,:) = []; end if strcmpi(UserData.shape,'bspline') B = [B ; B(1,:)]; end else B(I,:) = []; end if strcmpi(UserData.shape,'bspline') p = UserData.p; Nb = size(B,1); t = linspace(0,1,10*Nb-1); if UserData.Closed % Closed curve knots = linspace(0,1,Nb); dk = diff(knots(1:2)); knots = [-(fliplr(dk:dk:p*dk)), knots, 1+(dk:dk:p*dk)]; phi = bsplines(t,knots,p); for k = 1:p phi(:,k) = phi(:,k)+phi(:,end-(p-k)); end phi = phi(:,1:Nb-1); B = B(1:end-1,:); else % Open Curve Nk = Nb - p + 1; knots = [zeros(1,p), linspace(0,1,Nk), ones(1,p)] ; phi = bsplines(t,knots,p); end UserData.phi = phi; end B = [mean(B) ; B]; % update the curve coordinates [x, y, B] = UserData.shapefun(B,UserData); % update the userdata for possible changes in B UserData.B = B; set(H,'UserData',UserData); % change the coordinates of the plotted curves set(UserData.h1,'XData',x,'YData',y); set(UserData.h2,'XData',x,'YData',y); if UserData.Closed set(UserData.h3,'XData',B([2:end, 2],1),'YData',B([2:end, 2],2)); else set(UserData.h3,'XData',B(2:end,1),'YData',B(2:end,2)); end set(UserData.h4,'XData',B(1,1),'YData',B(1,2)); % ===================================================== function freemove(hObject, varargin) % this function controls what happens when nothing is selected. This % function merely indicates when the mouse is close enough UserData = get(hObject,'UserData'); p = get(UserData.ha,'CurrentPoint'); p = p(1,1:2); B = UserData.B; R = UserData.Rsel; % distance from the mouse to each control point D = hypot(B(:,1)-p(1),B(:,2)-p(2)); if any(D <= R) % the mouse is hovering a control point set(UserData.hf,'Pointer','fleur'); else % the mouse is not hovering a control point set(UserData.hf,'Pointer','crosshair'); end % ===================================================== function movehandle(hObject, varargin) % this function is used after clicking on a control point. It allows the % modification of a shape. UserData = get(hObject,'UserData'); if isempty(UserData.CurrentHandle) return end p = get(UserData.ha,'CurrentPoint'); p = p(1,1:2); B = UserData.B; I = UserData.CurrentHandle; if I == 1; % the first control point is always rigid body motion, i.e. move all % control points with the same motion U = p - B(1,:); B(:,1) = B(:,1) + U(1); B(:,2) = B(:,2) + U(2); else % any other control point is moved individually B(I,:) = p; end % update the curve coordinates [x, y, B] = UserData.shapefun(B,UserData); % update the userdata for possible changes in B UserData.B = B; set(hObject,'UserData',UserData); % change the coordinates of the plotted curves set(UserData.h1,'XData',x,'YData',y); set(UserData.h2,'XData',x,'YData',y); if UserData.Closed set(UserData.h3,'XData',B([2:end, 2],1),'YData',B([2:end, 2],2)); else set(UserData.h3,'XData',B(2:end,1),'YData',B(2:end,2)); end set(UserData.h4,'XData',B(1,1),'YData',B(1,2)); % ===================================================== function selecthandle(hObject, varargin) % what to do on a mouse click when no control point is currently selected % (but the mouse can be hovering one) UserData = get(hObject,'UserData'); m_type = get(hObject, 'selectionType'); if strcmp(m_type, 'open') % Detect a double click, exit the tool confirmselect([],[],hObject); end p = get(UserData.ha,'CurrentPoint'); p = p(1,1:2); B = UserData.B; R = UserData.Rsel; % distance from the mouse to each control point D = hypot(B(:,1)-p(1),B(:,2)-p(2)); if any(D <= R) % the mouse is hovering a control point % find out which control point I = find(D <= R,1); if numel(I) == 1 UserData.CurrentHandle = I; else [D, I] = min(abs(D-R)); UserData.CurrentHandle = I; end else % the mouse is not hovering a control point UserData.CurrentHandle = []; end % update the userdata set(hObject,'UserData',UserData); if isempty(UserData.CurrentHandle) return end % change to control point moving mode set(hObject,'WindowButtonMotionFcn',@movehandle) % ===================================================== function confirmhandle(hObject, varargin) % what to do on a mouse click when a control point is currently selected m_type = get(hObject, 'selectionType'); if strcmp(m_type, 'open') % Detect a double click, exit the tool confirmselect([],[],hObject); end % change to handle free mode set(hObject,'WindowButtonMotionFcn',@freemove) % ===================================================== function changecolor(varargin) % change the line color of the curve h1 = varargin{3}; h2 = varargin{4}; h3 = varargin{5}; h4 = varargin{6}; col = varargin{7}; set(h1,'Color',col{1}); set(h3,'Color',col{1}); set(h4,'Color',col{1}); if any(col{1} == 'wygc') % for light colors use a black background set(h2,'Color','k'); set(h3,'MarkerFaceColor','k'); set(h4,'MarkerFaceColor','k'); else % for dark colors use a white background set(h2,'Color','w'); set(h3,'MarkerFaceColor','w'); set(h4,'MarkerFaceColor','w'); end % ===================================================== function confirmselect(varargin) % stop the interactive mode (i.e. delete the plot h4). hf = varargin{3}; UserData = get(hf,'UserData'); delete(UserData.h1) delete(UserData.h2) delete(UserData.h3) delete(UserData.h4) % ===================================================== function keyPressFcn(varargin) H = varargin{1}; evnt = varargin{2}; UserData = get(H,'UserData'); if isempty(evnt.Modifier) evnt.Modifier{1} = ''; end % fprintf('Key: (%s) %s\n',[evnt.Modifier{:}],evnt.Key); stride = 0.05; if any(strcmp(evnt.Modifier,'control')) stride = 0.01; elseif strcmp(evnt.Modifier{1},'shift') stride = 0.1; end dx = stride*diff(UserData.lim(1,:)); dy = stride*diff(UserData.lim(2,:)); B = UserData.B; U = [0, 0]; if strcmpi(evnt.Key,'uparrow') U = [0, dy]; elseif strcmpi(evnt.Key,'downarrow') U = [0, -dy]; elseif strcmpi(evnt.Key,'leftarrow') U = [-dx, 0]; elseif strcmpi(evnt.Key,'rightarrow') U = [dx, 0]; end if all(U == 0) return end if strcmpi(get(UserData.ha,'ydir'),'reverse') U(2) = -U(2); end if strcmpi(get(UserData.ha,'xdir'),'reverse') U(1) = -U(1); end % apply displacement B(:,1) = B(:,1) + U(1); B(:,2) = B(:,2) + U(2); % update the curve coordinates [x, y, B] = UserData.shapefun(B,UserData); % update the userdata for possible changes in B UserData.B = B; set(H,'UserData',UserData); % change the coordinates of the plotted curves set(UserData.h1,'XData',x,'YData',y); set(UserData.h2,'XData',x,'YData',y); if UserData.Closed set(UserData.h3,'XData',B([2:end, 2],1),'YData',B([2:end, 2],2)); else set(UserData.h3,'XData',B(2:end,1),'YData',B(2:end,2)); end set(UserData.h4,'XData',B(1,1),'YData',B(1,2)); % ===================================================== function phi = bsplines(x,knots,Np) % compute bspline shape functions for a given coordinate vector x, knot % vector knots and bspline order p. Based on the Cox-de Boor recursion % formula. n = length(x); Ni = length(knots); x = x(:); % starting with degree zero p = 0; % number of basis-functions Nn = Ni-(p+1); % initiate matrix for basis functions phi = zeros(n,Nn); % Loop over the knots. This defines which coordinates belong to which knot % section. It is important to use each coordinate only once, and to include % the edges of the domain in the correct knot sections. for i = 1:Nn if i == (Nn-Np) % for the knot on the right edge of x, include the point on the % right knot I = find(x >= knots(i) & x <= knots(i+1)); elseif i > (Nn-Np) % for the next knots, exclude the point on left knot, include the % point on the right knot I = find(x > knots(i) & x <= knots(i+1)); else % for all other knots, include the point on the left knot but not % on the right knot I = find(x >= knots(i) & x < knots(i+1)); end % set the function to zero phi(I,i) = 1; end % Subsequent orders % ============= for p = 1:Np % calculate the number of shape functions for this degree Nn = Ni-(p+1); % store the previous phi as phi1 phi1 = phi; % initiate the current phi (every point supports exactly p+1 shapes if % no multiplicity knots are defined, so this is a worst case scenario) phi = zeros(n,Nn); % forloop over the knots for i = 1:Nn if knots(i+p) == knots(i) % if first term == zero (double knot on right side) phi(:,i) = phi1(:,i+1).* (knots(i+p+1) - x ) ./ ( knots(i+p+1) - knots(i+1) ); elseif knots(i+p+1) == knots(i+1) % if second term is zero (double knot on left side) phi(:,i) = phi1(:,i) .* ( x - knots(i) ) ./ ( knots(i+p) - knots(i) ) ; else % for all other knots phi(:,i) = phi1(:,i) .* ( x - knots(i) ) ./ ( knots(i+p) - knots(i) ) + ... phi1(:,i+1).* (knots(i+p+1) - x ) ./ ( knots(i+p+1) - knots(i+1) ); end end end phi = sparse(phi);
github
Jann5s/BasicGDIC-master
listdlgjn.m
.m
BasicGDIC-master/lib_bgdic/listdlgjn.m
3,399
utf_8
e49f003ed0221e6de496be1aafb9e7e4
function [Selection, Ok] = listdlgjn(Prompt,Title,List,SelMode,Position) % function similar to listdlg, except simpler and with the option to % position it. % [selection,ok] = listdlg(... % 'Name','Select strain definition',... % 'PromptString','Select strain definition',... % 'SelectionMode','Single',... % 'ListSize',[180 100],... % 'ListString',str); if strcmpi(SelMode,'Single') Max = 1; else Max = 2; end if ~iscell(Prompt) Prompt = {Prompt}; end fontsize = 12; L = length(List); N = length(Prompt) + L; M = max(cellfun('length',Prompt)); Figheight = N*2.0*fontsize + 3.5*fontsize; Figwidth = M*1.2*fontsize + 2*fontsize; Figpos(3:4) = [Figwidth Figheight]; Figpos(1:2) = Position - 0.5*Figpos(3:4); FigColor=get(0,'DefaultUicontrolBackgroundColor'); WindowStyle='modal'; Interpreter='none'; Resize = 'off'; H = dialog( ... 'Visible' ,'on' , ... 'Name' ,Title , ... 'Pointer' ,'arrow' , ... 'Units' ,'pixels' , ... 'UserData' ,'Cancel' , ... 'Tag' ,Title , ... 'HandleVisibility' ,'callback' , ... 'Color' ,FigColor , ... 'NextPlot' ,'add' , ... 'WindowStyle' ,WindowStyle, ... 'Resize' ,Resize, ... 'Position' ,Figpos ... ); xpos = linspace(0.03,0.98,3); ypos = linspace(0.05,0.98,N+3); height = 1.4*mean(diff(ypos)); width = 0.9*mean(diff(xpos)); % Create title uicontrol('String',Title,... 'Style','text',... 'HorizontalAlignment','center',... 'units','normalized',... 'Position',[xpos(1) ypos(L+2)+0.02 xpos(end)-xpos(1) (0.96-ypos(L+2))],... 'FontSize',fontsize,... 'Parent',H); % list box h = uicontrol('String',List,... 'Style','listbox',... 'units','normalized',... 'BackgroundColor','w',... 'Max',Max,... 'Position',[xpos(1) ypos(3) xpos(end)-xpos(1) ypos(L+2)-ypos(3)],... 'FontSize',fontsize,... 'Parent',H,... 'call',{@pressListbox,H}); uicontrol('String','Ok',... 'ToolTipString','confirm input',... 'Style','pushbutton',... 'units','normalized',... 'Position',[xpos(1) ypos(1) width height],... 'FontSize',fontsize,... 'Parent',H,... 'call',{@pressOk,H,h}); uicontrol('String','Cancel',... 'ToolTipString','cancel input',... 'Style','pushbutton',... 'units','normalized',... 'Position',[xpos(2) ypos(1) width height],... 'FontSize',fontsize,... 'Parent',H,... 'call',{@pressCancel,H,h}); set(H,'KeyPressFcn',{@doFigureKeyPress,H,h}) uiwait(H) if ishandle(H) Selection = guidata(H); delete(H); else Selection = []; end if isempty(Selection) Ok = 0; else Ok = 1; end function doFigureKeyPress(obj, evd, H ,h) %#ok switch(evd.Key) case {'return','space'} pressOk([],[],H,h); case {'escape'} pressCancel([],[],H,h); end function pressOk(varargin) H = varargin{3}; h = varargin{4}; selection = get(h,'Value'); guidata(H,selection); uiresume(H); function pressCancel(varargin) H = varargin{3}; selection=[]; guidata(H,selection); uiresume(H); function pressListbox(varargin) h = varargin{1}; H = varargin{3}; if get(h,'UserData') == get(h,'Value') selection = get(h,'Value'); guidata(H,selection); uiresume(H); end set(h,'UserData',get(h,'Value'));
github
Jann5s/BasicGDIC-master
plotres.m
.m
BasicGDIC-master/lib_bgdic/plotres.m
11,258
utf_8
67c0af40cd9424e6f1508799401fd51a
% ================================================== function [] = plotres(varargin) % compute result figure H = varargin{3}; S = guihandles(H); D = guidata(H); if isfield(D,'outputfile') % headless mode return end if ~isfield(D,'files') return; end if ~isfield(D,'cor') return; end if ~isfield(D.cor,'converged') set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes8) cla return; end if length(varargin) == 4 rescompute([],[],H) end if ~isfield(D,'res') || isempty(D.res) Prompt = 'Select strain definition'; Title = Prompt; SelMode = 'Single'; List = get(S.resstraindef,'String'); [selection,ok] = listdlgjn(Prompt,Title,List,SelMode,dlgposition(H)); if ok == 1 set(S.resstraindef,'Value',selection) % ask for this step rescompute([],[],H) D = guidata(H); else return end end res = D.res; cor = D.cor; % options dimensions = get(S.dicdimensions,'Value')+1; % i.e. 2 or 3 for 2D or 3D % get the slider positions (and put the rounded values back to the gui) soften = get(S.ressofteningslider,'Value'); soften = round(soften*100)/100; set(S.ressofteningslider,'Value',soften); set(S.ressoftening,'String',num2str(soften)); alpha = get(S.resalphaslider,'Value'); alpha = round(alpha*100)/100; set(S.resalphaslider,'Value',alpha); set(S.resalpha,'String',num2str(alpha)); ascale = get(S.resarrowscaleslider,'Value'); ascale = round(ascale*100)/100; set(S.resarrowscaleslider,'Value',ascale); set(S.resarrowscale,'String',num2str(ascale)); % get the popupmenu values str = get(S.resunderlay,'String'); underlay = str{get(S.resunderlay,'Value')}; str = get(S.resoverlay,'String'); overlay = str{get(S.resoverlay,'Value')}; str = get(S.resarrows,'String'); arrows = str{get(S.resarrows,'Value')}; % get the pixel size and unit pixelsize = str2double(get(S.respixelsize,'String')); str = get(S.resunit,'String'); unit = str{get(S.resunit,'Value')}; % image size and increment number n = D.files(1).size(1); m = D.files(1).size(2); xlim = [1 m]; ylim = [1 n]; inc = str2double(get(S.resid,'String')); Ninc = length(cor); Ncg = 4; if inc == 0 inc = 1; set(S.resid,'String','1') set(S.resslider,'Value',1) end if inc > Ninc set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes8) cla set(gca,'color','none') return end if isempty(D.res(inc).Exx) set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes8) cla set(gca,'color','none') return end if D.cor(inc).done ~= Ncg set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes8) cla set(gca,'color','none') return end % plot underlay % =============================== if strcmp(underlay,'f') A = D.files(1).image; A = 255*(A - min(A(:))) / (max(A(:)) - min(A(:))); x = 1:m; y = 1:n; elseif strcmp(underlay,'g') A = D.files(inc+1).image; A = 255*(A - min(A(:))) / (max(A(:)) - min(A(:))); x = 1:m; y = 1:n; elseif strcmp(underlay,'gtilde') A = cor(inc).froi - cor(inc).r; A = 255*(A - min(A(:))) / (max(A(:)) - min(A(:))); x = cor(inc).xroi; y = cor(inc).yroi; elseif strcmp(underlay,'r') A = cor(inc).r; A = 255*(A - min(A(:))) / (max(A(:)) - min(A(:))); x = cor(inc).xroi; y = cor(inc).yroi; elseif strcmp(underlay,'none') A = ones(n,m)*NaN; x = 1:m; y = 1:n; end % set unit x = x * pixelsize; y = y * pixelsize; set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes8) xlabel(sprintf('x [%s]',unit)) ylabel(sprintf('y [%s]',unit)) set(gca,'xlim',pixelsize*xlim) set(gca,'ylim',pixelsize*ylim) if ~strcmp(underlay,'none') % store the underlay as RGB (to fake grayvalue image) to allow using a % second colormap RGB(:,:,1) = uint8(soften*A);%+(1-soften)*255; RGB(:,:,2) = uint8(soften*A);%+(1-soften)*255; RGB(:,:,3) = uint8(soften*A);%+(1-soften)*255; else % white background (single pixel rgb image) RGB = ones(1,1,3); end % plot the RGB hi = findobj(H,'Tag','res_image'); if isempty(hi) set(gca,'NextPlot','replacechildren') imagesc(x,y,RGB,'Parent',S.axes8,'Tag','res_image'); set(gca,'ydir','reverse') daspect([1 1 1 ]) else set(hi,'CData',RGB,'XData',x([1,end]),'YData',y([1,end])); end % plot overlay % =============================== plotoverlay = true; xroi = cor(inc).xroi; yroi = cor(inc).yroi; nroi = length(yroi); mroi = length(xroi); % set pixel size xroi = xroi * pixelsize; yroi = yroi * pixelsize; [Xroi, Yroi] = meshgrid(xroi,yroi); Zroi = 0.5*ones(size(Xroi)); U1 = pixelsize*cor(inc).U1; U2 = pixelsize*cor(inc).U2; if isfield(cor,'U3') && ~isempty(cor(inc).U3) U3 = cor(inc).U3; else U3 = zeros(nroi,mroi); end if isfield(cor,'U4') && ~isempty(cor(inc).U4) U4 = cor(inc).U4; else U4 = zeros(nroi,mroi); end if isfield(cor,'U5') && ~isempty(cor(inc).U5) U5 = cor(inc).U5; else U5 = zeros(nroi,mroi); end if isfield(cor,'U6') && ~isempty(cor(inc).U6) U6 = cor(inc).U6; else U6 = zeros(nroi,mroi); end if strcmp(overlay,'U1 (x)') B = pixelsize*cor(inc).U1; cstr = sprintf('U1 [%s]',unit); elseif strcmp(overlay,'U2 (y)') B = pixelsize*cor(inc).U2; cstr = sprintf('U2 [%s]',unit); elseif strcmp(overlay,'U3 (z or Constant)') B = U3; if dimensions == 3 % 3D cstr = sprintf('U3 [%s]',unit); else B = B * 100; cstr = 'U3 (constant relaxation) [%]'; end elseif strcmp(overlay,'U4 (Linear)') B = U4 * 100; cstr = 'U4 (linear relaxation) [%]'; elseif strcmp(overlay,'U5 (Quadratic)') B = U5 * 100; cstr = 'U5 (quadratic relaxation) [%]'; elseif strcmp(overlay,'U6 (Cubic)') B = U6 * 100; cstr = 'U6 (cubic relaxation) [%]'; elseif strcmp(overlay,'strain xx') B = res(inc).Exx; cstr = '\epsilon_{xx} [-]'; elseif strcmp(overlay,'strain yy') B = res(inc).Eyy; cstr = '\epsilon_{yy} [-]'; elseif strcmp(overlay,'strain xy') B = res(inc).Exy; cstr = '\epsilon_{xy} [-]'; elseif strcmp(overlay,'strain yx') B = res(inc).Eyx; cstr = '\epsilon_{yx} [-]'; elseif strcmp(overlay,'strain maj') B = res(inc).Emaj; cstr = '\epsilon_{maj.} [-]'; elseif strcmp(overlay,'strain min') B = res(inc).Emin; cstr = '\epsilon_{min.} [-]'; elseif strcmp(overlay,'strain eq.') B = res(inc).Eeq; cstr = '\epsilon_{eq.} [-]'; elseif strcmp(overlay,'r') B = cor(inc).r; B = B*100; cstr = 'r (residual) [%]'; elseif strcmp(overlay,'q') gt = cor(inc).froi - cor(inc).r; B = U3 + gt.*U4 + gt.^2.*U5 + gt.^3.*U6; B = B*100; cstr = 'q (combined brightness correction) [%]'; elseif strcmp(overlay,'none') plotoverlay = true; B = ones(nroi,mroi)*NaN; cstr = ''; end if ~exist('B','var') || isempty(B) % if for some reason the field is undefined show zeros B = ones(nroi,mroi)*NaN; end B(cor(inc).Imask) = NaN; B = double(B); % assignin('base','B',B) clim = [-1, 1]; if plotoverlay % color limits clim1 = str2double(get(S.resclim1,'String')); clim2 = str2double(get(S.resclim2,'String')); if all([clim1 clim2] == 0); maxB = max(max(abs(B(~isnan(B))))); if isempty(maxB) maxB = 1; end clim = [-1 1] * maxB; else clim = [clim1 clim2]; end if clim(1) > clim(2) clim = clim([2 1]); end if clim(1) == clim(2); clim = clim(1) + [-0.1 0.1]; end clim = gather(clim); % prepare the axes set(0,'CurrentFigure',H) colormap(D.gui.color.cmapoverlay) set(H,'CurrentAxes',S.axes8) title(cstr,'FontSize',D.gui.fontsize(4)); view(2) hp = findobj(H,'Tag','res_overlay'); if isempty(hp) set(gca,'NextPlot','add') hc = colorbar; set(hc,'Xcolor',[0 0 0],'Ycolor',[0 0 0],'FontSize',D.gui.fontsize(3)) % plot the overlay if strcmp(underlay,'g') hp = surf(Xroi+U1,Yroi+U2,Zroi,B); else hp = surf(Xroi,Yroi,Zroi,B); end set(hp,'FaceAlpha',alpha,'EdgeColor','none','Tag','res_overlay') else if strcmp(underlay,'g') set(hp,'CData',B,'XData',Xroi+U1,'YData',Yroi+U2,'FaceAlpha',alpha); else set(hp,'CData',B,'XData',Xroi,'YData',Yroi,'FaceAlpha',alpha); end end else set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes8) hp = findobj(H,'Tag','res_overlay'); if ~isempty(hp) set(hp,'CData',NaN,'XData',x([1,end]),'YData',y([1,end])); end end ht = findobj(H,'Tag','res_text'); if isempty(ht) ht = text(0.02,0.02,sprintf('%d/%d',inc,Ninc),'units','normalized','Tag','res_text'); set(ht,'color',D.gui.color.fg) set(ht,'FontSize',D.gui.fontsize(4)) set(ht,'FontWeight','bold') else set(ht,'String',sprintf('%d/%d',inc,Ninc)); end % plot arrows % =============================== % number of arrows (in x and y) Nq = 15; % create a grid Iqn = round(linspace(2,nroi-1,Nq)); Iqm = round(linspace(2,mroi-1,Nq)); % select only those locations which are not masked [IQm, IQn] = meshgrid(Iqm,Iqn); Iq = sub2ind([nroi mroi],IQn(:),IQm(:)); Iq = intersect(Iq,cor(inc).Iunmask); Xroiq = Xroi(Iq); Yroiq = Yroi(Iq); % get the displacements U1q = pixelsize*cor(inc).U1(Iq); U2q = pixelsize*cor(inc).U2(Iq); if strcmp(arrows,'U (x,y)') C11 = ascale*U1q; C12 = ascale*U2q; C21 = nan(length(Iq),1); C22 = nan(length(Iq),1); Xq = Xroiq; Yq = Yroiq; elseif strcmp(arrows,'strain (xx,yy)') C11 = ascale*100*res(inc).Exx(Iq); C12 = zeros(length(Iq),1); C21 = zeros(length(Iq),1); C22 = ascale*100*res(inc).Eyy(Iq); if strcmp(underlay,'g') Xq = Xroiq+U1q; Yq = Yroiq+U2q; else Xq = Xroiq; Yq = Yroiq; end elseif strcmp(arrows,'strain (min,maj)') C11 = ascale*100*res(inc).Emin(Iq) .* res(inc).Q11(Iq); C12 = ascale*100*res(inc).Emin(Iq) .* res(inc).Q12(Iq); C21 = ascale*100*res(inc).Emaj(Iq) .* res(inc).Q21(Iq); C22 = ascale*100*res(inc).Emaj(Iq) .* res(inc).Q22(Iq); if strcmp(underlay,'g') Xq = Xroiq+U1q; Yq = Yroiq+U2q; else Xq = Xroiq; Yq = Yroiq; end elseif strcmp(arrows,'none') C11 = nan(length(Iq),1); C12 = nan(length(Iq),1); C21 = nan(length(Iq),1); C22 = nan(length(Iq),1); Xq = Xroiq; Yq = Yroiq; end % Force the arrows to be on-top of the overlay Zq = ones(length(Iq),1); Uz = zeros(length(Iq),1); hq1 = findobj(H,'Tag','res_vectors1'); hq2 = findobj(H,'Tag','res_vectors2'); if isempty(hq1) hq1 = NaN; end if isempty(hq2) hq2 = NaN; end hq = [hq1,hq2]; if ~strcmp(arrows,'none') if any(~ishandle(hq)) set(gca,'NextPlot','add') hq = quiver3(Xq,Yq,Zq,C11,C12,Uz,0,'Tag','res_vectors1'); set(hq,'Color',D.gui.color.fg); set(hq,'LineWidth',0.5); hq = quiver3(Xq,Yq,Zq,C21,C22,Uz,0,'Tag','res_vectors2'); set(hq,'Color',D.gui.color.fg2); set(hq,'LineWidth',0.5); else set(hq,'XData',Xq(:),'YData',Yq(:)); set(hq(1),'UData',C11(:),'VData',C12(:)); set(hq(2),'UData',C21(:),'VData',C22(:)); end else if all(ishandle(hq)) delete(hq) end end set(S.secind8,'BackgroundColor',D.gui.color.on) % set color limits last caxis(clim) drawnow
github
Jann5s/BasicGDIC-master
msgdlgjn.m
.m
BasicGDIC-master/lib_bgdic/msgdlgjn.m
2,001
utf_8
6d2d010713116624bb8bd97508c82699
function msgdlgjn(Message,Position) % function similar to msgbox, except simpler and with the option to % position it. if ~iscell(Message) Message = {Message}; end Title = 'basic gdic message'; fontsize = 12; N = length(Message); M = max(cellfun('length',Message)); Figheight = N*2.5*fontsize + 3.0*fontsize; Figwidth = M*0.8*fontsize + 2*fontsize; Figpos(3:4) = [Figwidth Figheight]; Figpos(1:2) = Position - 0.5*Figpos(3:4); FigColor=get(0,'DefaultUicontrolBackgroundColor'); WindowStyle='modal'; Interpreter='none'; Resize = 'off'; H = dialog( ... 'Visible' ,'on' , ... 'Name' ,Title , ... 'Pointer' ,'arrow' , ... 'Units' ,'pixels' , ... 'UserData' ,'Cancel' , ... 'Tag' ,Title , ... 'HandleVisibility' ,'callback' , ... 'Color' ,FigColor , ... 'NextPlot' ,'add' , ... 'WindowStyle' ,WindowStyle, ... 'Resize' ,Resize, ... 'Position' ,Figpos ... ); xpos = linspace(0.08,0.92,4); ypos(1) = 0.08; ypos(2) = ypos(1) + 0.05 + 2/(2*N+2); height = 1.8/(1.5*N+2); width = 0.9*mean(diff(xpos)); % Create title uicontrol('String',Message,... 'Style','text',... 'HorizontalAlignment','left',... 'units','normalized',... 'Position',[xpos(1) ypos(2) xpos(end)-xpos(1) 1-(ypos(2)+0.06)],... 'FontSize',fontsize,... 'Parent',H); uicontrol('String','Ok',... 'ToolTipString','Confirm',... 'Style','pushbutton',... 'units','normalized',... 'Position',[xpos(3) ypos(1) width height],... 'FontSize',fontsize,... 'Parent',H,... 'call',{@pressOk,H}); set(H,'KeyPressFcn',{@doFigureKeyPress,H}) uiwait(H) if ishandle(H) delete(H); end function doFigureKeyPress(obj, evd, H) %#ok switch(evd.Key) case {'return','space'} pressOk([],[],H); case {'escape'} pressOk([],[],H); end function pressOk(varargin) H = varargin{3}; uiresume(H);
github
Jann5s/BasicGDIC-master
plotcor.m
.m
BasicGDIC-master/lib_bgdic/plotcor.m
3,866
utf_8
5a05dbac63927d0117d348f71264b1ce
% ================================================== function [] = plotcor(H) % plot the current image to figpanel7 S = guihandles(H); D = guidata(H); if isfield(D,'outputfile') % headless mode return end % test if there are images if ~isfield(D,'files') return; end n = D.files(1).size(1); m = D.files(1).size(2); Nim = length(D.files); % get current image (i.e. slider position) inc = str2double(get(S.corid,'String')); id = inc + 1; x = 1:m; y = 1:n; xlim = x([1 end]); ylim = y([1 end]); if isfield(D,'cor') && ... (inc <= length(D.cor)) && ... (inc > 0) && ... isfield(D.cor,'r') && ... ~isempty(D.cor(inc).r) && ... ~isempty(D.cor(inc).done) && ... (D.cor(inc).done > 0) cor = D.cor; % plot image set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes7) title(sprintf('residual [%%], inc %d',inc)) colormap(D.gui.color.cmap) hi = findobj(H,'Tag','cor_image'); if isempty(hi) set(gca,'nextplot','replacechildren') imagesc(cor(inc).xroi,cor(inc).yroi,cor(inc).r*100,'parent',S.axes7,'Tag','cor_image'); set(gca,'nextplot','add'); set(gca,'color','k') set(gca,'ydir','reverse') set(gca,'xlim',xlim) set(gca,'ylim',ylim) daspect([1 1 1]) xlabel('x [px]') ylabel('y [px]') hc = colorbar; set(hc,'Xcolor',[0 0 0],'Ycolor',[0 0 0],'FontSize',D.gui.fontsize(3)) else set(hi,'CData',cor(inc).r*100,'XData',cor(inc).xroi([1,end]),'YData',cor(inc).yroi([1,end])); set(gca,'xlim',xlim) set(gca,'ylim',ylim) end clim = mean(cor(inc).r(:)) + [-3 3]*std(cor(inc).r(:)); clim = clim*100; caxis(gather(clim)); % Plot the quiver (arrows) Nq = D.gui.ini.cornquiver.value; nroi = length(cor(inc).yroi); mroi = length(cor(inc).xroi); Iqn = round(linspace(2,nroi-1,Nq)); Iqm = round(linspace(2,mroi-1,Nq)); [IQm, IQn] = meshgrid(Iqm,Iqn); Iq = sub2ind([nroi mroi],IQn(:),IQm(:)); Iq = intersect(Iq,cor(inc).Iunmask); [X, Y] = meshgrid(cor(inc).xroi,cor(inc).yroi); hq = findobj(H,'Tag','cor_quiver'); if isempty(hq) hq = quiver(X(Iq),Y(Iq),cor(inc).U1(Iq),cor(inc).U2(Iq),0,'Tag','cor_quiver'); set(hq,'color',D.gui.color.fg); else set(hq,'XData',X(Iq),'YData',Y(Iq),'UData',cor(inc).U1(Iq),'VData',cor(inc).U2(Iq)); end else % plot image title(sprintf('image %d',id)) set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes7) hi = findobj(H,'Tag','cor_image'); colormap(D.gui.color.cmap) if isempty(hi) set(gca,'nextplot','replacechildren') imagesc(x,y,D.files(id).image,'parent',S.axes7,'Tag','cor_image'); set(gca,'nextplot','add'); set(gca,'color','k') set(gca,'ydir','reverse') set(gca,'ydir','reverse') set(gca,'xlim',xlim) set(gca,'ylim',ylim) daspect([1 1 1]) xlabel('x [px]') ylabel('y [px]') else set(hi,'CData',D.files(id).image,'XData',x([1,end]),'YData',y([1,end])); end clim(1) = min(D.files(id).image(:)); clim(2) = max(D.files(id).image(:)); caxis(clim); hc = colorbar; set(hc,'Xcolor',[0 0 0],'Ycolor',[0 0 0],'FontSize',D.gui.fontsize(3)) hq = findobj(H,'Tag','cor_quiver'); if ~isempty(hq) X = get(hq,'XData'); Y = get(hq,'YData'); U = get(hq,'UData'); U(:) = NaN; set(hq,'XData',X,'YData',Y,'UData',U,'VData',U); end end ht = findobj(H,'Tag','cor_text'); if isempty(ht) ht = text(0.02,0.02,sprintf('%d/%d',id,Nim-1),'units','normalized','Tag','cor_text'); set(ht,'color',D.gui.color.fg) set(ht,'FontSize',D.gui.fontsize(3)) set(ht,'FontWeight','bold') else set(ht,'String',sprintf('%d/%d',id,Nim-1)); end drawnow
github
Jann5s/BasicGDIC-master
jncurvemap.m
.m
BasicGDIC-master/lib_bgdic/jncurvemap.m
3,730
utf_8
0d9e58bfff2c12eb9dcb21e6c94cb168
function colors = jncurvemap(N,varargin) % colors = jncurvemap(N) % % creates a cell-array of colors of length N. Note, this is not the same as % the typical matrices obtained from a colormap type command (e.g. jet). % the colors cell-array can be directly applied to a list of handles. % % example: % x = linspace(0,1,100); % N = 20; % a = 1:N; % for k = 1:N % hold on % h(k) = plot(x,x.^a(k)); % end % colors = jncurvemap(N); % set(h,{'color'},colors) % % optional: % colors = jncurvemap(N,[H1 H2],[S1 S2],[L1 L2]) % where ?1 is the start point (i.e. first color) and ?2 the end point, % H is the hue (i.e. color): % H=0 -> red, % H=0.3 -> green, % H=0.6 -> blue, % H=1 -> red, % S is the saturation (i.e. color intensity) % S=0 -> no color -> grayscale, % S=1 -> max color -> full color intensity, % L is the lightness (i.e. brightness) % S=0 -> black, % S=1 -> white, % default values are % colors = jncurvemap(N,[0.9 0.3],[0.7 0.7],[0.2 0.4]) % % Note, in general 0 <= H,S,L <= 1, however for H > 1 the colors are looped % around, making it possible to go around the color circle boundaries, or % even loop around more than once. % defaults H1 = 0.9; H2 = 0.3; S1 = 0.7; S2 = 0.7; L1 = 0.2; L2 = 0.4; if nargin == 4 H1 = varargin{1}(1); H2 = varargin{1}(2); S1 = varargin{2}(1); S2 = varargin{2}(2); L1 = varargin{3}(1); L2 = varargin{3}(2); elseif nargin == 0 % give a small demo help jncurvemap figure; N = 20; x = linspace(0,1,50); a = linspace(0.5,1,N); for k = 1:N hold on h(k) = plot(x,a(k)*sin(pi*x),'o-','linewidth',2); end colors = jncurvemap(N); set(h,{'color'},colors); error('please specify how many colors to produce: colors = jncurvemap(N)') end % create color spaces H = linspace(H1,H2,N); S = linspace(S1,S2,N); L = linspace(L1,L2,N); % loop around for H > 1; H = H + floor(min(H)); H = H - floor(H); % create color matrix HSL = [H(:) S(:) L(:)]; % convert to RGB RGB = hsl2rgb(HSL); % format the output colors = RGB; colors = mat2cell(colors,ones(1,N),3); function rgb=hsl2rgb(hsl) %Converts Hue-Saturation-Luminance Color value to Red-Green-Blue Color %value % %Usage % RGB = hsl2rgb(HSL) % % converts HSL, a M X 3 color matrix with values between 0 and 1 % into RGB, a M X 3 color matrix with values between 0 and 1 % %See also rgb2hsl, rgb2hsv, hsv2rgb %Suresh E Joel, April 26,2003 if nargin<1, error('Too few arguements for hsl2rgb'); return; elseif nargin>1, error('Too many arguements for hsl2rgb'); return; end; if max(max(hsl))>1 | min(min(hsl))<0, error('HSL values have to be between 0 and 1'); return; end; for i=1:size(hsl,1), if hsl(i,2)==0,%when sat is 0 rgb(i,1:3)=hsl(i,3);% all values are same as luminance end; if hsl(i,3)<0.5, temp2=hsl(i,3)*(1+hsl(i,2)); else temp2=hsl(i,3)+hsl(i,2)-hsl(i,3)*hsl(i,2); end; temp1=2*hsl(i,3)-temp2; temp3(1)=hsl(i,1)+1/3; temp3(2)=hsl(i,1); temp3(3)=hsl(i,1)-1/3; for j=1:3, if temp3(j)>1, temp3(j)=temp3(j)-1; elseif temp3(j)<0, temp3(j)=temp3(j)+1; end; if 6*temp3(j)<1, rgb(i,j)=temp1+(temp2-temp1)*6*temp3(j); elseif 2*temp3(j)<1, rgb(i,j)=temp2; elseif 3*temp3(j)<2, rgb(i,j)=temp1+(temp2-temp1)*(2/3-temp3(j))*6; else rgb(i,j)=temp1; end; end; end; rgb=round(rgb.*100000)./100000; %Sometimes the result is 1+eps instead of 1 or 0-eps instead of 0 ... so to %get rid of this I am rounding to 5 decimal places)
github
Jann5s/BasicGDIC-master
plotpattern.m
.m
BasicGDIC-master/lib_bgdic/plotpattern.m
4,157
utf_8
637528aa28d3964a571b484d51abf745
% ================================================== function [] = plotpattern(H) % plot funtion for the evaluated pattern S = guihandles(H); D = guidata(H); if isfield(D,'outputfile') % headless mode return end if ~isfield(D,'files') return; end % hide the ACF contour delete(findobj(H,'Tag','pat_contour')); Nim = length(D.files); % get current frame id = str2double(get(S.patid,'String')); n = D.files(1).size(1); m = D.files(1).size(2); A = D.files(id).image; hi = findobj(H,'Tag','pat_image'); if isempty(hi) % plot the pattern colormap(D.gui.color.cmap) set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes2) set(gca,'NextPlot','replacechildren') imagesc(A,'Parent',S.axes2,'Tag','pat_image'); xlabel('x [px]') ylabel('y [px]') title(sprintf('image:%d name:%s',id,D.files(id).name),'Interpreter','none') set(gca,'ydir','reverse') set(gca,'xlim',[1,m]) set(gca,'ylim',[1,n]) daspect([1 1 1 ]) else set(H,'CurrentAxes',S.axes2) set(hi,'CData',A,'XData',[1,m],'YData',[1,n]); title(sprintf('image:%d name:%s',id,D.files(id).name),'Interpreter','none') set(gca,'xlim',[1,m]) set(gca,'ylim',[1,n]) end ht = findobj(H,'Tag','pat_text'); if isempty(ht) ht = text(0.02,0.02,sprintf('%d/%d',id,Nim),'units','normalized','Tag','pat_text'); set(ht,'color',D.gui.color.fg) set(ht,'FontSize',D.gui.fontsize(4)) set(ht,'FontWeight','bold') else set(ht,'String',sprintf('%d/%d',id,Nim)); end % History Plot if strcmp(D.files(id).class,'uint8') bins = (2^8)-1; elseif strcmp(D.files(id).class,'uint16') bins = (2^16)-1; else bins = (2^8)-1; end A = D.files(id).image; set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes2hist) cla(S.axes2hist) set(gca,'NextPlot','replacechildren') hist(A(:),bins); % If ROI is set % =============================== if isfield(D,'roi') % plot the evaluation area roi = D.roi; FV.Vertices = [roi([1 2 2 1])',roi([3 3 4 4])']; FV.Faces = [1 2 3 4]; set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes2) hp = findobj(H,'Tag','pat_roi'); if isempty(hp) set(gca,'NextPlot','add') hp = patch(FV,'EdgeColor',D.gui.color.fg,'FaceColor','none','LineWidth',D.gui.linewidth,'Tag','pat_roi'); else set(hp,'Vertices',FV.Vertices); end end % If evaluation is done % =============================== if ~isfield(D,'pateval') return; end if length(D.pateval) < id return; end if isempty(D.pateval(id).acf) delete(findobj(H,'Tag','pat_contours')); delete(findobj(H,'Tag','pat_boxes')); return; end % plot subset circles subset = D.pateval(id).subset; subsetedge = D.pateval(id).subsetedge; subsetsize = hypot(mean(diff(D.pateval(id).subsetedge.X)),mean(diff(D.pateval(id).subsetedge.Y))); % (the data only contains half the contour) Z = [subset.Z; subset.Z]; T = [subset.T; subset.T+pi]; [Np, Nsub] = size(Z); X = repmat(subset.xc(:)',Np,1) + Z .* cos(T); Y = repmat(subset.yc(:)',Np,1) + Z .* sin(T); % disable ugly contours I = (max(abs(subset.Z)) > 0.4*subsetsize); Y(:,I) = NaN; set(0,'CurrentFigure',H) set(H,'CurrentAxes',S.axes2) set(gca,'NextPlot','Add'); hc = findobj(H,'Tag','pat_contours'); if isempty(hc) plot(X,Y,'Color',D.gui.color.fg,'LineWidth',0.5,'Tag','pat_contours') else for k = 1:Nsub set(hc(k),'XData',X(:,k),'YData',Y(:,k)); end end % plot subset edges [X, Y] = meshgrid(subsetedge.X,subsetedge.Y); % create the connectivity Nn = numel(X); [n,m] = size(X); Ne = (n-1)*(m-1); In = reshape(1:Nn,n,m); Ie = reshape(1:Ne,n-1,m-1); conn = zeros(Ne,4); for ki = 1:n-1 for kj = 1:m-1 ke = Ie(ki,kj); con = In(ki:ki+1,kj:kj+1); conn(ke,:) = con([1 2 4 3]); end end FV.Vertices = [X(:),Y(:)]; FV.Faces = conn; hb = findobj(H,'Tag','pat_boxes'); if isempty(hc) patch(FV,'FaceColor','None','EdgeColor',D.gui.color.fg,'LineWidth',0.5,'Tag','pat_boxes'); else set(hb,'Vertices',FV.Vertices,'Faces',FV.Faces); end % update the title title('Correlation radius per subset (averaged over all directions)') clim(1) = min(A(:)); clim(2) = max(A(:)); caxis(clim); drawnow
github
Jann5s/BasicGDIC-master
plotacf.m
.m
BasicGDIC-master/lib_bgdic/plotacf.m
2,204
utf_8
208c5e0b57d76dea733cba55213db15c
% ================================================== function [] = plotacf(H) % plot function for the evaluated autocorrelation function D = guidata(H); S = guihandles(H); id = str2double(get(S.patid,'String')); if isfield(D,'outputfile') % headless mode return end if ~isfield(D,'files') return; end Nim = length(D.files); if ~isfield(D,'pateval') return; end if length(D.pateval) < id return; end if isempty(D.pateval(id).acf) return; end % hide the Pattern stuff delete(findobj(H,'Tag','pat_contours')); delete(findobj(H,'Tag','pat_boxes')); delete(findobj(H,'Tag','pat_roi')); % get the acf acf = D.pateval(id).acf; ux = D.pateval(id).ux; uy = D.pateval(id).uy; zeta = D.pateval(id).zeta; theta = D.pateval(id).theta; hi = findobj(H,'Tag','pat_image'); if isempty(hi) % plot the acf set(0,'CurrentFigure',H) colormap(D.gui.color.cmap) set(H,'CurrentAxes',S.axes2) set(gca,'NextPlot','replacechildren') hi = imagesc(ux,uy,acf,'Parent',S.axes2,'Tag','pat_image'); colorbar xlabel('ux [px]') ylabel('uy [px]') set(gca,'ydir','reverse') set(gca,'xlim',3*D.pateval(id).zetamean*[-1,1]) set(gca,'ylim',3*D.pateval(id).zetamean*[-1,1]) daspect([1 1 1 ]) else set(H,'CurrentAxes',S.axes2) set(hi,'CData',acf,'XData',ux([1,end]),'YData',uy([1,end])); set(gca,'xlim',3*D.pateval(id).zetamean*[-1,1]) set(gca,'ylim',3*D.pateval(id).zetamean*[-1,1]) caxis('auto'); end ht = findobj(H,'Tag','pat_text'); if isempty(ht) ht = text(0.02,0.02,sprintf('%d/%d',id,Nim),'units','normalized','Tag','pat_text'); set(ht,'color',D.gui.color.fg) set(ht,'FontSize',D.gui.fontsize(4)) set(ht,'FontWeight','bold') else set(ht,'String',sprintf('%d/%d',id,Nim)); end % plot the contour (the data only contains half the contour) zeta = [zeta; zeta]; theta = [theta ; theta+pi]; X = zeta.*cos(theta); Y = zeta.*sin(theta); hc = findobj(H,'Tag','pat_contour'); if isempty(hc) set(gca,'NextPlot','add') plot(X,Y,'Color',D.gui.color.fg,'LineWidth',D.gui.linewidth,'Tag','pat_contour') else set(hc,'XData',X,'YData',Y); end % update the title title('auto-correlation function with correlation contour')
github
ganlubbq/matlab_beam_doa-master
beampattern.m
.m
matlab_beam_doa-master/Beam and Post/beampattern.m
5,347
utf_8
b8dcfd082d676e6799f69fb494f49279
function beampattern(beam_nr,phi_d,mue,mics,fs,varargin) % beampattern(beam_nr,phi_d,mue,mics,fs,sim,phi_n) % Plots the Beampattern of a 1-dimensional Array and the frequency response % at a defined angle, as well as the frequncy response for small % perturbations imposed to mic positions % beam_nr % phi_d % mue % mics % fs % sim % phi_n % you can choose between the following beamformers % 'DSB' ... Delay&Sum-Beamformer % 'SDB' ... Superdirective Beamformer % default beam_nr = 'SDB'; % angle to TDOA % for the regularization of Coherence Matrix Gamma % mue in dB; default mue = -20 % microphone positons; default load mics_8xh.mat % sampling frequency in Hz; default fs = 16000 (16kHz) % use simulated coherence function or sinc-function for % Gamma; default sim = 'sinc' % 'incoh' ............. incoherent Noisefield % 'sinc' .............. Sinc-Function % 'bessel' ............ Bessel-Function % 'zero' .............. puts a Zero at the angle % specified by phi_n % angle for the plotted frequency response; if sim = 'zero' % phi_n is the angle of the specified zero % used functions: mvdr.m if nargin>=7 phi_n = varargin{2}; end if nargin>=6 sim = varargin{1}; end if nargin<6 sim = 'sinc'; end if nargin<5 fs = 16000; end if nargin<4 load mics_8xh.mat; end if nargin<3 help beampattern return; end % Parameters theta_d = 90; % elvation angle to direction of arrival (fixed) % Check microphone position matrix [K,Dim] = size(mics); if (Dim < 2) | (K < 1) error('bad matrix of microphine coordinates'); end % Calculate mue if mue ~= 0 mue = 10^(mue/10); end %Calc. of angles in rad theta_r = theta_d(:).' * pi / 180; phi_r = phi_d(:).' * pi / 180; phi_n = phi_n(:).' * pi / 180; % Calculate time alignment vector ed = [sin(theta_r).*cos(phi_r); sin(theta_r).*sin(phi_r)]; Rc = mics*ed; % Define Matrix of the micorphone distances xc = mics(:,1); xc = xc(:,ones(K,1)); dR = (xc-xc.'); % Define Frequency vector if fs <= 12000 f = linspace(0,3400,120); else f = linspace(0,6800,240); end Nf = length(f); % Calculate Coherencefunction for l = 1:Nf switch sim case 'incoh' % Calc. coherencefunction for an incoherent noisefield Gamma_const = diag(ones(1,K)); case 'bessel' % Calc. coherencefunction for a zylindrical isotropic noisefield beta = 2*pi*f(l)/340; Gamma_dum = besselj(0,beta*dR); case 'sinc' % Calc. coherencefunction for a diffuse noisefield beta = 2*f(l)/340; Gamma_dum = sinc(beta*dR); case 'zero' % Calc. coherencefunction for a coherent noisefield (interferer noise from angle phi_n) beta = 2*pi*f(l)/340; Gamma_real = cos(beta*cos(phi_n)*dR); Gamma_imag = -sin(beta*cos(phi_n)*dR); Gamma_dum = (Gamma_real + j*Gamma_imag); end if strcmp(sim,'zero') | strcmp(sim,'bessel') | strcmp(sim,'sinc') % regularization of the coherence matrix Gamma_const = tril(Gamma_dum,-1)./(1 + mue) + diag(diag(Gamma_dum)) + ... triu(Gamma_dum,1)./(1 + mue); end Gamma(:,:,l) = Gamma_const; end % Calculate Beampattern phi_wav_d = [(-180):1:(180)]; % angle vector phi_wav = phi_wav_d(:).' * pi / 180; ed_wav = [sin(theta_r).*cos(phi_wav); sin(theta_r).*sin(phi_wav)]; Rc_wav = mics*ed_wav; for l = 1:Nf % Calc. beamformer coefficients and steering vector for each angle and frequency [W(:,l),dum] = mvdr(Rc,Gamma(:,:,l),f(l),beam_nr); beta_wav = 2*pi*f(l)/340; d = exp(-j * beta_wav *Rc_wav); % Calc. gain for each angle and frequency H = abs(W(:,l)'*d).^2; HdB = max(-25,10*log10(H + eps)); H_log(:,l) = HdB; end % Plot beampattern figure,surf(f,phi_wav_d,H_log); axis tight set(gca,'TickDir','out'); set(gca,'YTick',[-180:45:180]); if fs <= 12000 set(gca,'XTick',[100;1000;2000;3000;3400]) set(gca,'XTickLabel',{'100';'1000';'2000';'3000';'3400'}) else set(gca,'XTick',[100;1000;2000;3000;4000;5000;6000;6800]) set(gca,'XTickLabel',{'100';'1000';'2000';'3000';'4000';'5000';'6000';'6800'}) end colorbar('YLim',[-25 max(max(H_log))]) view([0,90]); box on shading interp ylabel('\theta in Grad'); xlabel('Frequenz [Hz]'); % Calculate frequency response if strcmp(sim,'zero') | ~isstr(sim) phi_freq = phi_n; else phi_freq = phi_r; end figurebackcolor = 'black'; Hf = calc_freq_resp(mics,W,theta_r,phi_n,f,fs); HfdB = max(-100,10*log10(Hf + eps)); % repeat for small perturbations imposed to mic positions delta = 0.001; % standard deviation in m r = mics + delta*randn(size(mics)); Hr = calc_freq_resp(r,W,theta_r,phi_n,f); HrdB = max(-100,10*log10(Hr + eps)); % Plot frequency response pos = [0.045 0.01 0.4 0.37]; fp4 = figure('numbertitle','off','name','Frequency domain',... 'Units','normal','Position',pos); colordef(fp4,figurebackcolor); plot(f,HfdB,f,HrdB); grid on; xlabel('f in Hz'); ylabel('magnitude in dB'); title('frequency responses of ideal (y), and perturbated array (m)'); % ------------------------------------------------------------------------- % Calc. frequency response end function Hf = calc_freq_resp(mics,W,theta_r,phi_r,f) beta = (2*pi*f/340); ed = [sin(theta_r).*cos(phi_r); sin(theta_r).*sin(phi_r)]; % Calc. of Constraint Matrix d = exp(-1i*(mics*ed)*beta); Hf = abs(diag(W'*d)).^2; end
github
ganlubbq/matlab_beam_doa-master
istft.m
.m
matlab_beam_doa-master/STFT analysis - synthesis/istft.m
1,814
utf_8
c64b6ca4cb5da6f329e8441ffea1f9c3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Inverse Short-Time Fourier Transform % % with MATLAB Implementation % % % % Author: M.Sc. Eng. Hristo Zhivomirov 12/26/13 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [x, t] = istft(stft, h, nfft, fs) % function: [x, t] = myistftfun(stft, wlen, h, wlen) % stft - STFT matrix (time across columns, freq across rows) % h - hop size % nfft - number of FFT points % fs - sampling frequency, Hz % x - signal in the time domain % t - time vector, s % estimate the length of the signal coln = size(stft, 2); xlen = nfft + (coln-1)*h; x = zeros(1, xlen); % form a periodic hamming window win = hamming(nfft, 'periodic'); % perform IFFT and weighted-OLA if rem(nfft, 2) % odd nfft excludes Nyquist point for b = 0:h:(h*(coln-1)) % extract FFT points X = stft(:, 1 + b/h); X = [X; conj(X(end:-1:2))]; % IFFT xprim = real(ifft(X)); % weighted-OLA x((b+1):(b+nfft)) = x((b+1):(b+nfft)) + (xprim.*win)'; end else % even nfft includes Nyquist point for b = 0:h:(h*(coln-1)) % extract FFT points X = stft(:, 1+b/h); X = [X; conj(X(end-1:-1:2))]; % IFFT xprim = real(ifft(X)); % weighted-OLA x((b+1):(b+nfft)) = x((b+1):(b+nfft)) + (xprim.*win)'; end end W0 = sum(win.^2); % find W0 x = x.*h/W0; % scale the weighted-OLA % calculate the time vector actxlen = length(x); % find actual length of the signal t = (0:actxlen-1)/fs; % generate time vector end
github
ganlubbq/matlab_beam_doa-master
stft.m
.m
matlab_beam_doa-master/STFT analysis - synthesis/stft.m
1,547
utf_8
d38b73eee539e2f08c415ad0108eefd9
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Short-Time Fourier Transform % % with MATLAB Implementation % % % % Author: M.Sc. Eng. Hristo Zhivomirov 12/21/13 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [stft, f, t] = stft(x, wlen, h, nfft, fs) % function: [stft, t, f] = mystftfun(x, fs, wlen, h, nfft) % x - signal in the time domain % wlen - length of the hamming window % h - hop size % nfft - number of FFT points % fs - sampling frequency, Hz % f - frequency vector, Hz % t - time vector, s % stft - STFT matrix (time across columns, freq across rows) % represent x as column-vector if it is not if size(x,2) > 1 x = x'; end % length of the signal xlen = length(x); % form a periodic hamming window win = hamming(wlen, 'periodic'); % form the stft matrix rown = ceil((1+nfft)/2); % calculate the total number of rows coln = 1+fix((xlen-wlen)/h); % calculate the total number of columns stft = zeros(rown, coln); % form the stft matrix % initialize the indexes indx = 0; col = 1; % perform STFT while indx + wlen <= xlen % windowing xw = x(indx+1:indx+wlen).*win; % FFT X = fft(xw, nfft); % update the stft matrix stft(:,col) = X(1:(rown)); % update the indexes indx = indx + h; col = col + 1; end % calculate the time and frequency vectors t = (wlen/2:h:xlen-wlen/2-1)/fs; f = (0:rown-1)*fs/nfft; end
github
ganlubbq/matlab_beam_doa-master
RobustFSBdes.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/RobustFSBdes.m
14,966
utf_8
f8e2b60c21f75b32c814e27495821145
% RobustFSB Designs the optimum filter weights of a robust least-squares % frequency-invariant polynomial (RLSFIP) filter-and-sum beamformer. % function [fir_imp_resp, cfg, steerVector, realWNG_dB] = ... RobustFSBdes(cfg) local = []; %---------------------------------------------------------------------- % Initialization %---------------------------------------------------------------------- %cfg.spacing = spacing; %spacing of microphones (or radius) %---------------------------------------------------------------------- % other parameters %---------------------------------------------------------------------- % set path of set of prototype hrirs if required if strcmp(cfg.design, 'hrtf') cfg.path_hrirs = 'data/HRIR_NAO_LRC_az_0_355_16kHz.mat'; end %---------------------------------------------------------------------- % specify beamforming frequency range local.fstep = 100; % frequency steps between 'sampling points' of set of % discrete frequencies used to design the filter weights % % lower and upper limit in order to create extended frequency range local.lfreq_lim = 100; %lower limit local.hfreq_lim = 200; %to create higher limit % % set of frequencies used to design the filter weights %Note: Upper Bound + cfg.hfreq_lim <= cfg.srate, otherwise fir2 (below) %won't work local.frange = 300:local.fstep:(cfg.fs/2 - local.hfreq_lim); % % extended frequency range for computations: extends beamforming frequency range % computation in order to ensure a flat response across entire frequency range! local.frange_ext = (local.frange(1)-local.lfreq_lim):local.fstep:(local.frange(end)+local.hfreq_lim); % local.k_range_ext = 2*pi*local.frange_ext/cfg.c; % wavenumber (corresponding to extended computation frequency range) local.k_range = 2*pi*local.frange/cfg.c; % wavenumber (corresponding to beamformer frequency range) % local.WNG_lim = 10*log10(cfg.nmic); %limit of WNG if (cfg.wng_limit_db > local.WNG_lim) disp(' ') disp('White noise gain cannot be larger than 10*log10(N_transducer) corresponding to a delay-and-sum beamformer.') eval(['disp(''Reverting to maximum possible WNG: ' num2str(cfg.WNG_lim) 'dB'')']) disp(' ') cfg.wng_limit_db = local.WNG_lim; end % Converts WNG into an absolute number local.WNG = 10^(cfg.wng_limit_db/10); cfg.nmbr_look_dir = length(cfg.des_look_dir); %number of prototype look % directions (for simple FSB nmbr_look_dir =1) %---------------------------------------------------------------------- % Initialisation of geometry dependent parameters %cfg = BF_Array_Geometry(cfg); %% %-------------------------------------------------------------- % Initialisation of desired magnitude response % angular resolution (discretized angles) in degrees Todo: in which direction % be careful with changing this: I think cfg.desResponse_def is created for steps % of 5° (H.Barfuss, 13.11.14) local.P = 0; local.D_i = (cfg.des_look_dir.azimuth - 90)/90; %local.angular_resolution.azimuth = cfg.angRange; %local.angular_resolution.elevation = repmat(cfg.des_look_dir.elevation,size(local.angular_resolution.azimuth)); % define shape of desired magnitude response local.resp_choice = 'narrow'; % 'narrow', 'wide' switch local.resp_choice case 'narrow' local.desResponse_def = [linspace(0,0.7079,4) 0.99 1 0.99 fliplr(linspace(0,0.7079,4))]; case 'wide' local.desResponse_def = [linspace(eps,1-eps,6) 1 linspace(1-eps,eps,6)]; end %needed to determine starting and ending index (lower and upper %limit) of desired impulse response offset = floor(length(local.desResponse_def)/2); %contains the desired response for each prototype look %direction (column-wise) local.desResponse = zeros(length(cfg.angRange.azimuth),length(cfg.des_look_dir.azimuth)); for idx_look_dir = 1:cfg.nmbr_look_dir % skip_u and skip_l indicate if there was a problem with the % upper and lower limit of the desired response. If there % is a problem, one/both is > 0 and includes the difference % between maximum/minimum possible index and actual index skip_u = 0; skip_l = 0; %lower limit (starting index) of desired response lower_limit = find(cfg.angRange.azimuth == cfg.des_look_dir.azimuth(idx_look_dir)) - offset; if lower_limit < 1 % detects lower limit problem skip_l = abs(lower_limit-1); lower_limit = 1; end %upper limit (ending index) of desired response upper_limit = (lower_limit+length(local.desResponse_def)-1-skip_l); if upper_limit > length(cfg.angRange.azimuth) % detects upper limit problem skip_u = upper_limit - length(cfg.angRange.azimuth); upper_limit = length(cfg.angRange.azimuth); end % computing indices ind_temp2 = lower_limit:upper_limit; %check if lower or upper limit exceeds minimum/maximum %value, and store des desired reponse in the corresponding %column of cfg.desResponse if skip_l ~= 0 local.desResponse(ind_temp2,idx_look_dir) = local.desResponse_def(skip_l+1:end); end if skip_u ~= 0 local.desResponse(ind_temp2,idx_look_dir) = local.desResponse_def(1:end-skip_u); end if skip_l == 0 && skip_u == 0 local.desResponse(ind_temp2,idx_look_dir) = local.desResponse_def; end end %-------------------------------------------------------------- % initialisation of array response matrix G (see Equation (4) % in [Mabande et al, 2009] at desired response angles % [frequency,theta_resolution,N] = [#frequencies, #angles, #microphones] switch cfg.design case 'freefield' for idx_micPos=1:cfg.nmic % for cnt_LD = 1 : cfg.nmbr_look_dir %so far as I can see, % this for loop is not needed here (at the moment), maybe % needed for a polynomial beamformer... %_ext means that G_ext is created using the extended frequency %range (see RobustFSB.m) %x_mic: position vector of idx_micPos-th microphone mic_position = [cfg.mic_pos.x(idx_micPos); cfg.mic_pos.y(idx_micPos); cfg.mic_pos.z(idx_micPos)]; %compute steering vectors and store them in cfg.G_ext for idx_frequency = 1:length(local.k_range_ext) %k_vec: wavevectors for current frequency i_frequency %and current microphone with respect to all source positions k_vec = - local.k_range_ext(idx_frequency) * [sind(cfg.angRange.elevation).*cosd(cfg.angRange.azimuth); sind(cfg.angRange.elevation).*sind(cfg.angRange.azimuth); cosd(cfg.angRange.elevation)]; %save steering vectors in cfg.G_ext % same as D(f,æ) eq. 30 Mic. Arrays tut local.G_ext(idx_frequency,:,idx_micPos) = exp(-1i*k_vec.'*mic_position); end % end end case 'hrtf' % load hrirs load(cfg.path_hrirs); local.hrirs = imp_resp; %transform them into dft domain local.hrtfs = fft(imp_resp,cfg.fs,1); %save hrtfs in cfg.G_ext local.G_ext = permute(local.hrtfs(local.frange_ext,cfg.idx_hrtfs,... cfg.angRange.azimuth/5+1),[1,3,2]); end %% %---------------------------------------------------------------------- % Initialisation of look direction vector local = InitLookDirVec(cfg,local); N_f_bins = length(local.k_range); %cfg.calG (\mathcal{G} in [Mabande et al, 2010]) includes the product %G(\omega_p)*D_i of Eq. (5) for each (design-) frequency \omega_p %stacked in vertical direction for each prototype look direction %dimension: [Num_DesiredLookDirections*theta_resolution,Num_mics*(P+1)] %(see definition of \mathcal{G} in [Mabande et al, 2010] between Eq. (5) and (6)) local.calG = []; %G_D is a temporary variable and will include the product G(\omega_p)*D_i %from Eq. (5) of dimension: [freq,Num_DesiredLookDirections,theta_resolution,Num_mics*(P+1)] %this product is computed for every (design-) frequency G_D = NaN(N_f_bins, 1, length(local.desResponse), cfg.nmic); %for-loop over each (design-) frequency for idx_frequency = 1:length(local.frange_ext) tmp3 = []; % calculation of G_D at frequency \omega_p of dimension [theta_resolution,Num_mics*(P+1)] for idx_look_dir = 1:cfg.nmbr_look_dir %cfg.G_ext = steering vector G_D(idx_frequency,idx_look_dir,:,:) = squeeze(local.G_ext(idx_frequency,:,:,idx_look_dir))*... squeeze(local.D(idx_look_dir,:,:)); % concatenating of matrices along first dimension -> % frequency-dependent G_D(\omega_p) are concatenated along vertical % direction tmp3 = cat(1,tmp3,squeeze(G_D(idx_frequency,idx_look_dir,:,:))); end %final result is stored in cfg.calG local.calG(idx_frequency,:,:) = tmp3; end % store all desired response (different for each desired prototype look % direction) in cfg.b_des (see Eq. (6) and definition before (6) in % [Mabande et al, 2010]) % % for cnt1 = 1:cfg.nmbr_look_dir %I think this for loop is not necessary local.b_des = local.desResponse(:); % end %---------------------------------------------------------------------- %---------------------------------------------------------------------- % CVX based Optimization % %---------------------------------------------------------------------- % This block of code performs the constraint optimization proposed in % [Mabande et al, 2010] to obtain the optimum filter weighs in the % design domain % The CVX toolbox is used to solve the (convex) optimization problem %---------------------------------------------------------------------- % % Use a waitbar to illustrate design progress % h_wb = waitbar(0, 'Beamformer is being designed...'); %---------------------------------------------------------------------- % variable for resulting optimum filter weights % This will include the optimum filter coefficients for the extended % design frequency range cfg.frange_ext flt.w_opt = NaN(cfg.nmic,N_f_bins); %for loop over each (design-) frequency for idx_frequency=1:length(local.k_range_ext) % ai_Di will include the product a^T_i(\omega_p)*D_i of dimension [1, N(P+1)] % on each row and is required for the distortionless constraint % -> Eq. (7) in [Mabande et al, 2010] % % Thus, ai_Di is of dimension [I, N(P+1)] (I: number of prototype % directions) % % Note: ai_Di is also already included in cfg.calD at position % squeeze(cfg.calG(idx_frequency,cfg.angular_resolution == cfg.des_look_dir(i),:)) ai_Di = []; for idx_look_dir = 1:cfg.nmbr_look_dir ai_Di(idx_look_dir,:) = squeeze(G_D(idx_frequency, idx_look_dir, cfg.angRange.azimuth == cfg.des_look_dir.azimuth(idx_look_dir),:)); end % array responses at freq idx_frequency A = squeeze(local.calG(idx_frequency,:,:)); %------------------------------------------------------------------ % begin cvx optimization %------------------------------------------------------------------ cvx_begin % pause for 1 sec cvx_quiet(1) % complex variable declaration variable w(cfg.nmic*(local.P+1),1) complex; % minization of least-squares (LS) problem % -> Eq. (6) in [Mabande et al, 2010] minimize ( norm(A*w - local.b_des, 2) ); % constraints of LS problem subject to % for each prototype look direction one distortionless constraints % -> Eq. (7) in [Mabande et al, 2010] for idx_look_dir = 1:cfg.nmbr_look_dir imag(w.'*ai_Di(idx_look_dir,:).') == 0; real(w.'*ai_Di(idx_look_dir,:).') == 1; end % % For a response <= 1 % max(abs(A*w)) <= 1.0; % for each prototype look direction one WNG constraint % -> Eq. (8) in [Mabande et al, 2010] for idx_look_dir = 1:cfg.nmbr_look_dir norm(squeeze(local.D(idx_look_dir,:,:))*w,2) <= 1/sqrt(local.WNG); end cvx_end %------------------------------------------------------------------ %end of cvx optimization %------------------------------------------------------------------ % cvx_optval % Concatenate optimum filter coefficiens of current frequency % flt.w_opt contains the optimum filter weights of one filter at each row flt.w_opt(:,idx_frequency) = w; % % Update waitbar % waitbar(idx_frequency/N_f_bins, h_wb) end % % Close waitbar % close(h_wb); %--------------------------------------------------------------------- % WNG calculations % %--------------------------------------------------------------------- local.plot_LookDir = 1; for idx_freq=1:length(local.frange_ext) % Steering Vector of dimension [#Microphones, 1] d = squeeze(G_D(idx_freq,local.plot_LookDir, cfg.angRange.azimuth == cfg.des_look_dir.azimuth(local.plot_LookDir),:)); % theoretical WNG (computed with optimum filter coefficients % flt.w_opt obtained from optimization problem local.WNG(idx_freq) = 10*log10( (abs(flt.w_opt(:,idx_freq).'*d))^2/... ((squeeze(local.D(local.plot_LookDir,:,:))*flt.w_opt(:,idx_freq))'*(squeeze(local.D(local.plot_LookDir,:,:))*flt.w_opt(:,idx_freq))) ); end %---------------------------------------------------------------------- % Set return values % %---------------------------------------------------------------------- fir_imp_resp = flt.w_opt; % Resulting WNG of designed beamformer in dB realWNG_dB = local.WNG(:); steerVector = local.G_ext; end
github
ganlubbq/matlab_beam_doa-master
RobustFSBORG.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/RobustFSBORG.m
18,061
iso_8859_13
e19afddaa14b4622f7fb7ce34b9b560b
% RobustFSB Designs the optimum filter weights of a robust least-squares % frequency-invariant polynomial (RLSFIP) filter-and-sum beamformer. % % Inputs: % N: Number of sensors or actors % spacing: spacing between micophones or radius of array [meters] % 0 => non-uniform spacing % WNG_dB: Desired White Noise Gain in dB % P: polynomial order = 0 for FSB % int_choice: Interpolation choice 1=>polynomial interpolation; 2=> ??? interpolation % norm_choice: 1 => L_2 norm; 2 => L_inf norm % geometry: 1=> linear; 2=> circular % des_look_dir: desired look direction % design: 'freefield ' or 'hrtf' % % Outputs: TODO % fir_imp_resp: Filter impulse response of approximated FIR % filters % G_plot: Matrix of steering vectors for look direction % for which the beampattern has been plotted % resp: Contains the magnitude of the beamformer response % range is between 0 and 1 % FrequencyAxis: frequency bins used for the plots % AngularAxis: angles used for the plots % realWNG_dB: Resulting WNG of designed beamformer in dB % % Description: % This programm computes the optimum filter tabs of a broadband polynomial % beamformer. The goal is to minimize the sum of all squares subject to a % distortionless and WNG constraint. % CVX is used to solve the convex Second order Cone Program (SOCP). % % Edwin Mabande, Erlangen 01.11 function [fir_imp_resp, G_plot, resp, faxis, angaxis, realWNG_dB] = ... RobustFSBORG(N,spacing,WNG_dB,P,int_choice,norm_choice,geometry, des_look_dir, design) if nargin ~= 9, error('9 arguments required'); end %---------------------------------------------------------------------- % Initialization %---------------------------------------------------------------------- cfg = []; % save arguments in the cfg struct cfg.N = N; %number of microphones cfg.spacing = spacing; %spacing of microphones (or radius) cfg.P = P; %order of polynomial beamformer, if 0 -> simple FSB cfg.int_choice = int_choice; %choice of interpolation, not used in this code! cfg.norm_choice = norm_choice; %choice of norm to be minimized cfg.geometry = geometry; %parameter indicating array geometry (linear or spherical) cfg.des_look_dir = des_look_dir; %desired look direction cfg.design = design; %choice of freefield-based or hrtf-based design %---------------------------------------------------------------------- % other parameters cfg.c = 342; %speed of sound cfg.srate = 16000; %sampling rate %---------------------------------------------------------------------- % set path of set of prototype hrirs if required if strcmp(cfg.design, 'hrtf') cfg.path_hrirs = 'data/HRIR_NAO_LRC_az_0_355_16kHz.mat'; end %---------------------------------------------------------------------- % specify beamforming frequency range cfg.fstep = 100; % frequency steps between 'sampling points' of set of % discrete frequencies used to design the filter weights % % lower and upper limit in order to create extended frequency range cfg.lfreq_lim = 100; %lower limit cfg.hfreq_lim = 200; %to create higher limit % % set of frequencies used to design the filter weights %Note: Upper Bound + cfg.hfreq_lim <= cfg.srate, otherwise fir2 (below) %won't work cfg.frange = 300:cfg.fstep:(cfg.srate/2 - cfg.hfreq_lim); % % extended frequency range for computations: extends beamforming frequency range % computation in order to ensure a flat response across entire frequency range! cfg.frange_ext = (cfg.frange(1)-cfg.lfreq_lim):cfg.fstep:(cfg.frange(end)+cfg.hfreq_lim); % cfg.k_range_ext = 2*pi*cfg.frange_ext/cfg.c; % wavenumber (corresponding to extended computation frequency range) cfg.k_range = 2*pi*cfg.frange/cfg.c; % wavenumber (corresponding to beamformer frequency range) % cfg.WNG_dB = WNG_dB; cfg.WNG_lim = 10*log10(N); %limit of WNG if (cfg.WNG_dB > cfg.WNG_lim) disp(' ') disp('White noise gain cannot be larger than 10*log10(N_transducer) corresponding to a delay-and-sum beamformer.') eval(['disp(''Reverting to maximum possible WNG: ' num2str(cfg.WNG_lim) 'dB'')']) disp(' ') cfg.WNG_dB = cfg.WNG_lim; end % Converts WNG into an absolute number cfg.WNG = 10^(cfg.WNG_dB/10); % % Possibly NEEDS TO BE ADAPTED FOR POLYNOMIAL BEAMFORMER cfg.nmbr_look_dir = length(cfg.des_look_dir); %number of prototype look % directions (for simple FSB -> 1) %---------------------------------------------------------------------- % Initialisation of geometry dependent parameters cfg = BF_Array_GeometryORG(cfg); %---------------------------------------------------------------------- % Initialisation of look direction vector cfg = InitLookDirVecORG(cfg); %---------------------------------------------------------------------- % Initialising of matrices for the optimization problem % % ToDo: I think this needs to be adapted (regarding the concatenation) % for several desired look directions -> for polynomial beamforming % H.Barfuss, 10.11.14 % N_f_bins = length(cfg.k_range_ext); %number of (design-) frequencies %cfg.calG (\mathcal{G} in [Mabande et al, 2010]) includes the product %G(\omega_p)*D_i of Eq. (5) for each (design-) frequency \omega_p %stacked in vertical direction for each prototype look direction %dimension: [Num_DesiredLookDirections*theta_resolution,Num_mics*(P+1)] %(see definition of \mathcal{G} in [Mabande et al, 2010] between Eq. (5) and (6)) cfg.calG = []; %G_D is a temporary variable and will include the product G(\omega_p)*D_i %from Eq. (5) of dimension: [freq,Num_DesiredLookDirections,theta_resolution,Num_mics*(P+1)] %this product is computed for every (design-) frequency G_D = NaN(N_f_bins, 1, length(cfg.desResponse), N); %for-loop over each (design-) frequency for idx_frequency = 1:length(cfg.frange_ext) tmp3 = []; % calculation of G_D at frequency \omega_p of dimension [theta_resolution,Num_mics*(P+1)] for idx_look_dir = 1:cfg.nmbr_look_dir %cfg.G_ext = steering vector G_D(idx_frequency,idx_look_dir,:,:) = squeeze(cfg.G_ext(idx_frequency,:,:,idx_look_dir))*... squeeze(cfg.D(idx_look_dir,:,:)); % concatenating of matrices along first dimension -> % frequency-dependent G_D(\omega_p) are concatenated along vertical % direction tmp3 = cat(1,tmp3,squeeze(G_D(idx_frequency,idx_look_dir,:,:))); end %final result is stored in cfg.calG cfg.calG(idx_frequency,:,:) = tmp3; end % store all desired response (different for each desired prototype look % direction) in cfg.b_des (see Eq. (6) and definition before (6) in % [Mabande et al, 2010]) % % for cnt1 = 1:cfg.nmbr_look_dir %I think this for loop is not necessary cfg.b_des = cfg.desResponse(:); % end %---------------------------------------------------------------------- %---------------------------------------------------------------------- % CVX based Optimization % %---------------------------------------------------------------------- % This block of code performs the constraint optimization proposed in % [Mabande et al, 2010] to obtain the optimum filter weighs in the % design domain % The CVX toolbox is used to solve the (convex) optimization problem %---------------------------------------------------------------------- % % Use a waitbar to illustrate design progress % h_wb = waitbar(0, 'Beamformer is being designed...'); %---------------------------------------------------------------------- % variable for resulting optimum filter weights % This will include the optimum filter coefficients for the extended % design frequency range cfg.frange_ext flt.w_opt = NaN(cfg.N,N_f_bins); %for loop over each (design-) frequency for idx_frequency=1:length(cfg.k_range_ext) % ai_Di will include the product a^T_i(\omega_p)*D_i of dimension [1, N(P+1)] % on each row and is required for the distortionless constraint % -> Eq. (7) in [Mabande et al, 2010] % % Thus, ai_Di is of dimension [I, N(P+1)] (I: number of prototype % directions) % % Note: ai_Di is also already included in cfg.calD at position % squeeze(cfg.calG(idx_frequency,cfg.angular_resolution == cfg.DesAng(i),:)) ai_Di = []; for idx_look_dir = 1:cfg.nmbr_look_dir ai_Di(idx_look_dir,:) = squeeze(G_D(idx_frequency, idx_look_dir, cfg.angular_resolution.azimuth == cfg.DesAng.azimuth(idx_look_dir),:)); end % array responses at freq idx_frequency A = squeeze(cfg.calG(idx_frequency,:,:)); %------------------------------------------------------------------ % begin cvx optimization %------------------------------------------------------------------ cvx_begin % pause for 1 sec cvx_quiet(1) % complex variable declaration variable w(cfg.N*(cfg.P+1),1) complex; % minization of least-squares (LS) problem % -> Eq. (6) in [Mabande et al, 2010] minimize ( norm(A*w - cfg.b_des, 2) ); % constraints of LS problem subject to % for each prototype look direction one distortionless constraints % -> Eq. (7) in [Mabande et al, 2010] for idx_look_dir = 1:cfg.nmbr_look_dir imag(w.'*ai_Di(idx_look_dir,:).') == 0; real(w.'*ai_Di(idx_look_dir,:).') == 1; end % % For a response <= 1 % max(abs(A*w)) <= 1.0; % for each prototype look direction one WNG constraint % -> Eq. (8) in [Mabande et al, 2010] for idx_look_dir = 1:cfg.nmbr_look_dir norm(squeeze(cfg.D(idx_look_dir,:,:))*w,2) <= 1/sqrt(cfg.WNG); end cvx_end %------------------------------------------------------------------ %end of cvx optimization %------------------------------------------------------------------ % cvx_optval % Concatenate optimum filter coefficiens of current frequency % flt.w_opt contains the optimum filter weights of one filter at each row flt.w_opt(:,idx_frequency) = w; % % Update waitbar % waitbar(idx_frequency/N_f_bins, h_wb) end % % Close waitbar % close(h_wb); %---------------------------------------------------------------------- % FIR Approximation % %---------------------------------------------------------------------- % filter coefficient computation -> FIR approxmation of optimum filters % saved in flt.w_opt %---------------------------------------------------------------------- % w_opt_wholeFreqRange will contain the optimum filter weights to be % approximated by fir2 % % At frequencies that are not included in the extended set of design % frequencies cfg.frange_ext, the eps value is used w_opt_wholeFreqRange = ones((cfg.P+1)*cfg.N,(cfg.srate/2)/cfg.fstep+1)*eps; % F is a vector of frequency points in the range from 0 to 1, where 1 % corresponds to the Nyquist frequency (half the sampling frequency) % required for fir2 function F = (0:cfg.fstep:cfg.srate/2)/(cfg.srate/2); % write optimum filter weights of each filter to variable w_opt_wholeFreqRange % cfg.frange_ext/cfg.fstep+1 makes sure that at entries of w_opt_wholeFreqRange % corresponding to frequencies that are not included in the extended set of % design frequencies cfg.frange_ext (e.g. 0Hz) no optimum filger weight is stored % This is necessesary because fir2 requires information about the whole % frequency range between 0Hz ... fs/2Hz for cnt = 1:cfg.N*(cfg.P+1) w_opt_wholeFreqRange(cnt,cfg.frange_ext/cfg.fstep+1) = ... conj(flt.w_opt(cnt,:)); %Why conj() ? weiß wohl nur Edwin :-) end % tmp_firfilt: contains approximated filter coefficients for each % filter on one row % -> dimension: [N*(P+1),filt_len] tmp_firfilt = zeros((cfg.P+1)*cfg.N,cfg.filterlength); for idx_filters=1:cfg.N*(cfg.P+1) tmp_firfilt(idx_filters,:) = fir2(cfg.filterlength-1,F,... squeeze(w_opt_wholeFreqRange(idx_filters,:))); end % ordering coefficients in P+1 filter-and-sum subblocks of dimension % [Filter length, #Microphones]. cfg.PBF_firfilt is used later on in % BF_Plot_BP % PBF_firfilt: (P+1) x filterlength x Number of mics cfg.PBF_firfilt = zeros((cfg.P+1),cfg.filterlength,cfg.N);% [P+1,filt_len, N] for idx_mic = 1:cfg.N for idx_P = 1:cfg.P+1 cfg.PBF_firfilt(idx_P,:,idx_mic) = tmp_firfilt((idx_mic-1)*(cfg.P+1)+idx_P,:); end end %---------------------------------------------------------------------- %Choose look direction chosen from prototype look directions for which %the beampattern shall be plotted cfg.plot_LookDir = 1; %---------------------------------------------------------------------- %---------------------------------------------------------------------- % WNG % %---------------------------------------------------------------------- % In this section, the White Noise Gain (WNG) is computed for the % original design frequency range % First it is computed for cfg.frange_ext % Second, the resulting WNG is limited to cfg.frange %---------------------------------------------------------------------- % computing the frequenc responses with obtained fiter coefficients % (of approximated FIR filters) filt_real= zeros(cfg.N*(cfg.P+1),size(flt.w_opt,2)); for idx_filter=1:cfg.N*(cfg.P+1) %compute frequency response of approximated FIR filters H = freqz( tmp_firfilt(idx_filter,:), 1, cfg.srate/2+1 ); %store compute frequency response of approximated FIR filters in %filt_real, one filter in each row filt_real(idx_filter,:) = H(cfg.frange_ext); end %---------------------------------------------------------------------- %Compute theoretical (-> WNG_theoretical) and real (-> WNG_real) WNGs % in the 'original' frequency range, not the extended frequency range %For the computation of the WNG, see e.g., Eq. (8) in [Mabande et al, %2010] WNG_theoretical_tmp = NaN(size(cfg.frange_ext)); WNG_real_tmp = NaN(size(cfg.frange_ext)); % for each for idx_freq_ext=1:length(cfg.frange_ext) % Steering Vector of dimension [#Microphones, 1] d = squeeze(G_D(idx_freq_ext,cfg.plot_LookDir, cfg.angular_resolution.azimuth == cfg.DesAng.azimuth(cfg.plot_LookDir),:)); % theoretical WNG (computed with optimum filter coefficients % flt.w_opt obtained from optimization problem WNG_theoretical_tmp(idx_freq_ext) = 10*log10( (abs(flt.w_opt(:,idx_freq_ext).'*d))^2/... ((squeeze(cfg.D(cfg.plot_LookDir,:,:))*flt.w_opt(:,idx_freq_ext))'*(squeeze(cfg.D(cfg.plot_LookDir,:,:))*flt.w_opt(:,idx_freq_ext))) ); % real/actual WNG (computed from approximated fir filter % coefficients in filt_real) WNG_real_tmp(idx_freq_ext) = 10*log10( (abs(filt_real(:,idx_freq_ext).'*d))^2/... ((squeeze(cfg.D(cfg.plot_LookDir,:,:))*filt_real(:,idx_freq_ext))'*(squeeze(cfg.D(cfg.plot_LookDir,:,:))*filt_real(:,idx_freq_ext))) ); end %save only WNG in the 'original' frequency range (cfg.frange), not in %the extended frequency range cfg.WNG_theoretical = WNG_theoretical_tmp(cfg.lfreq_lim/cfg.fstep+1:end - cfg.hfreq_lim/cfg.fstep); cfg.WNG_real = WNG_real_tmp(cfg.lfreq_lim/cfg.fstep+1:end - cfg.hfreq_lim/cfg.fstep); %---------------------------------------------------------------------- %---------------------------------------------------------------------- % Beampatterns % %---------------------------------------------------------------------- % In this section the resulting beampattern and WNG is plotted %---------------------------------------------------------------------- % Illustrate results cfg = BF_Plot_BP(cfg); %---------------------------------------------------------------------- %---------------------------------------------------------------------- % Set return values % %---------------------------------------------------------------------- % Filter impulse response of approximated FIR filters fir_imp_resp = tmp_firfilt.'; %Matrix of steering vectors for look direction for which the beampattern has been plotted G_plot = cfg.G_plot; %Magnitude of the beamformer response resp = cfg.BF_response_abs; % Frequency bins used for the plots faxis = cfg.frange(:); % Angles used for the plots angaxis = cfg.DOA_degs_plot(:); % Resulting WNG of designed beamformer in dB realWNG_dB = cfg.WNG_real(:); end
github
ganlubbq/matlab_beam_doa-master
estimate_cdr_nodoa.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/estimate_cdr_nodoa.m
1,389
utf_8
b12850a707e91ffd8c8be07b04f04121
%ESTIMATE_CDR_NODOA % Blind (DOA-independent), unbiased estimation of the Coherent-to-Diffuse Ratio (CDR) % from the complex coherence of a mixed (noisy) signal. Equivalent to CDRprop3 in [1]. % % CDR = estimate_cdr_nodoa(Cxx, Cnn) % Cxx: complex coherence of mixed (noisy) signal % Cnn: coherence of noise component (real-valued) % % Reference: % Andreas Schwarz, Walter Kellermann, "Coherent-to-Diffuse Power Ratio % Estimation for Dereverberation", IEEE/ACM Trans. on Audio, Speech and % Lang. Proc., 2015 (under review); preprint available: arXiv:1502.03784 % PDF: http://arxiv.org/pdf/1502.03784 % % Andreas Schwarz ([email protected]) % Multimedia Communications and Signal Processing % Friedrich-Alexander-Universitaet Erlangen-Nuernberg (FAU) % Cauerstr. 7, 91058 Erlangen, Germany function CDR = estimate_cdr_nodoa(Cxx,Cnn,~) Cnn = bsxfun(@times, ones(size(Cxx)), Cnn); % extend to dimension of Cxx % limit the magnitude of Cxx to prevent numerical problems magnitude_threshold = 1-1e-10; critical = abs(Cxx)>magnitude_threshold; Cxx(critical) = magnitude_threshold .* Cxx(critical) ./ abs(Cxx(critical)); CDR = (-(abs(Cxx).^2 + Cnn.^2.*real(Cxx).^2 - Cnn.^2.*abs(Cxx).^2 - 2.*Cnn.*real(Cxx) + Cnn.^2).^(1/2) - abs(Cxx).^2 + Cnn.*real(Cxx))./(abs(Cxx).^2-1); % Ensure we don't get any negative or complex results due to numerical effects CDR = max(real(CDR),0); end
github
ganlubbq/matlab_beam_doa-master
fft2melmx.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/tools/fwsegsnr/fft2melmx.m
6,437
utf_8
aed4ba527b0df617c06c56660cb6dd1c
function [wts,binfrqs] = fft2melmx(nfft, sr, nfilts, width, minfrq, maxfrq, htkmel, constamp) % wts = fft2melmx(nfft, sr, nfilts, width, minfrq, maxfrq, htkmel, constamp) % Generate a matrix of weights to combine FFT bins into Mel % bins. nfft defines the source FFT size at sampling rate sr. % Optional nfilts specifies the number of output bands required % (else one per bark), and width is the constant width of each % band relative to standard Mel (default 1). % While wts has nfft columns, the second half are all zero. % Hence, Mel spectrum is fft2melmx(nfft,sr)*abs(fft(xincols,nfft)); % minfrq is the frequency (in Hz) of the lowest band edge; % default is 0, but 133.33 is a common standard (to skip LF). % maxfrq is frequency in Hz of upper edge; default sr/2. % You can exactly duplicate the mel matrix in Slaney's mfcc.m % as fft2melmx(512, 8000, 40, 1, 133.33, 6855.5, 0); % htkmel=1 means use HTK's version of the mel curve, not Slaney's. % constamp=1 means make integration windows peak at 1, not sum to 1. % 2004-09-05 [email protected] based on fft2barkmx % Copyright (c) 2010, Dan Ellis % All rights reserved. % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in % the documentation and/or other materials provided with the distribution % * Neither the name of the Columbia University nor the names % of its contributors may be used to endorse or promote products derived % from this software without specific prior written permission. % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE % POSSIBILITY OF SUCH DAMAGE. if nargin < 2; sr = 8000; end if nargin < 3; nfilts = 40; end if nargin < 4; width = 1.0; end if nargin < 5; minfrq = 0; end % default bottom edge at 0 if nargin < 6; maxfrq = sr/2; end % default top edge at nyquist if nargin < 7; htkmel = 0; end if nargin < 8; constamp = 0; end wts = zeros(nfilts, nfft); % Center freqs of each FFT bin fftfrqs = [0:nfft-1]/nfft*sr; % 'Center freqs' of mel bands - uniformly spaced between limits minmel = hz2mel(minfrq, htkmel); maxmel = hz2mel(maxfrq, htkmel); binfrqs = mel2hz(minmel+[0:(nfilts+1)]/(nfilts+1)*(maxmel-minmel), htkmel); binbin = round(binfrqs/sr*(nfft-1)); for i = 1:nfilts % fs = mel2hz(i + [-1 0 1], htkmel); fs = binfrqs(i+[0 1 2]); % scale by width fs = fs(2)+width*(fs - fs(2)); % lower and upper slopes for all bins loslope = (fftfrqs - fs(1))/(fs(2) - fs(1)); hislope = (fs(3) - fftfrqs)/(fs(3) - fs(2)); % .. then intersect them with each other and zero % wts(i,:) = 2/(fs(3)-fs(1))*max(0,min(loslope, hislope)); wts(i,:) = max(0,min(loslope, hislope)); % actual algo and weighting in feacalc (more or less) % wts(i,:) = 0; % ww = binbin(i+2)-binbin(i); % usl = binbin(i+1)-binbin(i); % wts(i,1+binbin(i)+[1:usl]) = 2/ww * [1:usl]/usl; % dsl = binbin(i+2)-binbin(i+1); % wts(i,1+binbin(i+1)+[1:(dsl-1)]) = 2/ww * [(dsl-1):-1:1]/dsl; % need to disable weighting below if you use this one end if (constamp == 0) % Slaney-style mel is scaled to be approx constant E per channel wts = diag(2./(binfrqs(2+[1:nfilts])-binfrqs(1:nfilts)))*wts; end % Make sure 2nd half of FFT is zero wts(:,(nfft/2+1):nfft) = 0; % seems like a good idea to avoid aliasing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = mel2hz(z, htk) % f = mel2hz(z, htk) % Convert 'mel scale' frequencies into Hz % Optional htk = 1 means use the HTK formula % else use the formula from Slaney's mfcc.m % 2005-04-19 [email protected] if nargin < 2 htk = 0; end if htk == 1 f = 700*(10.^(z/2595)-1); else f_0 = 0; % 133.33333; f_sp = 200/3; % 66.66667; brkfrq = 1000; brkpt = (brkfrq - f_0)/f_sp; % starting mel value for log region logstep = exp(log(6.4)/27); % the magic 1.0711703 which is the ratio needed to get from 1000 Hz to 6400 Hz in 27 steps, and is *almost* the ratio between 1000 Hz and the preceding linear filter center at 933.33333 Hz (actually 1000/933.33333 = 1.07142857142857 and exp(log(6.4)/27) = 1.07117028749447) linpts = (z < brkpt); f = 0*z; % fill in parts separately f(linpts) = f_0 + f_sp*z(linpts); f(~linpts) = brkfrq*exp(log(logstep)*(z(~linpts)-brkpt)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function z = hz2mel(f,htk) % z = hz2mel(f,htk) % Convert frequencies f (in Hz) to mel 'scale'. % Optional htk = 1 uses the mel axis defined in the HTKBook % otherwise use Slaney's formula % 2005-04-19 [email protected] if nargin < 2 htk = 0; end if htk == 1 z = 2595 * log10(1+f/700); else % Mel fn to match Slaney's Auditory Toolbox mfcc.m f_0 = 0; % 133.33333; f_sp = 200/3; % 66.66667; brkfrq = 1000; brkpt = (brkfrq - f_0)/f_sp; % starting mel value for log region logstep = exp(log(6.4)/27); % the magic 1.0711703 which is the ratio needed to get from 1000 Hz to 6400 Hz in 27 steps, and is *almost* the ratio between 1000 Hz and the preceding linear filter center at 933.33333 Hz (actually 1000/933.33333 = 1.07142857142857 and exp(log(6.4)/27) = 1.07117028749447) linpts = (f < brkfrq); z = 0*f; % fill in parts separately z(linpts) = (f(linpts) - f_0)/f_sp; z(~linpts) = brkpt+(log(f(~linpts)/brkfrq))./log(logstep); end
github
ganlubbq/matlab_beam_doa-master
get_asr_score_longsignal.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/tools/sphinx_eval/get_asr_score_longsignal.m
1,422
utf_8
a05565da96107aa0914c898c1ab421a3
% get_asr_score_longsignal(long_signal, listname, endpoints) % % Andreas Schwarz ([email protected]), 2013 % % This function takes a concatenation of GRID utterances, splits it, calls the % speech recognizer, and returns the keyword score (recognition rate for % letter and number in the utterance, as in the CHIME challenge). % % Example: % addpath('sphinx_eval'); % load('test_short'); % % do something processing with long_signal; make sure output has same time alignment % long_signal = fftfilt(hamming(20), double(long_signal)); % low-pass filter as example % get_asr_score_longsignal(long_signal, 'test_short', endpoints) function [ score ] = get_asr_score_longsignal(long_signal, listname, endpoints) files = importdata([listname '.fileids']); wavdir = tempname(); warning('off','MATLAB:MKDIR:DirectoryExists'); warning('off','MATLAB:audiovideo:wavwrite:functionToBeRemoved'); for file_ix=1:length(files) if file_ix==1 startpoint=1; else startpoint=endpoints(file_ix-1)+1; end endpoint = endpoints(file_ix); mkdir(fileparts([wavdir '/' files{file_ix}])); %audiowrite([wavdir '/' files{file_ix} '.wav'], long_signal(startpoint:endpoint)./max(abs(long_signal)+0.01), 16000); wavwrite(long_signal(startpoint:endpoint)./max(abs(long_signal)+0.01), 16000, [wavdir '/' files{file_ix} '.wav']); end score=get_asr_score(wavdir, listname); system(['rm -rf ' wavdir]);
github
ganlubbq/matlab_beam_doa-master
calc_grid_score.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/tools/sphinx_eval/calc_grid_score.m
784
utf_8
931e917b36cbe9f487f30700f6731b05
% unlike calc_chime_score, this function considers all words in the utterance function [ relative_score ] = calc_grid_score( transcription ) correct = 0; total = 0; lines = regexp(strtrim(transcription),'\s*\n\s*','split'); for i=1:length(lines) line = lines{i}; parts = regexp(line,'\(','split'); recognized_words = regexp(strtrim(parts{1}),'\s+','split'); filename = regexp(parts{2},'[A-Za-z0-9]{6}','match'); filename=filename{1}; for word_ix=1:length(filename) if word_ix > length(recognized_words) || isempty(recognized_words{word_ix}) % wrong elseif lower(filename(word_ix)) == lower(recognized_words{word_ix}(1)) correct = correct + 1; end total = total + 1; end end relative_score = 100*correct/total; end
github
ganlubbq/matlab_beam_doa-master
BF_Array_GeometryORG.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/Generalized_RLSFI_BF/BF_Array_GeometryORG.m
10,646
utf_8
c51be47f3a8f924a4a46500e6df9883e
%-------------------------------------------------------------------------- % Array Geometry %-------------------------------------------------------------------------- function cfg = BF_Array_GeometryORG(cfg) switch (cfg.geometry) %------------------------------------------------------------------ % define array geometry (geometry-dependent variables) for linear array % positions of microphones defined in cartesian coordinate systems % according to [Van Trees, Optimum Array Processing, Fig.2.1] % x: right(>0), left(<0) % y: forward(>0), backward(<0) % z: above(>0), below(<0) % origin of array (x,y,z)=(0,0,0) assumed to be center microphone %------------------------------------------------------------------ case 1 % linear array if cfg.spacing == 0 %input non-uniform spacing manually switch cfg.design case 'freefield' switch cfg.N case 3 %left, right, and center microphone (mics: 1,5, and 9) %microphone positions always from left (mic 1) to %right (mic 9) cfg.mic_pos.z = mic_positions.z(1:3); cfg.mic_pos.x = [-7.5e-2 0 7.5e-2]; cfg.mic_pos.y = [-6e-2 0 -6e-2]; cfg.mic_pos.z = [-4e-2 0 -4e-2]; case 5 %(mics: 1, 3, 5, 7, and 9) cfg.mic_pos.x = [-7.5e-2 -3.375e-2 0 3.375e-2 7.5e-2]; cfg.mic_pos.y = [-6e-2 -0.75e-2 0 -0.75e-2 -6e-2]; cfg.mic_pos.z = [-4e-2 0 0 0 -4e-2]; case 7 %(mics: 1, 2, 4, 5, 6, 8, and 9) cfg.mic_pos.x = [-7.5e-2 -4.5e-2 -2.25e-2 0 2.25e-2 4.5e-2 7.5e-2]; cfg.mic_pos.y = [-6e-2 -1e-2 -0.5e-2 0 -0.5e-2 -1e-2 -6e-2]; cfg.mic_pos.z = [-4e-2 0 0 0 0 0 -4e-2]; case 9 %(mics: 1, 2, 3, 4, 5, 6, 7, 8, and 9) cfg.mic_pos.x = [-7.5e-2 -4.5e-2 -3.375e-2 -2.25e-2 0 2.25e-2 3.375e-2 4.5e-2 7.5e-2]; cfg.mic_pos.y = [-6e-2 -1e-2 -0.75e-2 -0.5e-2 0 -0.5e-2 -0.75e-2 -1e-2 -6e-2]; cfg.mic_pos.z = [-4e-2 0 0 0 0 0 0 0 -4e-2]; end case 'hrtf' switch cfg.N case 3 cfg.idx_hrtfs = [1 5 9]; case 5 cfg.idx_hrtfs = [1 3 5 7 9]; case 7 cfg.idx_hrtfs = [1 2 4 5 6 8 9]; case 9 cfg.idx_hrtfs = (1:9); end end else %uniform spacing automatically % initialisation of sensor positions cfg.mic_pos.x = linspace(-(cfg.N - 1)/2,(cfg.N - 1)/2,cfg.N)*cfg.spacing; cfg.mic_pos.y = zeros(size(cfg.mic_pos.x)); cfg.mic_pos.z = zeros(size(cfg.mic_pos.x)); end %-------------------------------------------------------------- % filterlength cfg.filterlength = 1023; %-------------------------------------------------------------- % Desired prototype look directions (MAY HAVE TO BE ADAPTED FOR % POLYNOMIAL BEAMFORMING) %evtl. kann cfg.DesAng auch ganz entfernt werden! cfg.DesAng = cfg.des_look_dir; % range of delays required for polynomial beamforming (-> one % value for normal FSB) % NOTE: at the moment, elevation is always assumed to be fix. % Steering the beamformer is only done in azimuth direction! %das hier muss noch für den polynomial beamformer angepasst %werden denke ich! cfg.D_i = (cfg.DesAng.azimuth - 90)/90; %-------------------------------------------------------------- % Initialisation of desired magnitude response % angular resolution (discretized angles) in degrees Todo: in which direction % be careful with changing this: I think cfg.desResponse_def is created for steps % of 5° (H.Barfuss, 13.11.14) cfg.angular_resolution.azimuth = (0:5:180); cfg.angular_resolution.elevation = repmat(cfg.DesAng.elevation,size(cfg.angular_resolution.azimuth)); % define shape of desired magnitude response cfg.resp_choice = 'narrow'; % 'narrow', 'wide' switch cfg.resp_choice case 'narrow' cfg.desResponse_def = [linspace(0,0.7079,4) 0.99 1 0.99 fliplr(linspace(0,0.7079,4))]; case 'wide' cfg.desResponse_def = [linspace(eps,1-eps,6) 1 linspace(1-eps,eps,6)]; end %needed to determine starting and ending index (lower and upper %limit) of desired impulse response offset = floor(length(cfg.desResponse_def)/2); %contains the desired response for each prototype look %direction (column-wise) cfg.desResponse = zeros(length(cfg.angular_resolution.azimuth),length(cfg.DesAng.azimuth)); for idx_look_dir = 1:cfg.nmbr_look_dir % skip_u and skip_l indicate if there was a problem with the % upper and lower limit of the desired response. If there % is a problem, one/both is > 0 and includes the difference % between maximum/minimum possible index and actual index skip_u = 0; skip_l = 0; %lower limit (starting index) of desired response lower_limit = find(cfg.angular_resolution.azimuth == cfg.DesAng.azimuth(idx_look_dir)) - offset; if lower_limit < 1 % detects lower limit problem skip_l = abs(lower_limit-1); lower_limit = 1; end %upper limit (ending index) of desired response upper_limit = (lower_limit+length(cfg.desResponse_def)-1-skip_l); if upper_limit > length(cfg.angular_resolution.azimuth) % detects upper limit problem skip_u = upper_limit - length(cfg.angular_resolution.azimuth); upper_limit = length(cfg.angular_resolution.azimuth); end % computing indices ind_temp2 = lower_limit:upper_limit; %check if lower or upper limit exceeds minimum/maximum %value, and store des desired reponse in the corresponding %column of cfg.desResponse if skip_l ~= 0 cfg.desResponse(ind_temp2,idx_look_dir) = cfg.desResponse_def(skip_l+1:end); end if skip_u ~= 0 cfg.desResponse(ind_temp2,idx_look_dir) = cfg.desResponse_def(1:end-skip_u); end if skip_l == 0 && skip_u == 0 cfg.desResponse(ind_temp2,idx_look_dir) = cfg.desResponse_def; end end %-------------------------------------------------------------- % initialisation of array response matrix G (see Equation (4) % in [Mabande et al, 2009] at desired response angles % [frequency,theta_resolution,N] = [#frequencies, #angles, #microphones] switch cfg.design case 'freefield' for idx_micPos=1:cfg.N % for cnt_LD = 1 : cfg.nmbr_look_dir %so far as I can see, % this for loop is not needed here (at the moment), maybe % needed for a polynomial beamformer... %_ext means that G_ext is created using the extended frequency %range (see RobustFSB.m) %x_mic: position vector of idx_micPos-th microphone x_mic = [cfg.mic_pos.x(idx_micPos); cfg.mic_pos.y(idx_micPos); cfg.mic_pos.z(idx_micPos)]; %compute steering vectors and store them in cfg.G_ext for idx_frequency = 1:length(cfg.k_range_ext) %k_vec: wavevectors for current frequency i_frequency %and current microphone with respect to all source positions k_vec = - cfg.k_range_ext(idx_frequency) * [sind(cfg.angular_resolution.elevation).*cosd(cfg.angular_resolution.azimuth); sind(cfg.angular_resolution.elevation).*sind(cfg.angular_resolution.azimuth); cosd(cfg.angular_resolution.elevation)]; %save steering vectors in cfg.G_ext % same as D(f,æ) eq. 30 Mic. Arrays tut cfg.G_ext(idx_frequency,:,idx_micPos) = exp(-1i*k_vec.'*x_mic); end % end end case 'hrtf' % load hrirs load(cfg.path_hrirs); cfg.hrirs = imp_resp; %transform them into dft domain cfg.hrtfs = fft(imp_resp,cfg.srate,1); %save hrtfs in cfg.G_ext cfg.G_ext = permute(cfg.hrtfs(cfg.frange_ext,cfg.idx_hrtfs,... cfg.angular_resolution.azimuth/5+1),[1,3,2]); end %-------------------------------------------------------------- %------------------------------------------------------------------ % define array geometry (geometry-dependent variables) for circular array %------------------------------------------------------------------ case 2 error('Other Geometry not supported yet\n') end end
github
ganlubbq/matlab_beam_doa-master
RobustFSB.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/Generalized_RLSFI_BF/RobustFSB.m
18,066
iso_8859_13
fde40277013097b05842c849828e06a1
% RobustFSB Designs the optimum filter weights of a robust least-squares % frequency-invariant polynomial (RLSFIP) filter-and-sum beamformer. % % Inputs: % N: Number of sensors or actors % spacing: spacing between micophones or radius of array [meters] % 0 => non-uniform spacing % WNG_dB: Desired White Noise Gain in dB % P: polynomial order = 0 for FSB % int_choice: Interpolation choice 1=>polynomial interpolation; 2=> ??? interpolation % norm_choice: 1 => L_2 norm; 2 => L_inf norm % geometry: 1=> linear; 2=> circular % des_look_dir: desired look direction % design: 'freefield ' or 'hrtf' % % Outputs: TODO % fir_imp_resp: Filter impulse response of approximated FIR % filters % G_plot: Matrix of steering vectors for look direction % for which the beampattern has been plotted % resp: Contains the magnitude of the beamformer response % range is between 0 and 1 % FrequencyAxis: frequency bins used for the plots % AngularAxis: angles used for the plots % realWNG_dB: Resulting WNG of designed beamformer in dB % % Description: % This programm computes the optimum filter tabs of a broadband polynomial % beamformer. The goal is to minimize the sum of all squares subject to a % distortionless and WNG constraint. % CVX is used to solve the convex Second order Cone Program (SOCP). % % Edwin Mabande, Erlangen 01.11 function [fir_imp_resp, G_plot, resp, realWNG_dB] = ... RobustFSB(N,spacing,WNG_dB,P,int_choice,norm_choice,geometry, des_look_dir, design) if nargin ~= 9, error('9 arguments required'); end %---------------------------------------------------------------------- % Initialization %---------------------------------------------------------------------- cfg = []; % save arguments in the cfg struct cfg.N = N; %number of microphones cfg.spacing = spacing; %spacing of microphones (or radius) cfg.P = P; %order of polynomial beamformer, if 0 -> simple FSB cfg.int_choice = int_choice; %choice of interpolation, not used in this code! cfg.norm_choice = norm_choice; %choice of norm to be minimized cfg.geometry = geometry; %parameter indicating array geometry (linear or spherical) cfg.des_look_dir = des_look_dir; %desired look direction cfg.design = design; %choice of freefield-based or hrtf-based design %---------------------------------------------------------------------- % other parameters cfg.c = 342; %speed of sound cfg.srate = 16000; %sampling rate %---------------------------------------------------------------------- % set path of set of prototype hrirs if required if strcmp(cfg.design, 'hrtf') cfg.path_hrirs = 'data/HRIR_NAO_LRC_az_0_355_16kHz.mat'; end %---------------------------------------------------------------------- % specify beamforming frequency range cfg.fstep = 100; % frequency steps between 'sampling points' of set of % discrete frequencies used to design the filter weights % % lower and upper limit in order to create extended frequency range cfg.lfreq_lim = 100; %lower limit cfg.hfreq_lim = 200; %to create higher limit % % set of frequencies used to design the filter weights %Note: Upper Bound + cfg.hfreq_lim <= cfg.srate, otherwise fir2 (below) %won't work cfg.frange = 300:cfg.fstep:(cfg.srate/2 - cfg.hfreq_lim); % % extended frequency range for computations: extends beamforming frequency range % computation in order to ensure a flat response across entire frequency range! cfg.frange_ext = (cfg.frange(1)-cfg.lfreq_lim):cfg.fstep:(cfg.frange(end)+cfg.hfreq_lim); % cfg.k_range_ext = 2*pi*cfg.frange_ext/cfg.c; % wavenumber (corresponding to extended computation frequency range) cfg.k_range = 2*pi*cfg.frange/cfg.c; % wavenumber (corresponding to beamformer frequency range) % cfg.WNG_dB = WNG_dB; cfg.WNG_lim = 10*log10(N); %limit of WNG if (cfg.WNG_dB > cfg.WNG_lim) disp(' ') disp('White noise gain cannot be larger than 10*log10(N_transducer) corresponding to a delay-and-sum beamformer.') eval(['disp(''Reverting to maximum possible WNG: ' num2str(cfg.WNG_lim) 'dB'')']) disp(' ') cfg.WNG_dB = cfg.WNG_lim; end % Converts WNG into an absolute number cfg.WNG = 10^(cfg.WNG_dB/10); % % Possibly NEEDS TO BE ADAPTED FOR POLYNOMIAL BEAMFORMER cfg.nmbr_look_dir = length(cfg.des_look_dir); %number of prototype look % directions (for simple FSB -> 1) %---------------------------------------------------------------------- % Initialisation of geometry dependent parameters cfg = BF_Array_Geometry(cfg); %---------------------------------------------------------------------- % Initialisation of look direction vector cfg = InitLookDirVec(cfg); %---------------------------------------------------------------------- % Initialising of matrices for the optimization problem % % ToDo: I think this needs to be adapted (regarding the concatenation) % for several desired look directions -> for polynomial beamforming % H.Barfuss, 10.11.14 % N_f_bins = length(cfg.k_range_ext); %number of (design-) frequencies %cfg.calG (\mathcal{G} in [Mabande et al, 2010]) includes the product %G(\omega_p)*D_i of Eq. (5) for each (design-) frequency \omega_p %stacked in vertical direction for each prototype look direction %dimension: [Num_DesiredLookDirections*theta_resolution,Num_mics*(P+1)] %(see definition of \mathcal{G} in [Mabande et al, 2010] between Eq. (5) and (6)) cfg.calG = []; %G_D is a temporary variable and will include the product G(\omega_p)*D_i %from Eq. (5) of dimension: [freq,Num_DesiredLookDirections,theta_resolution,Num_mics*(P+1)] %this product is computed for every (design-) frequency G_D = NaN(N_f_bins, 1, length(cfg.desResponse), N); %for-loop over each (design-) frequency for idx_frequency = 1:length(cfg.frange_ext) tmp3 = []; % calculation of G_D at frequency \omega_p of dimension [theta_resolution,Num_mics*(P+1)] for idx_look_dir = 1:cfg.nmbr_look_dir %cfg.G_ext = steering vector G_D(idx_frequency,idx_look_dir,:,:) = squeeze(cfg.G_ext(idx_frequency,:,:,idx_look_dir))*... squeeze(cfg.D(idx_look_dir,:,:)); % concatenating of matrices along first dimension -> % frequency-dependent G_D(\omega_p) are concatenated along vertical % direction tmp3 = cat(1,tmp3,squeeze(G_D(idx_frequency,idx_look_dir,:,:))); end %final result is stored in cfg.calG cfg.calG(idx_frequency,:,:) = tmp3; end % store all desired response (different for each desired prototype look % direction) in cfg.b_des (see Eq. (6) and definition before (6) in % [Mabande et al, 2010]) % % for cnt1 = 1:cfg.nmbr_look_dir %I think this for loop is not necessary cfg.b_des = cfg.desResponse(:); % end %---------------------------------------------------------------------- %---------------------------------------------------------------------- % CVX based Optimization % %---------------------------------------------------------------------- % This block of code performs the constraint optimization proposed in % [Mabande et al, 2010] to obtain the optimum filter weighs in the % design domain % The CVX toolbox is used to solve the (convex) optimization problem %---------------------------------------------------------------------- % % Use a waitbar to illustrate design progress % h_wb = waitbar(0, 'Beamformer is being designed...'); %---------------------------------------------------------------------- % variable for resulting optimum filter weights % This will include the optimum filter coefficients for the extended % design frequency range cfg.frange_ext flt.w_opt = NaN(cfg.N,N_f_bins); %for loop over each (design-) frequency for idx_frequency=1:length(cfg.k_range_ext) % ai_Di will include the product a^T_i(\omega_p)*D_i of dimension [1, N(P+1)] % on each row and is required for the distortionless constraint % -> Eq. (7) in [Mabande et al, 2010] % % Thus, ai_Di is of dimension [I, N(P+1)] (I: number of prototype % directions) % % Note: ai_Di is also already included in cfg.calD at position % squeeze(cfg.calG(idx_frequency,cfg.angular_resolution == cfg.DesAng(i),:)) ai_Di = []; for idx_look_dir = 1:cfg.nmbr_look_dir ai_Di(idx_look_dir,:) = squeeze(G_D(idx_frequency, idx_look_dir, cfg.angular_resolution.azimuth == cfg.DesAng.azimuth(idx_look_dir),:)); end % array responses at freq idx_frequency A = squeeze(cfg.calG(idx_frequency,:,:)); %------------------------------------------------------------------ % begin cvx optimization %------------------------------------------------------------------ cvx_begin % pause for 1 sec cvx_quiet(1) % complex variable declaration variable w(cfg.N*(cfg.P+1),1) complex; % minization of least-squares (LS) problem % -> Eq. (6) in [Mabande et al, 2010] minimize ( norm(A*w - cfg.b_des, 2) ); % constraints of LS problem subject to % for each prototype look direction one distortionless constraints % -> Eq. (7) in [Mabande et al, 2010] for idx_look_dir = 1:cfg.nmbr_look_dir imag(w.'*ai_Di(idx_look_dir,:).') == 0; real(w.'*ai_Di(idx_look_dir,:).') == 1; end % % For a response <= 1 % max(abs(A*w)) <= 1.0; % for each prototype look direction one WNG constraint % -> Eq. (8) in [Mabande et al, 2010] for idx_look_dir = 1:cfg.nmbr_look_dir norm(squeeze(cfg.D(idx_look_dir,:,:))*w,2) <= 1/sqrt(cfg.WNG); end cvx_end %------------------------------------------------------------------ %end of cvx optimization %------------------------------------------------------------------ % cvx_optval % Concatenate optimum filter coefficiens of current frequency % flt.w_opt contains the optimum filter weights of one filter at each row flt.w_opt(:,idx_frequency) = w; % % Update waitbar % waitbar(idx_frequency/N_f_bins, h_wb) end % % Close waitbar % close(h_wb); %---------------------------------------------------------------------- % FIR Approximation % %---------------------------------------------------------------------- % filter coefficient computation -> FIR approxmation of optimum filters % saved in flt.w_opt %---------------------------------------------------------------------- % w_opt_wholeFreqRange will contain the optimum filter weights to be % approximated by fir2 % % At frequencies that are not included in the extended set of design % frequencies cfg.frange_ext, the eps value is used w_opt_wholeFreqRange = ones((cfg.P+1)*cfg.N,(cfg.srate/2)/cfg.fstep+1)*eps; % F is a vector of frequency points in the range from 0 to 1, where 1 % corresponds to the Nyquist frequency (half the sampling frequency) % required for fir2 function F = (0:cfg.fstep:cfg.srate/2)/(cfg.srate/2); % write optimum filter weights of each filter to variable w_opt_wholeFreqRange % cfg.frange_ext/cfg.fstep+1 makes sure that at entries of w_opt_wholeFreqRange % corresponding to frequencies that are not included in the extended set of % design frequencies cfg.frange_ext (e.g. 0Hz) no optimum filger weight is stored % This is necessesary because fir2 requires information about the whole % frequency range between 0Hz ... fs/2Hz for cnt = 1:cfg.N*(cfg.P+1) w_opt_wholeFreqRange(cnt,cfg.frange_ext/cfg.fstep+1) = ... conj(flt.w_opt(cnt,:)); %Why conj() ? weiß wohl nur Edwin :-) end % tmp_firfilt: contains approximated filter coefficients for each % filter on one row % -> dimension: [N*(P+1),filt_len] tmp_firfilt = zeros((cfg.P+1)*cfg.N,cfg.filterlength); for idx_filters=1:cfg.N*(cfg.P+1) tmp_firfilt(idx_filters,:) = fir2(cfg.filterlength-1,F,... squeeze(w_opt_wholeFreqRange(idx_filters,:))); end % ordering coefficients in P+1 filter-and-sum subblocks of dimension % [Filter length, #Microphones]. cfg.PBF_firfilt is used later on in % BF_Plot_BP % PBF_firfilt: (P+1) x filterlength x Number of mics cfg.PBF_firfilt = zeros((cfg.P+1),cfg.filterlength,cfg.N);% [P+1,filt_len, N] for idx_mic = 1:cfg.N for idx_P = 1:cfg.P+1 cfg.PBF_firfilt(idx_P,:,idx_mic) = tmp_firfilt((idx_mic-1)*(cfg.P+1)+idx_P,:); end end %---------------------------------------------------------------------- %Choose look direction chosen from prototype look directions for which %the beampattern shall be plotted cfg.plot_LookDir = 1; %---------------------------------------------------------------------- %---------------------------------------------------------------------- % WNG % %---------------------------------------------------------------------- % In this section, the White Noise Gain (WNG) is computed for the % original design frequency range % First it is computed for cfg.frange_ext % Second, the resulting WNG is limited to cfg.frange %---------------------------------------------------------------------- % computing the frequenc responses with obtained fiter coefficients % (of approximated FIR filters) filt_real= zeros(cfg.N*(cfg.P+1),size(flt.w_opt,2)); for idx_filter=1:cfg.N*(cfg.P+1) %compute frequency response of approximated FIR filters H = freqz( flt.w_opt(idx_filter,:), 1, cfg.srate/2+1 ); %store compute frequency response of approximated FIR filters in %filt_real, one filter in each row filt_real(idx_filter,:) = H(cfg.frange_ext); end %---------------------------------------------------------------------- %Compute theoretical (-> WNG_theoretical) and real (-> WNG_real) WNGs % in the 'original' frequency range, not the extended frequency range %For the computation of the WNG, see e.g., Eq. (8) in [Mabande et al, %2010] WNG_theoretical_tmp = NaN(size(cfg.frange_ext)); WNG_real_tmp = NaN(size(cfg.frange_ext)); % for each for idx_freq_ext=1:length(cfg.frange_ext) % Steering Vector of dimension [#Microphones, 1] d = squeeze(G_D(idx_freq_ext,cfg.plot_LookDir, cfg.angular_resolution.azimuth == cfg.DesAng.azimuth(cfg.plot_LookDir),:)); % theoretical WNG (computed with optimum filter coefficients % flt.w_opt obtained from optimization problem WNG_theoretical_tmp(idx_freq_ext) = 10*log10( (abs(flt.w_opt(:,idx_freq_ext).'*d))^2/... ((squeeze(cfg.D(cfg.plot_LookDir,:,:))*flt.w_opt(:,idx_freq_ext))'*(squeeze(cfg.D(cfg.plot_LookDir,:,:))*flt.w_opt(:,idx_freq_ext))) ); % real/actual WNG (computed from approximated fir filter % coefficients in filt_real) WNG_real_tmp(idx_freq_ext) = 10*log10( (abs(filt_real(:,idx_freq_ext).'*d))^2/... ((squeeze(cfg.D(cfg.plot_LookDir,:,:))*filt_real(:,idx_freq_ext))'*(squeeze(cfg.D(cfg.plot_LookDir,:,:))*filt_real(:,idx_freq_ext))) ); end %save only WNG in the 'original' frequency range (cfg.frange), not in %the extended frequency range cfg.WNG_theoretical = WNG_theoretical_tmp(cfg.lfreq_lim/cfg.fstep+1:end - cfg.hfreq_lim/cfg.fstep); cfg.WNG_real = WNG_real_tmp(cfg.lfreq_lim/cfg.fstep+1:end - cfg.hfreq_lim/cfg.fstep); %---------------------------------------------------------------------- %---------------------------------------------------------------------- % Beampatterns % %---------------------------------------------------------------------- % In this section the resulting beampattern and WNG is plotted %---------------------------------------------------------------------- % Illustrate results cfg = BF_Plot_BP(cfg); %---------------------------------------------------------------------- %---------------------------------------------------------------------- % Set return values % %---------------------------------------------------------------------- % Filter impulse response of approximated FIR filters %fir_imp_resp = tmp_firfilt.'; fir_imp_resp = flt.w_opt; %Matrix of steering vectors for look direction for which the beampattern has been plotted G_plot = cfg.G_plot; %Magnitude of the beamformer response resp = cfg.BF_response_abs; % Frequency bins used for the plots faxis = cfg.frange_ext(:); % Angles used for the plots angaxis = cfg.DOA_degs_plot(:); % Resulting WNG of designed beamformer in dB realWNG_dB = cfg.WNG_real(:); end
github
ganlubbq/matlab_beam_doa-master
BF_Array_Geometry.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/Generalized_RLSFI_BF/BF_Array_Geometry.m
3,633
utf_8
64c0c8b993e6f54de5c7e419e83a2021
%-------------------------------------------------------------------------- % Array Geometry %-------------------------------------------------------------------------- function cfg = BF_Array_Geometry(cfg) switch (cfg.geometry) %------------------------------------------------------------------ % define array geometry (geometry-dependent variables) for linear array % positions of microphones defined in cartesian coordinate systems % according to [Van Trees, Optimum Array Processing, Fig.2.1] % x: right(>0), left(<0) % y: forward(>0), backward(<0) % z: above(>0), below(<0) % origin of array (x,y,z)=(0,0,0) assumed to be center microphone %------------------------------------------------------------------ case 1 % linear array if cfg.spacing == 0 %input non-uniform spacing manually switch cfg.design case 'freefield' switch cfg.nmic case 3 %left, right, and center microphone (mics: 1,5, and 9) %microphone positions always from left (mic 1) to %right (mic 9) cfg.mic_pos.x = [-7.5e-2 0 7.5e-2]; cfg.mic_pos.y = [-6e-2 0 -6e-2]; cfg.mic_pos.z = [-4e-2 0 -4e-2]; case 5 %(mics: 1, 3, 5, 7, and 9) cfg.mic_pos.x = [-7.5e-2 -3.375e-2 0 3.375e-2 7.5e-2]; cfg.mic_pos.y = [-6e-2 -0.75e-2 0 -0.75e-2 -6e-2]; cfg.mic_pos.z = [-4e-2 0 0 0 -4e-2]; case 7 %(mics: 1, 2, 4, 5, 6, 8, and 9) cfg.mic_pos.x = [-7.5e-2 -4.5e-2 -2.25e-2 0 2.25e-2 4.5e-2 7.5e-2]; cfg.mic_pos.y = [-6e-2 -1e-2 -0.5e-2 0 -0.5e-2 -1e-2 -6e-2]; cfg.mic_pos.z = [-4e-2 0 0 0 0 0 -4e-2]; case 9 %(mics: 1, 2, 3, 4, 5, 6, 7, 8, and 9) cfg.mic_pos.x = [-7.5e-2 -4.5e-2 -3.375e-2 -2.25e-2 0 2.25e-2 3.375e-2 4.5e-2 7.5e-2]; cfg.mic_pos.y = [-6e-2 -1e-2 -0.75e-2 -0.5e-2 0 -0.5e-2 -0.75e-2 -1e-2 -6e-2]; cfg.mic_pos.z = [-4e-2 0 0 0 0 0 0 0 -4e-2]; end case 'hrtf' switch cfg.nmic case 3 cfg.idx_hrtfs = [1 5 9]; case 5 cfg.idx_hrtfs = [1 3 5 7 9]; case 7 cfg.idx_hrtfs = [1 2 4 5 6 8 9]; case 9 cfg.idx_hrtfs = (1:9); end end else %uniform spacing automatically % initialisation of sensor positions cfg.mic_pos.x = linspace(-(cfg.nmic - 1)/2,(cfg.nmic - 1)/2,cfg.nmic)*cfg.spacing; cfg.mic_pos.y = zeros(size(cfg.mic_pos.x)); cfg.mic_pos.z = zeros(size(cfg.mic_pos.x)); end case 2 disp('not implemented yet'); end end
github
ganlubbq/matlab_beam_doa-master
InitLookDirVecORG.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/Generalized_RLSFI_BF/InitLookDirVecORG.m
1,981
utf_8
b0fc2f7e82155795dd8f7868654fc46f
%-------------------------------------------------------------------------- % Look Direction Vector %-------------------------------------------------------------------------- function [cfg] = InitLookDirVecORG(cfg) switch(cfg.int_choice) %------------------------------------------------------------------ % polynomial interpolation according to equation (4) in [Mabande et al,2010] %------------------------------------------------------------------ case 1 % create vector d %d includes all vectors d_{i}, i=0,...,I-1, with I being the % number of protype look directions, and % d_{i}=[D_{i}^{0}...D_{i}^{P}]^{T} includes all interpolation % values D (interpolation factors for each filter-ans-sum unit) %d = zeros(cfg.nmbr_look_dir,cfg.P+1); p = 0:cfg.P; for idx_look_dir=1:cfg.nmbr_look_dir cfg.d(idx_look_dir,:)=cfg.D_i(idx_look_dir).^p; % cfg.D_i: corresponding D for each look direction; D_i = (cfg.DesAng - 90)/90 for linear array and %cfg.d = cfg.D_i,cfg.nmbr_look_dir=1 cfg.P=0 % D = (cfg.DesAng - pi/cfg.N)/(pi/cfg.N) for circular array end case 2 %not implemented yet warning('Warning: There is no other interpolation implemented but polynomial interpolation at the moment.'); exit(1); end %---------------------------------------------------------------------- % Apply kronecker product (see Eq. (4) in [Mabande et al,2010]) % Result D of dimension [I, N, N(P+1)] including all D_{i}, i=0,...,I-1 % of dimension [N, N(P+1)], with N = #Microphones for idx_look_dir = 1:cfg.nmbr_look_dir cfg.D(idx_look_dir,:,:) = kron(eye(cfg.N),cfg.d(idx_look_dir,:)); end %-------------------------------------------------------------------------- end
github
ganlubbq/matlab_beam_doa-master
InitLookDirVec.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/Generalized_RLSFI_BF/InitLookDirVec.m
1,369
utf_8
490d36417fc2b1298fc7d601dad26910
%-------------------------------------------------------------------------- % Look Direction Vector %-------------------------------------------------------------------------- function [local] = InitLookDirVec(cfg,local) % create vector d %d includes all vectors d_{i}, i=0,...,I-1, with I being the % number of protype look directions, and % d_{i}=[D_{i}^{0}...D_{i}^{P}]^{T} includes all interpolation % values D (interpolation factors for each filter-ans-sum unit) %d = zeros(cfg.nmbr_look_dir,cfg.P+1); p = 0:local.P; for idx_look_dir=1:cfg.nmbr_look_dir local.d(idx_look_dir,:)=local.D_i(idx_look_dir).^p; % cfg.D_i: corresponding D for each look direction; D_i = (cfg.DesAng - 90)/90 for linear array and %cfg.d = cfg.D_i,cfg.nmbr_look_dir=1 cfg.P=0 % D = (cfg.DesAng - pi/cfg.N)/(pi/cfg.N) for circular array end %---------------------------------------------------------------------- % Apply kronecker product (see Eq. (4) in [Mabande et al,2010]) % Result D of dimension [I, N, N(P+1)] including all D_{i}, i=0,...,I-1 % of dimension [N, N(P+1)], with N = #Microphones for idx_look_dir = 1:cfg.nmbr_look_dir local.D(idx_look_dir,:,:) = kron(eye(cfg.nmic),local.d(idx_look_dir,:)); end %-------------------------------------------------------------------------- end
github
ganlubbq/matlab_beam_doa-master
BF_Plot_BP.m
.m
matlab_beam_doa-master/Desktop/Matlab_Code_Angabe/Generalized_RLSFI_BF/BF_Plot_BP.m
10,041
ibm852
360548fdc8e8d33735fe0fef2134445a
%-------------------------------------------------------------------------- % Plotting PBF Array Beampattern % %-------------------------------------------------------------------------- % This function plots the resulting beampattern of the polynomial % beamformer as well as the corresponding WNG %-------------------------------------------------------------------------- function cfg = BF_Plot_BP(cfg) %---------------------------------------------------------------------- % filt_real = frequency response of approximated FIR filters % dimension: (P+1) x #Microphones x frequency bins filt_real= []; % for i_PBF_firfilt = 1:cfg.P+1 for i_mics=1:cfg.N % compute frequency response of approximated FIR filter % cfg.PBF_firfilt contains filter coefficients of P+1 filter-and-sum subblocks % of dimension [Filter length, #Microphones] % -> dimension of cfg.PBF_firfilt: [(P+1) x filter length x % #Microphones] H = freqz(squeeze(cfg.PBF_firfilt(i_PBF_firfilt,:,i_mics)), 1, cfg.srate/2+1); %H = freqz(squeeze(cfg.w_opt(i_mics,:)), 1, cfg.srate/2+1); %save frequency respones in filt_real %here H(cfg.frange), since we only want to plot the beampattern % in the 'original frequency range', not the extended range filt_real(i_PBF_firfilt,i_mics,:) = H(cfg.frange); end end %---------------------------------------------------------------------- % --------------------------------------------------------------------- % create steering vectors for plotting the beampatterns for i_mics=1:cfg.N switch cfg.geometry case 1 % linear array %cfg.DOA_degs_plot: DoAs used to plot the beampattern in %degree cfg.DOA_degs_plot.azimuth = (0:5:180); cfg.DOA_degs_plot.elevation = repmat(cfg.DesAng.elevation,size(cfg.DOA_degs_plot.azimuth)); switch cfg.design case 'freefield' %x_mic: position vector of idx_micPos-th microphone x_mic = [cfg.mic_pos.x(i_mics); cfg.mic_pos.y(i_mics); cfg.mic_pos.z(i_mics)]; % G_plot: stores all steering vectors for current array geometry % created using the angular resolution cfg.DOA_degs_plot used % for plotting the beampattern % dimension: [frequency bins x #Angles for plotting x #Microphones] for idx_frequency = 1:length(cfg.k_range) %k_vec: wavevectors for current frequency i_frequency %and current microphone with respect to all source positions k_vec = - cfg.k_range(idx_frequency) * [sind(cfg.DOA_degs_plot.elevation).*cosd(cfg.DOA_degs_plot.azimuth); sind(cfg.DOA_degs_plot.elevation).*sind(cfg.DOA_degs_plot.azimuth); cosd(cfg.DOA_degs_plot.elevation)]; %%save steering vectors G_plot(idx_frequency,:,i_mics) = exp(-1i*k_vec.'*x_mic); end case 'hrtf' % create matrix of hrtfs used to plot the beampattern (for % original frequency range cfg.frange!) G_plot = permute(cfg.hrtfs(cfg.frange,cfg.idx_hrtfs,... cfg.DOA_degs_plot.azimuth/5+1),[1,3,2]); end case 2 % circular array %cfg.DOA_degs_plot: DoAs used to plot the beampattern in radians cfg.DOA_degs_plot.azimuth = (0:1:360); cfg.DOA_degs_plot.elevation = repmat(cfg.DesAng.elevation,size(cfg.DOA_degs_plot.azimuth)); %%TODO noch nicht geprüft for idx_frequency = 1:length(cfg.k_range) %k_vec: wavevectors for current frequency i_frequency %and current microphone with respect to all source positions k_vec = - cfg.k_range(idx_frequency) * [sind(cfg.DOA_degs_plot.elevation).*cosd(cfg.DOA_degs_plot.azimuth); sind(cfg.DOA_degs_plot.elevation).*sind(cfg.DOA_degs_plot.azimuth); cosd(cfg.DOA_degs_plot.elevation)]; %%save steering vectors G_plot(idx_frequency,:,i_mics) = exp(-1i*k_vec.'*x_mic); end end end % cfg.G_plot = G_plot; % --------------------------------------------------------------------- % --------------------------------------------------------------------- % Create beamformer response according to (1) in [Mabande et al, 2010] % % k_range: wavenumbers in defined range (e.g., cfg.frange = 300 - 3400 Hz); % BF_response will contain the beamformer response of the polynopmial % beamformer with respect to the chosen look direction for plotting indexed % by fg.plot_LookDir (which is set in RobustFSB.m) % dimension -> [frequency bins, #Angles for plotting] BF_response=zeros(length(cfg.k_range),length(cfg.DOA_degs_plot.azimuth)); % for each FSU and microphone (P+1: number of filter-and-sum units (FSUs), % N: Number of microphones) for i_FSUs = 1:cfg.P+1 tmp = []; for i_mics=1:cfg.N % d_lookDir: Includes includes all P+1 interpolation factors % corresponding to the chose plot-look direction % % cfg.plot_LookDir: index of a prototype look direction out of % array cfg.DesAng % cfg.d: contains the D_i.^p and is of size I x P+1, created in % InitLookDirVec.m d_lookDir = cfg.d(cfg.plot_LookDir,:); % temp includes the frequency responses of the approximated FIR % filters of the current FSU weighted with the corresponding % interpolation factor % dimension: [freq,length(cfg.DOA_degs_plot),N] tmp(:,:,i_mics)=repmat(squeeze(filt_real(i_FSUs,i_mics,:))*d_lookDir(i_FSUs),1,length(cfg.DOA_degs_plot.azimuth)); end %sum(G_plot.*tmp,3) creates the beamformer response of the current %FSU, weighted with the corresponding interpolation factor %the sum over all FSUs (outer loop) creates the overall beamformer %response according to (1) in [Mabande et al, 2010] BF_response = BF_response + sum(G_plot.*tmp,3); end % save created beamformer response cfg.BF_response = BF_response; % --------------------------------------------------------------------- % --------------------------------------------------------------------- %Plot beampattern, response in look direction and WNGs % --------------------------------------------------------------------- % save look direction for which beampattern should be plotted des_angle = cfg.des_look_dir.azimuth(cfg.plot_LookDir); % take absolute value of beamformer response and normalize to maximum % value BF_response_abs=abs(BF_response); BF_response_abs=BF_response_abs/max(max(BF_response_abs)); %compute beampattern BPattern=20*log10(BF_response_abs); %limit lower values to -40dB a=find(BPattern<-40); BPattern(a)=-40; %save beampattern in cfg structure cfg.BPattern = BPattern; cfg.BF_response_abs = BF_response_abs; b=0; if b==0 % --------------------------------------------------------------------- %plot beampattern (created from approximated FIR filters) figure subplot(2,2,[1 3]); imagesc(cfg.DOA_degs_plot.azimuth,cfg.frange,BPattern) xlabel('DOA in degrees') ylabel('Frequency in Hz') title('Beampattern (FIR approx)') colorbar % --------------------------------------------------------------------- %compute beamformer response in look direction BF_lookDir_abs=BF_response_abs(:,find(cfg.DOA_degs_plot.azimuth == round(des_angle))); BF_lookDir_abs_log = 20*log10(BF_lookDir_abs); %limit from below by -20dB a=find(BF_lookDir_abs_log<-20); BF_lookDir_abs_log(a)=-20; %save desired response in look direction cfg.BF_lookDir_abs_log = BF_lookDir_abs_log; % --------------------------------------------------------------------- %plot response in look direction subplot(2,2,2); semilogx(cfg.frange,BF_lookDir_abs_log,'LineWidth',2); axis([10^(log10(cfg.frange(1))) 10^(log10(cfg.frange(end))) -20 0.1]); grid on; xlabel('Frequency in Hz'); ylabel('Response in dB') title(['Response in look-direction \vartheta = ', num2str(des_angle)]) % set(gca, 'xtick', [400:100:1000, 2000, 3000]); % set(gca, 'xticklabel', {'' '500' '' '' '' '' '1000' '' '3000'}); % --------------------------------------------------------------------- %plot theoretical wng, real wng, and difference between theoretical and %real wng subplot(2,2,4) % plot(cfg.frange,cfg.WNG_theoretical,'b') semilogx(cfg.frange,cfg.WNG_real,'LineWidth',2); hold on; semilogx(cfg.frange,cfg.WNG_theoretical,'--r','LineWidth',2); semilogx(cfg.frange,cfg.WNG_theoretical-cfg.WNG_real,'-.k','LineWidth',2); legend('real WNG','theoretical WNG', 'difference') grid on xlim([10^(log10(cfg.frange(1))) 10^(log10(cfg.frange(end)))]); xlabel ('Frequency in Hz') ylabel ('White Noise Gain in dB') ylim([min(cfg.WNG_real)-3, max( max(cfg.WNG_real), min(cfg.WNG_real)+10)]) % legend('Expected White Noise Gain','White Noise Gain realized by the FIR-filter',4) hold on % set(gca, 'xtick', [400:100:1000, 2000, 3000]); % set(gca, 'xticklabel', {'' '500' '' '' '' '' '1000' '' '3000'}); end end
github
ganlubbq/matlab_beam_doa-master
estimate_cdr_nodiffuse.m
.m
matlab_beam_doa-master/cdr-demo/estimate_cdr_nodiffuse.m
1,396
utf_8
43c131381f4fd4e5b552a8f25639bc4e
%ESTIMATE_CDR_NODIFFUSE % Unbiased estimation of the Coherent-to-Diffuse Ratio (CDR) from the complex % coherence of a mixed (noisy) signal, without assuming knowledge of the noise % coherence. Equivalent to CDRprop4 in [1]. % % CDR = estimate_cdr_nodiffuse(X, NaN, S) % X: complex coherence of mixed (noisy) signal % NaN: second argument is unused % S: coherence of signal component (magnitude one) % % Reference: % Andreas Schwarz, Walter Kellermann, "Coherent-to-Diffuse Power Ratio % Estimation for Dereverberation", IEEE/ACM Trans. on Audio, Speech and % Lang. Proc., 2015 (under review); preprint available: arXiv:1502.03784 % PDF: http://arxiv.org/pdf/1502.03784 % % Andreas Schwarz ([email protected]) % Multimedia Communications and Signal Processing % Friedrich-Alexander-Universitaet Erlangen-Nuernberg (FAU) % Cauerstr. 7, 91058 Erlangen, Germany function CDR = estimate_cdr_nodiffuse(Cxx,~,Css) Css = bsxfun(@times, ones(size(Cxx)), Css); % limit the magnitude of Cxx to prevent numerical problems magnitude_threshold = 1-1e-10; critical = abs(Cxx)>magnitude_threshold; Cxx(critical) = magnitude_threshold .* Cxx(critical) ./ abs(Cxx(critical)); CDR = imag(Cxx)./(imag(Css) - imag(Cxx)); CDR(imag(Css)./imag(Cxx)<=1) = Inf; CDR(imag(Css)./imag(Cxx)<=0) = 0; % Ensure we don't get any negative or complex results due to numerical effects CDR = max(real(CDR),0); end
github
ganlubbq/matlab_beam_doa-master
estimate_cdr_robust_unbiased.m
.m
matlab_beam_doa-master/cdr-demo/estimate_cdr_robust_unbiased.m
1,614
utf_8
cd460a3538aae3a4bcb2f0eb44bbe582
%ESTIMATE_CDR_ROBUST_UNBIASED % Unbiased estimation of the Coherent-to-Diffuse Ratio (CDR) from the complex % coherence of a mixed (noisy) signal, using knowledge of both signal and noise % coherence. This is a variation of estimate_cdr_unbiased which shows better % performance in practice. Equivalent to CDRprop2 in [1]. % % CDR = estimate_cdr_nodiffuse(X, N, S) % X: complex coherence of mixed (noisy) signal % N: coherence of noise component (real-valued) % S: coherence of signal component (magnitude one) % % Reference: % Andreas Schwarz, Walter Kellermann, "Coherent-to-Diffuse Power Ratio % Estimation for Dereverberation", IEEE/ACM Trans. on Audio, Speech and % Lang. Proc., 2015 (under review); preprint available: arXiv:1502.03784 % PDF: http://arxiv.org/pdf/1502.03784 % % Andreas Schwarz ([email protected]) % Multimedia Communications and Signal Processing % Friedrich-Alexander-Universitaet Erlangen-Nuernberg (FAU) % Cauerstr. 7, 91058 Erlangen, Germany function CDR = estimate_cdr_robust_unbiased(Cxx,Cnn,Css) Css = bsxfun(@times, ones(size(Cxx)), Css); Cnn = bsxfun(@times, ones(size(Cxx)), Cnn); % limit the magnitude of Cxx to prevent numerical problems magnitude_threshold = 1-1e-10; critical = abs(Cxx)>magnitude_threshold; Cxx(critical) = magnitude_threshold .* Cxx(critical) ./ abs(Cxx(critical)); CDR = 1./(-abs(Cnn-exp(1j*angle(Css)))./(Cnn.*cos(angle(Css))-1)).*abs((exp(-1j*angle(Css)).*Cnn - (exp(-1i*angle(Css)).*Cxx))./(real(exp(-1i*angle(Css)).*Cxx) - 1)); % Ensure we don't get any negative or complex results due to numerical effects CDR = max(real(CDR),0); end
github
ganlubbq/matlab_beam_doa-master
estimate_cdr_nodoa.m
.m
matlab_beam_doa-master/cdr-demo/estimate_cdr_nodoa.m
1,389
utf_8
b12850a707e91ffd8c8be07b04f04121
%ESTIMATE_CDR_NODOA % Blind (DOA-independent), unbiased estimation of the Coherent-to-Diffuse Ratio (CDR) % from the complex coherence of a mixed (noisy) signal. Equivalent to CDRprop3 in [1]. % % CDR = estimate_cdr_nodoa(Cxx, Cnn) % Cxx: complex coherence of mixed (noisy) signal % Cnn: coherence of noise component (real-valued) % % Reference: % Andreas Schwarz, Walter Kellermann, "Coherent-to-Diffuse Power Ratio % Estimation for Dereverberation", IEEE/ACM Trans. on Audio, Speech and % Lang. Proc., 2015 (under review); preprint available: arXiv:1502.03784 % PDF: http://arxiv.org/pdf/1502.03784 % % Andreas Schwarz ([email protected]) % Multimedia Communications and Signal Processing % Friedrich-Alexander-Universitaet Erlangen-Nuernberg (FAU) % Cauerstr. 7, 91058 Erlangen, Germany function CDR = estimate_cdr_nodoa(Cxx,Cnn,~) Cnn = bsxfun(@times, ones(size(Cxx)), Cnn); % extend to dimension of Cxx % limit the magnitude of Cxx to prevent numerical problems magnitude_threshold = 1-1e-10; critical = abs(Cxx)>magnitude_threshold; Cxx(critical) = magnitude_threshold .* Cxx(critical) ./ abs(Cxx(critical)); CDR = (-(abs(Cxx).^2 + Cnn.^2.*real(Cxx).^2 - Cnn.^2.*abs(Cxx).^2 - 2.*Cnn.*real(Cxx) + Cnn.^2).^(1/2) - abs(Cxx).^2 + Cnn.*real(Cxx))./(abs(Cxx).^2-1); % Ensure we don't get any negative or complex results due to numerical effects CDR = max(real(CDR),0); end
github
ganlubbq/matlab_beam_doa-master
estimate_cdr_unbiased.m
.m
matlab_beam_doa-master/cdr-demo/estimate_cdr_unbiased.m
1,446
utf_8
0c57df9c844aec6695d9f99e28e8f4c2
%ESTIMATE_CDR_UNBIASED % Unbiased estimation of the Coherent-to-Diffuse Ratio (CDR) from the complex % coherence of a mixed (noisy) signal, using knowledge of both signal and noise % coherence. Equivalent to CDRprop1 in [1]. % % CDR = estimate_cdr_nodiffuse(X, N, S) % X: complex coherence of mixed (noisy) signal % N: coherence of noise component (real-valued) % S: coherence of signal component (magnitude one) % % Reference: % Andreas Schwarz, Walter Kellermann, "Coherent-to-Diffuse Power Ratio % Estimation for Dereverberation", IEEE/ACM Trans. on Audio, Speech and % Lang. Proc., 2015 (under review); preprint available: arXiv:1502.03784 % PDF: http://arxiv.org/pdf/1502.03784 % % Andreas Schwarz ([email protected]) % Multimedia Communications and Signal Processing % Friedrich-Alexander-Universitaet Erlangen-Nuernberg (FAU) % Cauerstr. 7, 91058 Erlangen, Germany function CDR = estimate_cdr_unbiased(Cxx,Cnn,Css) Css = bsxfun(@times, ones(size(Cxx)), Css); Cnn = bsxfun(@times, ones(size(Cxx)), Cnn); % limit the magnitude of Cxx to prevent numerical problems magnitude_threshold = 1-1e-10; critical = abs(Cxx)>magnitude_threshold; Cxx(critical) = magnitude_threshold .* Cxx(critical) ./ abs(Cxx(critical)); CDR = real(exp(-1j*angle(Css)).*Cnn - (exp(-1i*angle(Css)).*Cxx))./(real(exp(-1i*angle(Css)).*Cxx) - 1); % Ensure we don't get any negative or complex results due to numerical effects CDR = max(real(CDR),0); end
github
ganlubbq/matlab_beam_doa-master
estimate_delay_gcc_phat.m
.m
matlab_beam_doa-master/cdr-demo/lib/estimate_delay_gcc_phat.m
787
utf_8
2e7e08ecee1ab7c234ed1462ea89eab0
%ESTIMATE_DELAY_GCC_PHAT Delay estimation using GCC-PHAT. % % Estimates the delay between two signals using the GCC-PHAT method. % Returns the delay % in samples. % % Andreas Schwarz ([email protected]), Dec. 2014 function shift = estimate_delay_gcc_phat(x1,x2) factor = 20; % oversampling (padding) factor to increase time resolution nfft=1024; window=hanning(nfft); n_overlap = nfft/2; X1 = specgram(x1,nfft,1,window,n_overlap); X2 = specgram(x2,nfft,1,window,n_overlap); delta = 10; % regularization constant norm_CPSD = mean(X1.*conj(X2),2)./mean((abs(X1.*conj(X2))+delta),2); % padding to increase time resolution of the cross-correlation function c = fftshift(ifft(norm_CPSD,factor*nfft,'symmetric')); %plot(c); [~,shift] = max(c); shift = (shift-(length(c)/2+1))/factor;
github
ganlubbq/matlab_beam_doa-master
spectral_subtraction.m
.m
matlab_beam_doa-master/cdr-demo/lib/spectral_subtraction.m
867
utf_8
e1c1554ffadfa5ec0f73ab2c6b196574
%SPECTRAL_SUBTRACTION Compute spectral subtraction weights. % % weights = spectral_subtraction(SNR,alpha,beta,mu,Gmin) % % alpha = 1; beta = 1; % power subtraction % alpha = 2; beta = 0.5; % magnitude subtraction % alpha = 2; beta = 1; % Wiener filter % mu: noise overestimation % Gmin: gain floor % % Andreas Schwarz ([email protected]) % Multimedia Communications and Signal Processing % Friedrich-Alexander-Universitaet Erlangen-Nuernberg (FAU) % Cauerstr. 7, 91058 Erlangen, Germany function weights = spectral_subtraction(SNR,alpha,beta,mu,Gmin) if (nargin == 1) % default: magnitude subtraction alpha = 2; beta = 0.5; mu = 1; end if ~exist('Gmin','var') Gmin = 0.1; end SNR = max(SNR,0); weights = max(1 - (mu./(SNR + 1)).^beta, 0).^alpha; weights = max(weights,0); weights = max(sqrt(weights),Gmin); end
github
rushilanirudh/tsrvf-master
findP2_from_P1_A.m
.m
tsrvf-master/grassmann/GrassmannCodes/Grassmann_Projection/findP2_from_P1_A.m
698
utf_8
61a0e4fae53930bf5f4d76f94a18c24e
% Feb 21-10 % Given point P1 and velocity A, find point P2 reached in unit time by % following a geodesic starting at P1 and having velocity A % input: P1,A,U (can be tensors) where and Q is the identity component on % Projection group % P2 = findP2_from_P1_A(P1, A, U, t) % inputs can be a batch of matrices in tensor format % p2 = U*expm(tX)*U'*P1*U*expm(tX')*U'; function P2 = findP2_from_P1_A(P1, A, U, t) n = size(A,2)+2; for i = 1: size(A,3) A_1 = A(:,:,i); U_1= U(:,:,i); P_1 = P1(:,:,i); X = [zeros(2) , A_1 ; -A_1' zeros(n-2)]; V = U_1*expm(t*X)*U_1'; P2(:,:,i) = V*P_1*V'; end
github
rushilanirudh/tsrvf-master
findVelocity_A_QtoP.m
.m
tsrvf-master/grassmann/GrassmannCodes/Grassmann_Projection/findVelocity_A_QtoP.m
1,232
utf_8
067b8876f6584a30de623c1d8b27cb2b
% Feb 24-10 % find velocity X, from Q to given P function [A,X] = findVelocity_A_QtoP(Q,P) B = Q - P; [W,D] = eig(B); W = real(W); D = real(D); eig_values = diag(D); temp = abs(eig_values); temp(temp<1e-5)=0; eig_values(temp==0)=0; % D must be in the format diag(a,-a,b,-b,.,0,0..); [sEig,Ind]=sort(eig_values,'descend'); W = W(:,Ind); i=1; Ind = []; n = length(temp); while (sEig(i)>0) Ind=[Ind,i,n-i+1]; i=i+1; end Ind=[Ind i:n-i+1]; W = W(:,Ind); D = diag(sEig(Ind)); eig_values = diag(D); omega = zeros(size(D)); omega_tild = eye(size(D)); for i=1:2:nnz(temp) r1 = eig_values(i); r2 = eig_values(i+1); if (r1+r2 < 1e-6) % must be otherwise sth is wrong (r1=-r2) lambda = abs(r1); replacement1 = [0 -asin(lambda) ; asin(lambda) 0]; replacement2 = [sqrt(1-lambda^2) -lambda ; lambda sqrt(1-lambda^2)]; % fix Q.wj c = W(1,i+1)/W(1,i); c_tild = c/abs(c); W(:,i) = c_tild*W(:,i); else disp('ERROR') return; end omega(i:i+1,i:i+1) = replacement1; omega_tild(i:i+1,i:i+1) = replacement2; end X = W*omega*W'; X(abs(X)<1e-5)=0; A = X(1:2,3:end); % for check: expm(X) = W*omega_tild*W';
github
rushilanirudh/tsrvf-master
extrinsicMean.m
.m
tsrvf-master/grassmann/GrassmannCodes/Grassmann_Projection/extrinsicMean.m
291
utf_8
65bf88621fcb646d72b0f0960bacbfc7
% Feb 21-10 % compute the exterinsic mean of a set of projection matrix function Pmean = extrinsicMean(Pt) % Pt = tensor, each 2D matrix is a P n = size(Pt,1); Q = [eye(2) ,zeros(2,n-2);zeros(n-2,2) zeros(n-2)]; G = sum(Pt,3)/size(Pt,3); [U,S,V] = svd(G); Pmean = U * Q * U';
github
rushilanirudh/tsrvf-master
subspace2image.m
.m
tsrvf-master/grassmann/GrassmannCodes/Grassmann_Projection/subspace2image.m
669
utf_8
8ad9c171d0614298f5563d1d3ce97ac1
% Feb 22-10 % map from subspace to landmark space by calculating the afffine matrix function L = subspace2image(P, imgSpace) % L = subspace2image(P, L_part, RigidIndex) % P is the projection matrix which represents a subspace on Grassmann % L_part is the landmarks we already have on the image (with RigidIndex as their indices) % L is the full landmark matrix from transforming P to the image L_part = imgSpace.L; RigidIndex = imgSpace.indx; [U,Y] = phi_inv(P); % find A(3*2) such that: L = Y1*A where Y1=[Y,1] Y_append = [Y, ones(size(Y,1),1)]; Y_part = Y_append(RigidIndex,:); A = Y_part\L_part; L = Y_append*A; L = round(L);
github
rushilanirudh/tsrvf-master
grassmannRep.m
.m
tsrvf-master/grassmann/GrassmannCodes/Grassmann_Projection/grassmannRep.m
328
utf_8
78f0b2b39fdd798b9a06b23763e13be0
% Feb 17-10 % find the procrustes representation for landmark matrix on Grassmann % Manifold %[out, Rot, trans] = grassmannRep(L) % out*Rot+repmat(trans,size(out,1),1) = L; function [out, Rot, trans] = grassmannRep(L) L_mz = L - repmat(mean(L),length(L),1); [U,S,V] = svd(L_mz,'econ'); out = U; Rot = S*V'; trans = mean(L);
github
rushilanirudh/tsrvf-master
findVelocity_A_P1toP2.m
.m
tsrvf-master/grassmann/GrassmannCodes/Grassmann_Projection/findVelocity_A_P1toP2.m
426
utf_8
3f04e7c6dfe6fd698a7d6780c1cf5f34
% Feb 23-10 % compute velocity matrix, A, between two subspace having projeciton % matrices ans subspaces representation % [A,X] = findVelocity_A_P1toP2(P1, P2, Q) function [A,X] = findVelocity_A_P1toP2(P1, P2) % P1 = U.Q.U' n = size(P1,1); Q = [eye(2), zeros(2,n-2);zeros(n-2,2) zeros(n-2)]; % Q is fixed for the entire program %[U,Y] = phi_inv(P1); [U,uu,vv] = svd(P1); P = U'*P2*U; [A,X] = findVelocity_A_QtoP (Q,P);
github
rushilanirudh/tsrvf-master
phi_inv.m
.m
tsrvf-master/grassmann/GrassmannCodes/Grassmann_Projection/phi_inv.m
551
utf_8
bc4522aa49b585dd247618ef46542f49
% Feb 24-10 % function phi: SO(3)-->P % phi(U) = UQU' % [U,Y] = phi_inv(P) function [U,Y] = phi_inv(P) % P = U.Q.U' n = size(P,1); if (0) colSpc = rref(P); tmp = eye(size(P)); flag = (colSpc == repmat(tmp(:,1),1,size(P,2))); ind1 = find(sum(flag,1)==size(P,2)); flag = (colSpc == repmat(tmp(:,2),1,size(P,2))); ind2 = find(sum(flag,1)==size(P,2)); Y1 = P(:,[ind1,ind2]); else Y1 = P(:,[1,2]); end [Y,uu,vv] = svd(Y1,'econ'); [U,uu,vv] = svd(P); %U = [Y,rand(n,n-2)]; ---> bad-bad-bad-bad %[U,R] = qr(U);
github
jasnap/philogenetic_trees-master
tree_plot.m
.m
philogenetic_trees-master/tree_plot.m
1,449
utf_8
f9d92d08126da9a08bd6ba451697a845
%-------------- tree_plot ----------- % This function plots the phylogenetic tree calculated by BrB algorithm % % Input: % optimal_model - Optimal model calculated by BrB % u_model - Optimal model with negative internal nodes % function tree_plot(optimal_model, u_model, score, name_matrix) optimal_model(1) = 1; n = length(optimal_model); nodes = zeros(1, n); j = 1; %find parents for i = 1:n if(u_model(i) < 0) u_parents(j) = i; o_parents(j) = optimal_model(i); j = j + 1; end end j = 1; m = length(u_parents); for i = 1:n if(any(optimal_model(i) == o_parents)) [ch1 ch2] = children(u_model, u_model(i)); if(ch1 > 0 && ch2 > 0) % if children are both leaves nodes(ch1) = optimal_model(i); nodes(ch2) = optimal_model(i); else index1 = find(u_model == ch1); index2 = find(u_model == ch2); ch1 = optimal_model(index1); ch2 = optimal_model(index2); nodes(ch1) = optimal_model(i); nodes(ch2) = optimal_model(i); end end end figure nodes(1) = max(optimal_model); treeplot(nodes, 'o', 'k') title(['Phylogenetic tree using Maximum Parsimony with score ',num2str(score)]) ylabel('Evolutionary distance') [x,y] = treelayout(nodes); for ii=1:length(name_matrix) text(x(ii), y(ii)-0.02, name_matrix(ii)); end set(gca,'XtickLabel',[],'YtickLabel',[]); xlabel('') camroll(90) end
github
jasnap/philogenetic_trees-master
ExhaustiveSearch.m
.m
philogenetic_trees-master/ExhaustiveSearch.m
1,007
utf_8
3cf8a4af3bbbf983bfe41f9e3b293805
%------------ ExhaustiveSearch ----------- % This function for searching trees with Exhaustive search method % % Input: % set_of_seq - Matrix that contains all input sequences % Output: % optimal_score - Best score of all trees % optimal_model - Tree model for the best score function [optimal_score, optimal_model] = ExhaustiveSearch(set_of_seq, name_matrix) [row, col] = size(set_of_seq); id = treeID(row); best_score = Inf; k = 1; [id_row, id_col] = size(id); for i = 1:id_row type = tree_type(id(i,:)); if type == 2 [out_model, out_score] = FitchScoring(id(i, :), set_of_seq); if out_score <= best_score best_score = out_score; best_model = out_model; model = treeModelGen(id(i, :)); end end end optimal_model = best_model; optimal_score = best_score; tree_plot(optimal_model, model, optimal_score, name_matrix); end
github
jasnap/philogenetic_trees-master
get_row_count.m
.m
philogenetic_trees-master/get_row_count.m
375
utf_8
ae75b810d63d2fcfbf6f04ab242fa604
%------- get_row_count -------- % This function calculates the number of all possible trees for a set of % sequences % % Input: % n - Number of input sequences % Output: % number - Number of possible trees function number = get_row_count(n) if(n > 2) number = 1 + factd(2*(n-1)-5) + factd(2*n-5); else number = 0; end end
github
jasnap/philogenetic_trees-master
BrB.m
.m
philogenetic_trees-master/BrB.m
1,472
utf_8
c1e27af46d4578537280d6cbf4b75483
%----------------- BrB -------------------- % This function implements Branch and bound optimization of Maximum Parsimony % % Input: % set_of_seq - Set of data with important information about sequences % Output: % optimal_score - Optimal score calculated % optimal_model - Model with the optimal score % function [optimal_score, optimal_model] = BrB(set_of_seq, name_matrix) [row, col] = size(set_of_seq); last_id = last_tree(row); best_score = Inf; k = 1; partID = partial_treeID(row); [mrow, mcol] = size(partID); for i = 1:mrow %score first partial tree first_id = partID(i, :); [first_model,first_score] = FitchScoring(first_id, set_of_seq); prev= first_id; if(first_score < best_score) %score all derivative trees for j = 1:last_id(end) new_id = gen_complete_tree(prev, last_id); prev = new_id; [new_model,new_score] = FitchScoring(new_id, set_of_seq); if(new_score <= best_score) best_score = new_score; best_model = new_model; model = treeModelGen(new_id); best_id = new_id; k = k + 1; end end end end optimal_score = best_score; optimal_model = best_model; tree_plot(optimal_model, model, optimal_score, name_matrix); end
github
jasnap/philogenetic_trees-master
get_row_odd.m
.m
philogenetic_trees-master/get_row_odd.m
286
utf_8
48629e52362a91d56b722393ce6f75a5
%----------- get_row_odd------------- % Function that calculates odd rows % % Input: % n - Number of input sequences % Output: % odd - Number of odd sequences function odd = get_row_odd(n) n = n - 3; odd = 1; for i = 1:n odd = odd + 2; end end
github
jasnap/philogenetic_trees-master
P_BrB.m
.m
philogenetic_trees-master/P_BrB.m
2,028
utf_8
c89894b13c80b76fa5cae2cbadb0c56b
%---------------- P_BrB ------------------------ % This function implements parallel Branch and bound on CPU % % Input: % set_of_seq - Set of sequences for calculating trees % Output: % optimal_score - Calculated optimal score % optimal_model - Model with the calculated optimal score % function [optimal_score, optimal_model] = P_BrB(set_of_seq, name_matrix) [row, col] = size(set_of_seq) last_id = last_tree(row); best_score = Inf; partID = partial_treeID(row); [mrow, mcol] = size(partID); [row col] = size(partID); tic a = distributed(rot90(partID)); spmd p = rot90(getLocalPart(a), -1); end spmd [mrow, mcol] = size(p); for i = 1:mrow %score first partial tree first_id = p(i, :); [first_model,first_score] = FitchScoring(first_id, set_of_seq); prev= first_id; if(first_score < best_score) %score all derivative trees for j = 1:last_id(end) new_id = gen_complete_tree(prev, last_id); prev = new_id; [new_model,new_score] = FitchScoring(new_id, set_of_seq); if(new_score <= best_score) best_score = new_score; best_model = new_model; model = treeModelGen(new_id); test_id = new_id; end end end end end toc optimal_model = gather(best_model); optimal_score = gather(best_score); temp_umodel = gather(model); [row, col] = size(optimal_score); optimal_id = gather(test_id); temp_score = Inf; for i = 1:col if(optimal_score{i} <= temp_score) temp_score = optimal_score{i}; temp_model = optimal_model{i}; umodel = temp_umodel{i}; tree_plot(temp_model, umodel, temp_score, name_matrix); end end end
github
jasnap/philogenetic_trees-master
gen_complete_tree.m
.m
philogenetic_trees-master/gen_complete_tree.m
606
utf_8
4714861748185a1d891ee1ade3718036
%------------ gen_complete_tree(previous, last)---------------------- % % This function generates a complete tree based on inputs previous and % last % % Input: % previous - Previous complete tree that was scored % last - Last possible complete tree that can be derived from given % partial tree % Output: % t - Calculated complete tree function t = gen_complete_tree(previous, last) next_tree = previous; if(next_tree(end) ~= last(end)) next_tree(end) = previous(end) + 1; t = next_tree; else disp('t is zero') t = 0; end end
github
jasnap/philogenetic_trees-master
treeModelGen.m
.m
philogenetic_trees-master/treeModelGen.m
634
utf_8
74d424c7a9e1d7838a8a7fb47aa8d945
%------------- treeModelGen --------------- % This function generates a tree model based on the ID of the tree % % Input: % id - Identification number of the tree % Output: % model - Generated model of the given tree id function model = treeModelGen(id) model(1, 1) = 1; model(1, 2) = 2; internal_node = 0; for i = 3:length(id) new_el = i; if(id(i) ~= 0) internal_node = internal_node - 1; io = id(i) + 1; add_to_end = model(io); model(io) = internal_node; model = [model( 1 : end) add_to_end new_el]; end end end
github
jasnap/philogenetic_trees-master
partial_treeID.m
.m
philogenetic_trees-master/partial_treeID.m
1,250
utf_8
2c82615bc9370b8988ea86488e1ff2fc
%------------ partial_treeID(n)-------------------------- % % This function generates all partial trees for given number of sequences % % Input: % n - Number of input sequences % Output: % matrix - Matrix containing all possible partial trees function matrix = partial_treeID(n) init_id = zeros(1, 2); init_id(:, 3:n) = 1; init_id(end) = 0; last_id = [zeros(1, 2) 1]; k = 1; for i = 3 : n - 1 last_id(i + 1) = last_id(i) + 2; end last_id(end) = 0; levels = n - 1; p = levels; ID = init_id; flag = 1; while(flag) for j = 1:last_id(n-1) temp = j; ID(end-1) = temp; matrix(k, :) = ID; k = k + 1; end if(isequal(ID, last_id)) flag = 0; break; end if(p > 3) if(isequal(ID(:, p:length(ID)),last_id(:, p:length(last_id)))) p = p - 1; tmp = ID(p) + 1; ID(p) = tmp; else tmp = ID(p) + 1; ID(p) = tmp; ID(end-1) = 0; end else tmp = ID(p) + 1; ID(p) = tmp; end end end
github
jasnap/philogenetic_trees-master
fasta_rd.m
.m
philogenetic_trees-master/fasta_rd.m
738
utf_8
3b24e4b98f2f7b53273b2e557af2ef30
%------------- fasta_rd -------------- % This function preprocesses input fasta sequences % % Input: % f - Read fasta file % Output: % data - Data readable for the BrB function % function data = fasta_rd(f) SeqsMultiAligned = multialign(f); [row, col] = size(SeqsMultiAligned); for i = 1:row temp = SeqsMultiAligned(i).Sequence; matrix{i, :} = temp; end for i = 1:row data(i, :) = matrix{i}; end [row, col] = size(data); for i = 1:row for j = 1:col if(~isequal(data(i, j), 'A')... && ~isequal(data(i, j), 'C')... && ~isequal(data(i, j), 'T')... && ~isequal(data(i, j), 'G')) data(i, j) = '-'; end end end end
github
jasnap/philogenetic_trees-master
FitchScoring.m
.m
philogenetic_trees-master/FitchScoring.m
1,541
utf_8
4cbf23b1022193d73d68742faf25bcb1
% -------------- FitchScoring------------ % This function calculates score of a tree using Fitch scoring algorithm % % Input: % id - Id of the tree it is scoring % set_of_seq - Matrix of input sequences % Output: % out_model - Model of the output tree % out_score - Calculated score function [out_model, out_score] = FitchScoring(id, set_of_seq) model = treeModelGen(id); out_model = model; out_score = 0; new_node = model(end); k = 1; flag = 1; for i = 1:length(model) if model(i) < 0 int_nodes1(1, k) = model(1,i); k = k+1; end end int_nodes = sort(int_nodes1); while flag == 1 i = 1; while i<= length(int_nodes) temp = out_model; [ch1, ch2] = children(temp, int_nodes(i)); if(ch1 > 0 && ch2 >0) [score, new_seq] = Merge(set_of_seq(ch1, :),set_of_seq(ch2, :)); new_node = new_node + 1; temp(temp == int_nodes(i)) = new_node; set_of_seq(new_node, :) = new_seq; out_score = out_score + score; int_nodes(i) = []; end out_model = temp; i = i +1; end if(isempty(int_nodes)) flag = 0; end end [score, new_seq] = Merge(set_of_seq(1, :),set_of_seq(new_node - 1, :)); new_node = new_node + 1; set_of_seq(new_node, :) = new_seq; out_score = out_score + score; out_model(1) = new_node; end
github
jasnap/philogenetic_trees-master
treeID.m
.m
philogenetic_trees-master/treeID.m
1,093
utf_8
cb43795b9ad99831e878df5c0e9a999a
%--------------- treeID --------------- % This function generates all possible trees % % Input: % n - Number of input sequences % Output % output - matrix with all possible trees and theis id numbers function output = treeID(n) row = get_row_count(n); output = zeros(row, n); % set 3rd column to 1 output(:,3) = 1; % setting last row last_row_odd = get_row_odd(n); for i = n-3:row output(i,n) = mod(i + 3 - n,last_row_odd + 1); end % setting subdefault rows for i = 2:n-4 for j = 4:i+2 output(i,j)=1; end end divisor = last_row_odd + 1; % setting other cols for col = (n-1):-1:4 for i = n-3:row aa = i + 4 - n; temp = ceil(aa/divisor); if temp > get_row_odd(col) temp = mod(temp, get_row_odd(col)); if temp == 0 temp = get_row_odd(col); end end output(i,col) = temp; end divisor = divisor * get_row_odd(col); end end
github
jasnap/philogenetic_trees-master
tree_type.m
.m
philogenetic_trees-master/tree_type.m
569
utf_8
a839cd73ba2c11c30f1a6c388df53de8
%---------------- tree_type-------------- % This function finds if a tree is incomplete, partial or complete % % Input: % tree - Id number of the tree % Output: % type - Type of the tree % % 0 - incomplete % 1 - partial % 2 - complete function type = tree_type(tree) num_of_zeros = sum(tree(:) == 0) - 2; last_index = size(tree); if num_of_zeros == 0 type = 2; elseif num_of_zeros == 1 if tree(last_index) == 0 type = 1; else type = 0; end else type = 0; end end
github
jasnap/philogenetic_trees-master
non_inf_sites.m
.m
philogenetic_trees-master/non_inf_sites.m
1,155
utf_8
53c5b547770e3cb7e5707f484249c2d1
%----------- non_inf_sites -------------- % This function removes all noninformative sites in a sequence % % Input: % set_of_seq - Matrix of input sequences % fact - Similarity factor % Output: % output - Matrix with all sequences where the non informative sites are removed function output = non_inf_sites(set, fact) [row, col] = size(set); for i = 1:row M(i, :) = lookup_table(set(i, :)); end [row, col] = size(M); for j = 1:col for i = 1:row score1(j) = sum(M(:, j) == 1); score2(j) = sum(M(:, j) == 2); score3(j) = sum(M(:, j) == 4); score4(j) = sum(M(:, j) == 8); end end scoring_matrix = [score1;score2;score3;score4]; % %distrubution of a number in array [srow, scol] = size(scoring_matrix); B = scoring_matrix == fact; k = 1; duplicate = 0; for i = 1:scol for j = 1:srow if(B(j, i) == 1 && duplicate ~= i) duplicate = i; flag = 1; output(:, k) = M(:, i); k = k + 1; end end end end
github
jasnap/philogenetic_trees-master
Merge.m
.m
philogenetic_trees-master/Merge.m
646
utf_8
59a96d3097ae0682946b7bb184389b34
%-------------- Merge ------------- % This function merges child nodes with parent nodes, and returns the parent % node and the calculated score % % Input: % seq1 - First child node sequence % seq2 - Second child node sequence % Output: % score - Score of the merging % out_seq - Merged parent sequence function [score, out_seq] = Merge (seq1, seq2) score = 0; for i = 1:length(seq1) if (bitand(seq1(i), seq2(i)) ~= 0) out(i) = bitand(seq1(i), seq2(i)); else out(i) = bitor(seq1(i), seq2(i)); score = score + 1; end end out_seq = out; end
github
jasnap/philogenetic_trees-master
nwk.m
.m
philogenetic_trees-master/nwk.m
1,679
utf_8
13c0c9ecbc7d66f3706e0a4234d1e365
%------------- nwk(tree)--------- % This function returns a Newick file format of the tree, and draws a % phylogenetic tree % % Input: % s_model - Tree model that had been scored % u_model - TreeID of the model that had been scored % Output: % tree_matrix - A matrix for generating phytree object % Newick file .tree which can be found in the working directory function tree_matrix = nwk(s_model, u_model, score) j = 1; flag = 1; [row, col] = size(u_model); temp_umodel = u_model; d = zeros(row, col); while(flag) for i = length(u_model):-1:1 if(d(i) == 0 && u_model(i) < 0) [ch1 ch2] = children(u_model, u_model(i)); % find its children if(ch1 > 0 && ch2 > 0) % if children are both leaves d(i) = 1; tree_matrix(j, :) = [ch1 ch2]; % put them in the matrix for phytree temp_umodel = temp_umodel(temp_umodel ~= ch1 & temp_umodel~=ch2); % delete them from the temp model %temp_umodel(i) = s_model(i); u_model(i) = s_model(i); j = j + 1; % temp_umodel now has parents as leaves % and leaves are deleted end end end if(isequal(u_model(2:end), s_model(2:end))) flag = 0; break; end end tree_matrix(end+1, :) = [s_model(2) u_model(1)]; phy_tree = phytree(tree_matrix); plot(phy_tree); title(['Phylogenetic tree using Maximum Parsimony with score ',num2str(score)]) ylabel('Evolutionary distance') %Generate Newick formated tree file %phytreewrite('newtree.tree',phy) end
github
jasnap/philogenetic_trees-master
last_tree.m
.m
philogenetic_trees-master/last_tree.m
299
utf_8
6c8e36d8808d4d242467d1df7c013aa0
%-------------- last_tree -------------- % This function calculates the last possible tree % % Input: % n - Number of sequences % Output: % tree - Last possible tree % function tree = last_tree(n) tree = [zeros(1, 2) 1]; for i = 3 : n - 1 tree(i + 1) = tree(i) + 2; end end
github
jasnap/philogenetic_trees-master
children.m
.m
philogenetic_trees-master/children.m
411
utf_8
619778fd59997345f2c3afac735fa25b
%---------------- children ---------- % Function for finding all children nodes % % Input: % model - Tree model % node - Parent node for which it's finding % Output: % child1 - First child node % child2 - Second child node function [child1, child2] = children(model,node) offset = 2*abs(node) + 1; child1 = model(offset); child2 = model(offset + 1); end
github
kranthibalusu/Crystal-plasticity--master
distSet1Set2V2.m
.m
Crystal-plasticity--master/ProfileAnalysis/distSet1Set2V2.m
1,430
utf_8
3610325aa9f2a44d13bdf7758e8b8d1c
%function to determine the index of point in set 1 %closest to every point in set 2 %also compare one other parsameter function [idSet, distSet] = distSet1Set2V2(set1,set2, set12, set22, par1by2) % set1 and set12 are expected to be of the same size, describing the same thing %par1by2 pareameter describes the relative importance of each data type %size of set1 set1S=size(set1,1); %size of set2 set2S=size(set2,1); idDiff = set1S - set2S; %idSet allocatoipn idSet = zeros(set2S,1); distSet = zeros(set2S,1); % loop through every point in set 2 to find its nearrest neightbor in Set1 for iS2=1:set2S point2 = set2(iS2,:); point22 = set22(iS2,:); minDist = 10^6; %something really large id = []; %loop through each point in set1 %not each point but similar IDs st1 = iS2 - idDiff; %min iD st2 = iS2 + idDiff; %max iD if st1<1 st1 = 1; end temp = st2; if st2 > set1S temp = set1S; end st2 =temp; for iS1 = st1:st2 point1 = set1(iS1,:); point12 = set12(iS1,:); %dist a combination of both the parameters dist = norm(point1-point2)*par1by2 + norm(point12-point22); if dist < minDist id = iS1; minDist = dist; end end idSet(iS2) = id; distSet(iS2) = minDist; end
github
kranthibalusu/Crystal-plasticity--master
distSet1Set2.m
.m
Crystal-plasticity--master/ProfileAnalysis/distSet1Set2.m
1,039
utf_8
bae3b74d4651545121c99334db5b5786
%function to determine the index of point in set 1 %closest to every point in set 2 function [idSet, distSet] = distSet1Set2(set1,set2) %size of set1 set1S=size(set1,1); %size of set2 set2S=size(set2,1); idDiff = set1S - set2S; %idSet allocatoipn idSet = zeros(set2S,1); distSet = zeros(set2S,1); % loop through every point in set 2 to find its nearrest neightbor in Set1 for iS2=1:set2S point2 = set2(iS2,:); minDist = 10^6; %something really large id = []; %loop through each point in set1 %not each point but similar IDs st1 = iS2 - idDiff; %min iD st2 = iS2 + idDiff; %max iD if st1<1 st1 = 1; end temp = st2; if st2 > set1S temp = set1S; end st2 =temp; for iS1 = st1:st2 point1 = set1(iS1,:); dist = norm(point1-point2); if dist < minDist id = iS1; minDist = dist; end end idSet(iS2) = id; distSet(iS2) = minDist; end
github
kranthibalusu/Crystal-plasticity--master
kraFilt.m
.m
Crystal-plasticity--master/ProfileAnalysis/kraFilt.m
703
utf_8
b0c4a099dbb5ca3fc36db641b4747040
% my own filter %not implemented yet %1) identify values lying outside a specif range %2) replace them by a value average of its sorrounding. function [imageFilt]=kraFilt(image,stds) % image shoudl be having only one channel %stds is the numbed of std deviations that have to be removed %from image [sizeC,sizeR]=size(image); meanData=mean(image(:)); stdDevData=std(image(:)); lowLimit= meanData - stds*stdDevData; highLimit= meanData + stds*stdDevData; for iC=1:sizeC %cycle columns for iR=1:sizeR %cycle rows if image(iC,iR)<lowLimit || image(iC,iR)<highLimit else end end end
github
kranthibalusu/Crystal-plasticity--master
IPFRDPlot.m
.m
Crystal-plasticity--master/ProfileAnalysis/IPFRDPlot.m
2,906
utf_8
db565dd2b718e1a74d63a00d92b7f6c8
% function to plot points on the IPF function [plotnameFig] = IPFRDPlot(points,idx,labels) %labels - array with labels for points noPoints=size(points,1); if ~exist('labels','var') % third parameter does not exist, so default it to something labels = [1:noPoints]'; end %% RD location determination ND=[0,0,1]; RD=[1,0,0]; RDSt=[]; NDSt=[]; for j=1:noPoints % lattice orientation ( euler angles xzx; same as in DAMASK 'math_EulerToR(Euler)' ) alpha=points(j,1); beta=points(j,2); gamma=points(j,3); Euler=[alpha,beta,gamma]*pi/180; % EulerCol=[alpha,beta,gamma]./90; C1 = cos(Euler(1)); C = cos(Euler(2)); C2 = cos(Euler(3)); S1 = sin(Euler(1)); S = sin(Euler(2)); S2 = sin(Euler(3)); % conversion matrix rotate lattice coords to global coords system math_EulerToR(1,1)=C1*C2-S1*S2*C; math_EulerToR(1,2)=-C1*S2-S1*C2*C; math_EulerToR(1,3)=S1*S; math_EulerToR(2,1)=S1*C2+C1*S2*C; math_EulerToR(2,2)=-S1*S2+C1*C2*C; math_EulerToR(2,3)=-C1*S; math_EulerToR(3,1)=S2*S; math_EulerToR(3,2)=C2*S; math_EulerToR(3,3)=C; % RD; transpose is correct, check visEuler.m RDStN=abs((math_EulerToR'*RD')'); % % RD swapping xSt=RDStN(1); ySt=RDStN(2); zSt=RDStN(3); if xSt>zSt temp=xSt; xSt=zSt; zSt=temp; end if ySt>zSt temp=ySt; ySt=zSt; zSt=temp; end if ySt>xSt temp=ySt; ySt=xSt; xSt=temp; end RDSt=[RDSt;xSt/(zSt+1),ySt/(zSt+1)]; % plotting NDStN=abs(math_EulerToR'*ND'); % ND swapping xSt=NDStN(1); ySt=NDStN(2); zSt=NDStN(3); if xSt>zSt temp=xSt; xSt=zSt; zSt=temp; end if ySt>zSt temp=ySt; ySt=zSt; zSt=temp; end if ySt>xSt temp=ySt; ySt=xSt; xSt=temp; end NDSt=[NDSt;xSt/(zSt+1),ySt/(zSt+1)]; end %% plotting outline of the IPF ND=[0,0,1]; RD=[1,0,0]; N=10; % number of divisions on each side of the traingle like shape % line 1 L1=zeros((N+1),3); L1(:,3)=1; L1(:,1)=[0:N]/N; % line 2 L2=zeros((N+1),3); L2(:,3)=1; L2(:,1)=1; L2(:,2)=[0:N]/N; % line 3 L3=zeros((N+1),3); L3(:,3)=1; L3(:,1)=[N:-1:0]/N; L3(:,2)=[N:-1:0]/N; L=[L1;L2;L3]; for i=1:(3*N+3) L(i,:)=L(i,:)/norm(L(i,:)); end % stereographic projection LSt=[L(:,1)./(L(:,3)+1),L(:,2)./(L(:,3)+1)]; %% plot outline plotnameFig=figure; hold on; plot(LSt(:,1),LSt(:,2),'LineWidth',2,'Color',[0 0 0]) xlim([-0.05 0.5]) ylim([-0.05 0.4]) title('RD'); %% plot points for Gn=1:noPoints if idx(Gn) ~= 0 txt = int2str(labels(Gn)); pCol = [1,0,0]*(1+idx(Gn))/2 + [0,0,1]*(1-idx(Gn))/2; %red for rising blue for sinking scatter(RDSt(Gn,1),RDSt(Gn,2),'MarkerFaceColor',pCol,'MarkerEdgeColor',pCol,'LineWidth',1); text(RDSt(Gn,1)+0.001,RDSt(Gn,2)+0.001,txt,'FontSize',14,'FontName','Times New Roman'); end end hold off;
github
lowrank/pat-master
lbfgsb_c.m
.m
pat-master/lbfgsc/Matlab/lbfgsb_c.m
10,263
utf_8
a96e46dd0b500bad16bc460eed316eb1
function [x,f,info] = lbfgsb_c( fcn, l, u, opts ) % x = lbfgsb( fcn, l, u ) % uses the lbfgsb v.3.0 library (fortran files must be installed; % see compile_mex.m ) which is the L-BFGS-B algorithm. % The algorithm is similar to the L-BFGS quasi-Newton algorithm, % but also handles bound constraints via an active-set type iteration. % This version is based on the modified C code L-BFGS-B-C, and so has % a slightly different calling syntax than previous versions. % % The minimization problem that it solves is: % min_x f(x) subject to l <= x <= u % % 'fcn' is a function handle that accepts an input, 'x', % and returns two outputs, 'f' (function value), and 'g' (function gradient). % % 'l' and 'u' are column-vectors of constraints. Set their values to Inf % if you want to ignore them. (You can set some values to Inf, but keep % others enforced). % % The full format of the function is: % [x,f,info] = lbfgsb( fcn, l, u, opts ) % where the output 'f' has the value of the function f at the final iterate % and 'info' is a structure with useful information % (self-explanatory, except for info.err. The first column of info.err % is the history of the function values f, and the second column % is the history of norm( gradient, Inf ). ) % % The 'opts' structure allows you to pass further options. % Possible field name values: % % opts.x0 The starting value (default: all zeros) % opts.m Number of limited-memory vectors to use in the algorithm % Try 3 <= m <= 20. (default: 5 ) % opts.factr Tolerance setting (see this source code for more info) % (default: 1e7 ). This is later multiplied by machine epsilon % opts.pgtol Another tolerance setting, relating to norm(gradient,Inf) % (default: 1e-5) % opts.maxIts How many iterations to allow (default: 100) % opts.maxTotalIts How many iterations to allow, including linesearch iterations % (default: 5000) % opts.printEvery How often to display information (default: 1) % opts.errFcn A function handle (or cell array of several function handles) % that computes whatever you want. The output will be printed % to the screen every 'printEvery' iterations. (default: [] ) % Results saved in columns 3 and higher of info.err variable % % Stephen Becker, [email protected] % Feb 14, 2012 % Updated Feb 21 2015, Stephen Becker, [email protected] narginchk(3, 4) if nargin < 4, opts = struct([]); end % Matlab doesn't let you use the .name convention with structures % if they are empty, so in that case, make the structure non-empty: if isempty(opts), opts=struct('a',1) ; end function out = setOpts( field, default, mn, mx ) if ~isfield( opts, field ) opts.(field) = default; end out = opts.(field); if nargin >= 3 && ~isempty(mn) && any(out < mn), error('Value is too small'); end if nargin >= 4 && ~isempty(mx) && any(out > mx), error('Value is too large'); end opts = rmfield( opts, field ); % so we can do a check later end % [f,g] = callF( x ); if iscell(fcn) % the user has given us separate functions to compute % f (function) and g (gradient) callF = @(x) fminunc_wrapper(x,fcn{1},fcn{2} ); else callF = fcn; end n = length(l); if length(u) ~= length(l), error('l and u must be same length'); end x0 = setOpts( 'x0', zeros(n,1) ); x = x0 + 0; % important: we want Matlab to make a copy of this. % just in case 'x' will be modified in-place % (Feb 2015 version of code, it should not be modified, % but just-in-case, may as well leave this ) if size(x0,2) ~= 1, error('x0 must be a column vector'); end if size(l,2) ~= 1, error('l must be a column vector'); end if size(u,2) ~= 1, error('u must be a column vector'); end if size(x,1) ~= n, error('x0 and l have mismatchig sizes'); end if size(u,1) ~= n, error('u and l have mismatchig sizes'); end % Number of L-BFGS memory vectors % From the fortran driver file: % "Values of m < 3 are not recommended, and % large values of m can result in excessive computing time. % The range 3 <= m <= 20 is recommended. " m = setOpts( 'm', 5, 0 ); % 'nbd' is 0 if no bounds, 1 if lower bound only, % 2 if both upper and lower bounds, and 3 if upper bound only. % This .m file assumes l=-Inf and u=+Inf imply that there are no constraints. % So, convert this to the fortran convention: nbd = isfinite(l) + isfinite(u) + 2*isinf(l).*isfinite(u); if ispc nbd = int32(nbd); else nbd = int64(nbd); end % Some scalar settings, "factr" and "pgtol" % Their descriptions, from the fortran file: % factr is a DOUBLE PRECISION variable that must be set by the user. % It is a tolerance in the termination test for the algorithm. % The iteration will stop when % % (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr*epsmch % % where epsmch is the machine precision which is automatically % generated by the code. Typical values for factr on a computer % with 15 digits of accuracy in double precision are: % factr=1.d+12 for low accuracy; % 1.d+7 for moderate accuracy; % 1.d+1 for extremely high accuracy. % The user can suppress this termination test by setting factr=0. factr = setOpts( 'factr', 1e7, 0 ); % pgtol is a double precision variable. % On entry pgtol >= 0 is specified by the user. The iteration % will stop when % % max{|proj g_i | i = 1, ..., n} <= pgtol % % where pg_i is the ith component of the projected gradient. % The user can suppress this termination test by setting pgtol=0. pgtol = setOpts( 'pgtol', 1e-5, 0 ); % may crash if < 0 % Maximum number of outer iterations maxIts = setOpts( 'maxIts', 100, 1 ); % Maximum number of total iterations % (this includes the line search steps ) maxTotalIts = setOpts( 'maxTotalIts', 5e3 ); % Print out information this often (and set to Inf to suppress) printEvery = setOpts( 'printEvery', 1 ); errFcn = setOpts( 'errFcn', [] ); iprint = setOpts('verbose',-1); % <0 for no output, 0 for some, 1 for more, 99 for more, 100 for more % I recommend you set this -1 and use the Matlab print features % (e.g., set printEvery ) fcn_wrapper(); % initialized persistent variables callF_wrapped = @(x,varargin) fcn_wrapper( callF, errFcn, maxIts, ... printEvery, x, varargin{:} ); % callF_wrapped = @(x,varargin)callF(x); % also valid, but simpler % Call the mex file [f,x,taskInteger,outer_count, k] = lbfgsb_wrapper( m, x, l, u, nbd, ... callF_wrapped, factr, pgtol, ... iprint, maxIts, maxTotalIts); info.iterations = outer_count; info.totalIterations = k; info.lbfgs_message = findTaskString( taskInteger ); errHist = fcn_wrapper(); info.err = errHist; end % end of main function function [f,g] = fcn_wrapper( callF, errFcn, maxIts, printEvery, x, varargin ) persistent k history if isempty(k), k = 1; end if nargin==0 % reset persistent variables and return information if ~isempty(history) && ~isempty(k) printFcn(k,history); f = history(1:k,:); end history = []; k = []; return; end if isempty( history ) width = 0; if iscell( errFcn ), width = length(errFcn); elseif ~isempty(errFcn), width = 1; end width = width + 2; % include fcn and norm(grad) as well history = zeros( maxIts, width ); end % Find function value and gradient: [f,g] = callF(x); if nargin > 5 outerIter = varargin{1}+1; history(outerIter,1) = f; history(outerIter,2) = norm(g,Inf); % g is not projected if isa( errFcn, 'function_handle' ) history(outerIter,3) = errFcn(x); elseif iscell( errFcn ) for j = 1:length(errFcn) history(outerIter,j+2) = errFcn{j}(x); end end if outerIter > k % Display info from *previous* input % Since this may be called several times before outerIter % is actually updated % fprintf('At iterate %5d, f(x)= %.2e, ||grad||_infty = %.2e [MATLAB]\n',... % k,history(k,1),history(k,2) ); if ~isinf(printEvery) && ~mod(k,printEvery) printFcn(k,history); end k = outerIter; end end end function printFcn(k,history) fprintf('Iter %5d, f(x) = %2e, ||grad||_infty = %.2e', ... k, history(k,1), history(k,2) ); for col = 3:size(history,2) fprintf(', %.7e', history(k,col) ); end fprintf('\n'); end function [f,g] = fminunc_wrapper(x,F,G) % [f,g] = fminunc_wrapper( x, F, G ) % for use with Matlab's "fminunc" f = F(x); if nargin > 2 && nargout > 1 g = G(x); end end function str = findTaskString( taskInteger ) % See the #define statements in lbfgsb.h switch taskInteger case 209 str = 'ERROR: N .LE. 0'; case 210 str = 'ERROR: M .LE. 0'; case 211 str = 'ERROR: FACTR .LT. 0'; case 3 str = 'ABNORMAL_TERMINATION_IN_LNSRCH.'; case 4 str = 'RESTART_FROM_LNSRCH.'; case 21 str = 'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL.'; case 22 str = 'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH.'; case 31 str = 'STOP: CPU EXCEEDING THE TIME LIMIT.'; case 32 str = 'STOP: TOTAL NO. of f AND g EVALUATIONS EXCEEDS LIM.'; case 33 str = 'STOP: THE PROJECTED GRADIENT IS SUFFICIENTLY SMALL.'; case 101 str = 'WARNING: ROUNDING ERRORS PREVENT PROGRESS'; case 102 str = 'WARNING: XTOL TEST SATISIED'; case 103 str = 'WARNING: STP = STPMAX'; case 104 str = 'WARNING: STP = STPMIN'; case 201 str = 'ERROR: STP .LT. STPMIN'; case 202 str = 'ERROR: STP .GT. STPMAX'; case 203 str = 'ERROR: INITIAL G .GE. ZERO '; case 204 str = 'ERROR: FTOL .LT. ZERO'; case 205 str = 'ERROR: GTOL .LT. ZERO'; case 206 str = 'ERROR: XTOL .LT. ZERO'; case 207 str = 'ERROR: STPMIN .LT. ZERO'; case 208 str = 'ERROR: STPMAX .LT. STPMIN'; case 212 str = 'ERROR: INVALID NBD'; case 213 str = 'ERROR: NO FEASIBLE SOLUTION'; otherwise str = 'UNRECOGNIZED EXIT FLAG'; end end
github
EvanMu96/nnPiCar-master
controlPad.m
.m
nnPiCar-master/server/controlPad.m
5,614
utf_8
adadd6fc95f8d65c0c6dce342d9b689c
function varargout = controlPad(varargin) % CONTROLPAD MATLAB code for controlPad.fig % CONTROLPAD, by itself, creates a new CONTROLPAD or raises the existing % singleton*. % % H = CONTROLPAD returns the handle to a new CONTROLPAD or the handle to % the existing singleton*. % % CONTROLPAD('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in CONTROLPAD.M with the given input arguments. % % CONTROLPAD('Property','Value',...) creates a new CONTROLPAD or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before controlPad_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to controlPad_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help controlPad % Last Modified by GUIDE v2.5 27-Sep-2017 13:26:40 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @controlPad_OpeningFcn, ... 'gui_OutputFcn', @controlPad_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before controlPad is made visible. function controlPad_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 controlPad (see VARARGIN) % Choose default command line output for controlPad handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes controlPad wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = controlPad_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global currentType;global curl; currentType = 'forward';cmd(currentType,curl);pause(0.2);cmd('stop',curl); % --- Executes on button press in pushbutton2. function pushbutton2_Callback(~, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global currentType;global curl; currentType = 'turnleft';cmd(currentType, curl);pause(0.2);cmd('stop',curl); % --- Executes on button press in pushbutton3. function pushbutton3_Callback(hObject, eventdata, handles) % hObject handle to pushbutton3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global currentType;global curl; currentType = 'backward';cmd(currentType, curl);pause(0.2);cmd('stop',curl); % --- Executes on button press in pushbutton4. function pushbutton4_Callback(hObject, eventdata, handles) % hObject handle to pushbutton4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global currentType;global curl; currentType = 'turnright';cmd(currentType, curl);pause(0.2);cmd('stop',curl); % --- Executes on button press in togglebutton1. function togglebutton1_Callback(hObject, eventdata, handles) % hObject handle to togglebutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of togglebutton1 global startFlag; button_state = get(hObject,'Value'); if button_state == get(hObject,'Max') startFlag = ~startFlag; elseif button_state == get(hObject,'Min') startFlag = ~startFlag; end % --- Executes on button press in pushbutton5. function pushbutton5_Callback(hObject, eventdata, handles) % hObject handle to pushbutton5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global quitLoop; quitLoop = true; % --- Executes on button press in pushbutton6. function pushbutton6_Callback(hObject, eventdata, handles) % hObject handle to pushbutton6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global currentType; currentType = 'stop';
github
mszinte/pRF_gazeMod_testCode-master
kde2d.m
.m
pRF_gazeMod_testCode-master/stats/kde2d.m
7,506
utf_8
129d5d2a0461b7ae38b706c421cbb8a3
function [bandwidth,density,X,Y]=kde2d(data,MIN_XY,MAX_XY,n) % fast and accurate state-of-the-art % bivariate kernel density estimator % with diagonal bandwidth matrix. % The kernel is assumed to be Gaussian. % The two bandwidth parameters are % chosen optimally without ever % using/assuming a parametric model for the data or any "rules of thumb". % Unlike many other procedures, this one % is immune to accuracy failures in the estimation of % multimodal densities with widely separated modes (see examples). % INPUTS: data - an N by 2 array with continuous data % n - size of the n by n grid over which the density is computed % n has to be a power of 2, otherwise n=2^ceil(log2(n)); % the default value is 2^8; % MIN_XY,MAX_XY- limits of the bounding box over which the density is computed; % the format is: % MIN_XY=[lower_Xlim,lower_Ylim] % MAX_XY=[upper_Xlim,upper_Ylim]. % The dafault limits are computed as: % MAX=max(data,[],1); MIN=min(data,[],1); Range=MAX-MIN; % MAX_XY=MAX+Range/4; MIN_XY=MIN-Range/4; % OUTPUT: bandwidth - a row vector with the two optimal % bandwidths for a bivaroate Gaussian kernel; % the format is: % bandwidth=[bandwidth_X, bandwidth_Y]; % density - an n by n matrix containing the density values over the n by n grid; % density is not computed unless the function is asked for such an output; % X,Y - the meshgrid over which the variable "density" has been computed; % the intended usage is as follows: % surf(X,Y,density) % Example (simple Gaussian mixture) % clear all % % generate a Gaussian mixture with distant modes % data=[randn(500,2); % randn(500,1)+3.5, randn(500,1);]; % % call the routine % [bandwidth,density,X,Y]=kde2d(data); % % plot the data and the density estimate % contour3(X,Y,density,50), hold on % plot(data(:,1),data(:,2),'r.','MarkerSize',5) % % Example (Gaussian mixture with distant modes): % % clear all % % generate a Gaussian mixture with distant modes % data=[randn(100,1), randn(100,1)/4; % randn(100,1)+18, randn(100,1); % randn(100,1)+15, randn(100,1)/2-18;]; % % call the routine % [bandwidth,density,X,Y]=kde2d(data); % % plot the data and the density estimate % surf(X,Y,density,'LineStyle','none'), view([0,60]) % colormap hot, hold on, alpha(.8) % set(gca, 'color', 'blue'); % plot(data(:,1),data(:,2),'w.','MarkerSize',5) % % Example (Sinusoidal density): % % clear all % X=rand(1000,1); Y=sin(X*10*pi)+randn(size(X))/3; data=[X,Y]; % % apply routine % [bandwidth,density,X,Y]=kde2d(data); % % plot the data and the density estimate % surf(X,Y,density,'LineStyle','none'), view([0,70]) % colormap hot, hold on, alpha(.8) % set(gca, 'color', 'blue'); % plot(data(:,1),data(:,2),'w.','MarkerSize',5) % % Notes: If you have a more accurate density estimator % (as measured by which routine attains the smallest % L_2 distance between the estimate and the true density) or you have % problems running this code, please email me at [email protected] % Reference: Z. I. Botev, J. F. Grotowski and D. P. Kroese % "KERNEL DENSITY ESTIMATION VIA DIFFUSION" ,Submitted to the % Annals of Statistics, 2009 global N A2 I if nargin<4 n=2^8; end n=2^ceil(log2(n)); % round up n to the next power of 2; N=size(data,1); if nargin<3 MAX=max(data,[],1); MIN=min(data,[],1); Range=MAX-MIN; MAX_XY=MAX+Range/4; MIN_XY=MIN-Range/4; end scaling=MAX_XY-MIN_XY; if N<=size(data,2) error('data has to be an N by 2 array where each row represents a two dimensional observation') end transformed_data=(data-repmat(MIN_XY,N,1))./repmat(scaling,N,1); %bin the data uniformly using regular grid; initial_data=ndhist(transformed_data,n); % discrete cosine transform of initial data a= dct2d(initial_data); % now compute the optimal bandwidth^2 I=(0:n-1).^2; A2=a.^2; t_star=fzero( @(t)(t-evolve(t)),[0,0.1]); p_02=func([0,2],t_star);p_20=func([2,0],t_star); p_11=func([1,1],t_star); t_y=(p_02^(3/4)/(4*pi*N*p_20^(3/4)*(p_11+sqrt(p_20*p_02))))^(1/3); t_x=(p_20^(3/4)/(4*pi*N*p_02^(3/4)*(p_11+sqrt(p_20*p_02))))^(1/3); % smooth the discrete cosine transform of initial data using t_star a_t=exp(-(0:n-1)'.^2*pi^2*t_x/2)*exp(-(0:n-1).^2*pi^2*t_y/2).*a; % now apply the inverse discrete cosine transform if nargout>1 density=idct2d(a_t)*(numel(a_t)/prod(scaling)); [X,Y]=meshgrid(MIN_XY(1):scaling(1)/(n-1):MAX_XY(1),MIN_XY(2):scaling(2)/(n-1):MAX_XY(2)); end bandwidth=sqrt([t_x,t_y]).*scaling; end %####################################### function [out,time]=evolve(t) global N Sum_func = func([0,2],t) + func([2,0],t) + 2*func([1,1],t); time=(2*pi*N*Sum_func)^(-1/3); out=(t-time)/time; end %####################################### function out=func(s,t) global N if sum(s)<=4 Sum_func=func([s(1)+1,s(2)],t)+func([s(1),s(2)+1],t); const=(1+1/2^(sum(s)+1))/3; time=(-2*const*K(s(1))*K(s(2))/N/Sum_func)^(1/(2+sum(s))); out=psi(s,time); else out=psi(s,t); end end %####################################### function out=psi(s,Time) global I A2 % s is a vector w=exp(-I*pi^2*Time).*[1,.5*ones(1,length(I)-1)]; wx=w.*(I.^s(1)); wy=w.*(I.^s(2)); out=(-1)^sum(s)*(wy*A2*wx')*pi^(2*sum(s)); end %####################################### function out=K(s) out=(-1)^s*prod((1:2:2*s-1))/sqrt(2*pi); end %####################################### function data=dct2d(data) % computes the 2 dimensional discrete cosine transform of data % data is an nd cube [nrows,ncols]= size(data); if nrows~=ncols error('data is not a square array!') end % Compute weights to multiply DFT coefficients w = [1;2*(exp(-i*(1:nrows-1)*pi/(2*nrows))).']; weight=w(:,ones(1,ncols)); data=dct1d(dct1d(data)')'; function transform1d=dct1d(x) % Re-order the elements of the columns of x x = [ x(1:2:end,:); x(end:-2:2,:) ]; % Multiply FFT by weights: transform1d = real(weight.* fft(x)); end end %####################################### function data = idct2d(data) % computes the 2 dimensional inverse discrete cosine transform [nrows,ncols]=size(data); % Compute wieghts w = exp(i*(0:nrows-1)*pi/(2*nrows)).'; weights=w(:,ones(1,ncols)); data=idct1d(idct1d(data)'); function out=idct1d(x) y = real(ifft(weights.*x)); out = zeros(nrows,ncols); out(1:2:nrows,:) = y(1:nrows/2,:); out(2:2:nrows,:) = y(nrows:-1:nrows/2+1,:); end end %####################################### function binned_data=ndhist(data,M) % this function computes the histogram % of an n-dimensional data set; % 'data' is nrows by n columns % M is the number of bins used in each dimension % so that 'binned_data' is a hypercube with % size length equal to M; [nrows,ncols]=size(data); bins=zeros(nrows,ncols); for i=1:ncols [dum,bins(:,i)] = histc(data(:,i),[0:1/M:1],1); bins(:,i) = min(bins(:,i),M); end % Combine the vectors of 1D bin counts into a grid of nD bin % counts. binned_data = accumarray(bins(all(bins>0,2),:),1/nrows,M(ones(1,ncols))); end
github
adeelz92/Machine-Learning-Coursera-master
submit.m
.m
Machine-Learning-Coursera-master/machine-learning-ex2/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