www.gusucode.com > mbcdata 工具箱 matlab 源码程序 > mbcdata/@cgoppoint/ImportFile.m

    function [op,err, sheetname] = ImportFile(op_in,pname,fname,arg4,varargin)
% p = ImportFile(cgoppoint)
%    create a new operating point set from a file, chosen from uigetfile.
%    Filetypes supported: .xls, .xlsx, .txt, .csv, .mat
%    File should contain a block of data, with or without headings.
%    .xls, .xlsx: A dialog is displayed if there is more than one worksheet
%    .mat: file should contain a single cgoppoint object.
%
% p = ImportFile(cgoppoint,pname,fname)
%    create a new operating point set from the named file.
%
% p = ImportFile(cgoppoint,pname,fname,sheetname)
%    create a new operating point set from a named sheet in an excel spreadsheet.
%
% p = ImportFile(p,...)
%    fill the existing operating point set from the file.
%    If column headings are present in the file, these will be matched with
%      the dataset.  If no headings are present, the number of columns must
%      match the number of: inputs; inputs and outputs; or all factors.
%
% p = ImportFile(p,{factornames})
% p = ImportFile(p,{factornames},pname,fname)
% p = ImportFile(p,{factornames},pname,fname,sheetname)
%    Fill the named factors in order from the file. Column headings are ignored.
%
% pname = 'clipboard' imports from clipboard. Other settings are as above.
%
% [p,err] = ImportFile(...) returns any error messages and does not display them.

%  Copyright 2000-2014 The MathWorks, Inc. and Ford Global Technologies, Inc.

op = op_in;
sheetname = [];


if nargin>1
elseif nargin<3
    [fname,pname] = uigetfile('*.txt;*.xls,*.xlsx;*.csv;*.mat' , 'Select Data File', ...
        mbcGetPath('cage', 'Data'));
    if isnumeric(fname) || isnumeric(pname) || isempty(strfind(fname,'.'))
        err = '';
        return;
    end
end
switch pname 
    case {'clipboard','mbcmodel','workspace'}
        extension = pname;
    otherwise
        [~, ~, extension] = fileparts( fname );
end
try
    %Must have different load types for different file extensions.
    switch extension
        case 'mbcmodel'
            pData = xregpointer;
            if nargin>=4
                pData = arg4;
            end
            [num,heads,err] = i_read_mbcmodel(fname,pData);
        case 'workspace'
            if nargin>=4
                ss= arg4;
            else
                ss=sweepset;
            end
            [num,heads,err] = iReadWorkspace(ss);

        case 'clipboard'
            [num,heads,~,err] = cg_read_txt( op_in, 'clipboard', [] );
        case {'.xls','.xlsx'}
            if nargin>=4
                sheetname = arg4;
            end
            [num,heads,~,err,sheetname] = cg_read_excel( op_in, ...
                pname, fname, sheetname );
        case '.txt'
            [num,heads,~,err] = cg_read_txt( op_in, pname, fname );
        case '.csv'
            [num,heads,~,err] = cg_read_txt(op_in, pname, fname, ',');
        case '.mat'
            [num,heads,~,err] = cg_read_mat(op_in, pname, fname);
        otherwise
            err = sprintf( 'File type %s not supported.', extension );
    end
catch ME
     err = sprintf( 'File: %s does not seem to be of the correct format.\n%s', ...
         fname, ME.message);
end

% final check, make sure we have some heads
if isempty( err ) && isempty( heads )
    err = 'Dataset has no factors.';
end

% if we have err defined we'll bail now.
if ~isempty( err )
    if nargout<2
        error('mbc:cgoppoint:InvalidData', err);
    else
        return;
    end
end

% we must have successfully loaded stuff in
if ~isempty(op_in)
    % if the input datset isn't empty we should fill this one
    [op, err] = fill_existing( op_in, num, heads );
else
    % otherwise create a new dataset
    [op, err] = create_new( num, heads );
end

%------------------------------------------------------------------
function [op, err] = create_new( num, heads )
%------------------------------------------------------------------
% we create a new dataset
nHeads = length(heads);
newname = cell(1, nHeads);
err = '';
for i = 1:length(heads)
    if ~ischar(heads{i})
        heads{i} = 'Var';
    elseif length(heads{i})>1
        if heads{i}(1) == '('
            heads{i} = heads{i}(2:end);
        end
        if heads{i}(end) == ')'
            heads{i} = heads{i}(1:end-1);
        end
    end
    newname{i} = uniquename(newname,heads{i});
end
op = cgoppoint(newname,num,'grid_flag',7,...
    'factor_type','output', 'constant',0);


%------------------------------------------------------------------
function [op,err] = fill_existing(op,num,heads)
%------------------------------------------------------------------
err = '';

% Remove trailing blanks from the column headers
for j = 1:length(heads)
    heads{j} = strtrim(heads{j});
end
factors = get(op,'factors');
factor_type = get(op,'factor_type');
ptrlist = get(op,'ptrlist');
if ~all(isnull(ptrlist))
    % Need to look in alias list
    IsVar = find(~isnull(ptrlist));
    IsVar = IsVar(parrayeval(ptrlist(IsVar),@isinport,{},@false));
    AliasList = pveceval(ptrlist(IsVar),@getaliaslist);
    if all( cellfun('isempty',AliasList ) )
        AliasList = [];
    end
else
    IsVar = [];
    AliasList = [];
end
orig_names = get(op,'orig_name');
op_col = zeros(1,length(factors));

if ~isempty(heads) && ...
        ~(~isempty(heads) && iscell(heads) && strcmp(heads{1},'Var1')) 
    % File contains headings
    for i = 1:length(heads)
        f = find(strcmp(heads{i},factors));
        if length(f)==1
            op_col(f) = i;
        else
            f = find(strcmp(heads{i},orig_names));
            if length(f)==1
                op_col(f) = i;
            else
                f = iFindAlias(heads{i},AliasList);
                if f
                    op_col(IsVar(f)) = i;
                end
            end
        end
    end
    if ~any(op_col)
        err = sprintf('%s, ', heads{:});
        err = {'No matching factors found in file.', ...
            ['File contains headings: ' err(1:end-2) '.']};
    end

else    %no headings - fill in order
    in_i = find(factor_type==1);
    ass_i = find(~get(op,'assign_lock'));
    if size(num,2)==length(ass_i)   %fill factors which are free to be assigned
        % (may be created from file in the first place)
        op_col(ass_i) = 1:length(ass_i);
    elseif size(num,2)==length(in_i)
        op_col(in_i) = 1:length(in_i);  %fill inputs
    else
        err = ['Number of columns in data file must be equal to either the number of columns originally ', ...
            'imported or the number of inputs in the data set'];
    end
end

if isempty(err)
    f = find(op_col);
    assdataind = [];
    if size(op.data, 1) == size(num, 1)
        % Overwrite the data where specified, but keep any other existing
        % data
        data = op.data;
    else
        % Mark any other unassigned data for deletion
        assdataind = find(get(op, 'grid_flag') == 7 & ~isvalid(op.ptrlist));
        assdataind = setdiff(assdataind, f);
        % Any factors not specified by the input data are set to constant
        con = get(op,'constant');
        if length(con)~=length(factors)
            con = zeros(1,length(factors));
        end
        data = repmat(con,size(num,1),1);
    end
    data(:,f) = num(:,op_col(f));
    op.data = data;
    op = set(op,f,'grid_flag',7); %filled from file
    op = set(op, f,'created_flag', 0); %Signify imported data
    gf = get(op, 'grid_flag');
    indsnot = find(gf == 1);
    op = set(op, indsnot, 'grid_flag', 0);
    op = SetRange(op);
    op = SetTolerance(op);
    % Ensure that imported data has the orig_name field filled in
    % This is needed if the user wants to unassign and keep the data
    % in the data set for future use
    allimportednames = op.orig_name;
    emptyinds = find(cellfun('isempty', allimportednames));
    for z = 1:length(emptyinds)
        allimportednames{emptyinds(z)} = '';
    end
    for i = 1:length(f)
        if isempty(op.orig_name{f(i)})
            basename = ['Imported', factors{f(i)}];
            testname = basename;
            count = 0;
            while any(  strcmp( testname,allimportednames ) )
                count = count + 1;
                testname = [basename, num2str(count)];
            end
            op.orig_name{f(i)} = testname;
        end
    end
    % Delete any unassigned data that is no longer needed
    if ~isempty(assdataind)
        op = removefactor(op,assdataind, 'hold');
    end
end
%------------------------
function name = uniquename(l,name)
%------------------------

for i=1:length(l)
    currentName=l{i};
    if strcmp(name,currentName)
        for j = 0:length(name)-1
            if isempty(str2double((name(end-j))))
                break;
            end
        end
        if j == 0
            num = 1;
        else
            num = str2double(name(end-j+1:end)) + 1;
        end
        name = [name(1:end-j) num2str(num)];
    end
end



function [num,heads,err] = i_read_mbcmodel(name,pData)

pMBCModel = get(MBrowser,'RootNode');
pModelData = pMBCModel.dataptrs;
if isnull(pData)
    % find data from name
    Selected = strcmp(name,pveceval(pModelData,@(d) get(d,'Label')));
else
    Selected = ismember(pModelData,pData);
end

err = '';

if sum(Selected)==1
    % get data from sweepset
    S = sweepset(pModelData(Selected).info);
    num = double(S);
    heads = get(S,'Name');
else
    num = [];
    heads={};
    err = 'Data not found in MBC Model Browser';
end

function [num,heads,err] = iReadWorkspace(ss)
num = double(ss);
heads = get(ss,'Name');
err = {};
function index = iFindAlias(head,AliasList)

index = 0;
for i=1:length(AliasList)
    if ~isempty(AliasList{i}) && ismember(head,AliasList{i})
        index = i;
        break;
    end
end