Code covered by the BSD License  

Highlights from
Desenvolvimento de Aplicacoes com MATLAB

image thumbnail

Desenvolvimento de Aplicacoes com MATLAB

by

 

Slides and demo files from the webinar "Desenvolvimento de Aplicacoes com MATLAB"

optimtowers_www(towers, side, seed, height, width)
function outputBytes = optimtowers_www(towers, side, seed, height, width)
    % Copyright 2006 The MathWorks, Inc.

    % Initial Parameters
    param.towers = towers;%15;
    param.side   = side;%10;
    param.seed   = seed;%5;

    % Generate Figure
    figH = figure(...
      'name'                            , 'Phone Tower Location', ...
      'visible'                         , 'off');

    axH = axes();

    stopOptim  = false;
    pauseOptim = false;

    % Initialize
    [R, xL, xU, yL, yU, lb, ub, x0] = celltowersetup(param);
    myplotcircles(x0, 0, '', R, xL, xU, yL, yU);

    options = optimset;
    options = optimset(options, 'Display'   , 'none');
    options = optimset(options, 'TolFun'    , 0.0001);
    options = optimset(options, 'OutputFcn' , {@(x,itervals,flag) myplotcircles(x,itervals,flag,R,xL,xU,yL,yU), @myOutputFcn});
    options = optimset(options, 'LargeScale', 'on');
    options = optimset(options,'Algorithm' ,'active-set');
    %options = optimset(options, 'LargeScale', 'off');
    [x,fval,exitflag,output] = fmincon(@circlesIntersect, x0, [], [], [], [], lb, ub, [], options);

    set(figH,'Position',[0,200,width,height]);        

    %outputBytes = figToImStream('figHandle', figH, 'outputType', 'uint8');
    %outputBytes = webfigure(figH);
    %outputBytes = convertFigure(figH);
    set(figH,'Color','w');
    outputBytes = webfigure(figH);
    close(figH);

    %plotOptimSummary(output,R,xL,xU,yL,yU);

    %-------------------------------------------------
    % OUTPUT FUNCTION (plot cell phone locations)
    %-------------------------------------------------
    function stop = myplotcircles(x,itervals,flag,R,xL,xU,yL,yU)
        
        if ~ishandle(figH)
          stop = true;
          return;
        end

        pts = reshape(x, 2, length(x)/2);
        X = pts(1, :);
        Y = pts(2, :);
        N = length(R);

        if isnumeric(itervals)
          iter = itervals;
        else
          iter = itervals.iteration;
        end

        switch flag
          case {'iter', ''}
            t = 0:.1:2*pi+0.1;

            set(0   , 'currentfigure', figH);
            set(figH, 'currentaxes'  , axH);
            cla;
            for i = 1:N
                fill(R(i)*cos(t) + X(i), R(i)*sin(t) + Y(i), [0.3 0.3 1]);
                alpha(0.5);
%              plot(R(i)*cos(t) + X(i), R(i)*sin(t) + Y(i),'linewidth',2);
              text(X(i), Y(i), num2str(i), 'horizontalalignment', 'center');
              hold on
            end

            plot([xL;xU;xU;xL;xL], [yL;yL;yU;yU;yL],'r--','linewidth',1);
%            alpha(0.5);
            axis([xL-1, xU+1, yL-1, yU+1]);
            axis square;

            %title(sprintf('Iteration: %d', iter));
            %pause(.05);

            while true
              if ~pauseOptim  || ~ishandle(figH)
                break;
              end
              %pause(.1);
            end

        end

        stop = stopOptim;
    end

    %-------------------------------------------------
    
    %-------------------------------------------------
    function  [R,xL,xU,yL,yU,lb,ub,x0] = celltowersetup(param)
        % CELLTOWERSETUP creates a randomly generated celltower problem.
        % param.towers
        % param.side
        % param.seed

        % Copyright 2003 The MathWorks, Inc.

        low = 0;
        rand('seed', param.seed);
        R = rand(param.towers, 1)+1; % allocate array

        % Generate bound constraints
        xL = low; xU = param.side;
        yL = low; yU = param.side;
        % 2*N variables in the order [x1,y1,x2,y2...,xn,yn]'
        lb = zeros(2*param.towers,1);
        ub = lb;
        lb(1:2:2*param.towers) = xL + R;
        lb(2:2:2*param.towers) = yL + R;
        ub(1:2:2*param.towers) = xU - R;
        ub(2:2:2*param.towers) = yU - R;

        % Random start point
        x0 = param.side * rand(2*param.towers,1);
    end
%-------------------------------------------------

%-------------------------------------------------
% OBJECTIVE FUNCTION
%-------------------------------------------------
    function f = circlesIntersect(x)
        % CIRCLESINTERSECT Objective function for celltower problem.

        % Copyright 2003 The MathWorks, Inc.

        pts = reshape(x, 2, length(x)/2);
        N   = length(R);
        f   = 0;
        % Two circles can intersect in 0,1, 2, or all points.
        % If they intersect in 0 points, then no area to add since disjoint.
        % If they intersect in 1 point, then either have no common area
        %       of intersection (almost disjoint), or one is inside the other and barely touching.
        %       In the second case, area of intersection is the smaller circle.
        % If they intersect in 2 points, then usual case of overlapping, call
        %       circleIntersectArea to compute.
        % They can be the same circle and so intersect at all points, they can have
        % the same center but different radii (so compute diff), or they can have
        % different centers and radii but one is completely inside the other (so
        % compute diff).

        for ii = 1:N-1
          for jj = ii+1:N

            [p,q,areatotal] = areaIntersect(pts(:,ii),R(ii),pts(:,jj),R(jj));
            if isequal(pts(:,ii), pts(:,jj))
              % Circles have the same center: give a higher penalty
              f = f + areatotal + 1/(1e-8);
            else % different centers
              f = f + areatotal + 1/40 * 1/((norm(pts(:,ii)-pts(:,jj)))^2);
            end
          end
        end


        %-------------------------------
        function [p,q,areatotal,numberOfPoints] = areaIntersect(C1,r1,C2,r2)
            % Circle centers C1 and C2 with radius r1 and r2.

            % Compute x and y
            % Solve in easy coordinates
            a = norm(C1 - C2);
            % Check for divide by zero
            if isequal(a, 0)
                % Circles have same center. Return the area of the smaller circle.
                p = [NaN; NaN]; q = [NaN; NaN]; numberOfPoints = Inf;
                areatotal = pi * min(r1, r2)^2;
                return
            end
            x = 0.5*(a + (r1^2 - r2^2)/a);
            if r1^2 < x^2 % Check for sqrt of negative
                p = [NaN; NaN]; q = [NaN; NaN];
                if r1 + r2 < a
                    areatotal = 0; numberOfPoints = 0;
                else % One circle is inside the other
                    areatotal = pi*min(r1,r2)^2;
                    numberOfPoints = Inf;
                end
                return
            end
            y = sqrt(r1^2 - x^2);
            
            % Original coordinates basis
            i = (C2-C1)/norm(C2-C1);
            j = null(i');
            
            % Intersection points in original coordinates
            p = C1 + i*x + j*y ;
            q = C1 + i*x - j*y;
            
            % Compute the angle theta between radius and x-axis
            % in the easy coordinates
            theta1 =  atan2(y,x);
            theta2 =  atan2(y,a-x);
            
            % Obtain A1 with x, y, r1
            area1 = theta1*r1^2 - x*y;
            % Obtain A2 with a-x, y, r2
            area2 = theta2*r2^2 - (a-x)*y;
            
            areatotal = area1 + area2;
            
            if isequal(p,q)
                numberOfPoints = 1;
            else
                numberOfPoints = 2;
            end
            
        end
    end
    %-------------------------------------------------

    function buffImage = convertFigure(hFig)
        ppm = get(hFig,'PaperPositionMode');
        set(hFig,'PaperPositionMode','auto');

        %Get the MATLAB pixel representation of the figure
        pixels = hardcopy(hFig, '-dOpenGL', '-r0');

        %Geck 450731 returning the incorrect size image. 
        % restore old value
        set(hFig,'PaperPositionMode',ppm);

        %Required java classes to convert image.
        import java.awt.image.BufferedImage;
        import java.awt.image.DataBufferInt;
        import java.awt.image.DataBuffer;
        import java.awt.image.ComponentSampleModel;
        import java.awt.image.Raster;
        import java.io.ByteArrayOutputStream;
        import javax.imageio.ImageIO;

        %This creates a model that depicts how
        %  our pixel information is stored
        [rows,cols,planes] = size(pixels);
        dataBuffer = DataBufferInt(pixels(:), rows*cols*planes);
        sampleModel = ComponentSampleModel( DataBuffer.TYPE_INT, ...
                                            cols, ...
                                            rows, ...
                                            rows, ...
                                            1,...
                                            [0,rows*cols,2*rows*cols]);

        %We then use a Raster to map the array data into 
        %  a java raster using the infromation in the model
        raster = Raster.createRaster(sampleModel,dataBuffer,[]);

        %Create a buffered image that is the size of our image
        buffImage = BufferedImage(cols,rows,BufferedImage.TYPE_INT_RGB);
        %Fill it with the data from the raster
        buffImage.setData(raster);

    end
    
    function stop = myOutputFcn(varargin)
        % Copyright 2006 The MathWorks, Inc.
        if nargin == 0
          % return function handle to be used as an output function
          stop = @(x, optimValues, state) myOutputFcn(x, optimValues, state);
        else
          % stores the intermediate optimization results
          stop = false;
          storeResultsFcn(varargin{:});
        end
    end

    %--------------------------------------------------------------------------
    function storeResultsFcn(x, optimValues, state)
        % Stores intermediate optimization results
        % Use this as a custom output function
        switch state
          case 'init'
            setappdata(0, 'optim_xSaved', []);

          case 'iter'
            setappdata(0, 'optim_xSaved', [getappdata(0, 'optim_xSaved'), x]);

        end
    end

end

Contact us