exponenta event banner

setMetricIDs

Класс: slmetric.dashboard.CustomWidget
Пакет: slmetric.dashboard

Установка идентификатора метрики для пользовательского графического элемента «Панель мониторинга метрик»

Описание

setMetricIDs(CustomWidget, metricID) присваивает метрический идентификатор slmetric.dashboard.CustomWidget объект.

Входные аргументы

развернуть все

slmetric.dashboard.CustomWidget для которого требуется назначить метрический идентификатор. slmetric.dashboard.CustomWidget объект является средством визуализации метрических данных для идентификатора метрики.

Типы данных: char

Метрический идентификатор, связанный с slmetric.dashboard.CustomWidget объект.

Примеры

развернуть все

Создайте пользовательскую метрику, которая будет подсчитывать невиртуальные блоки. Укажите виджет для отображения этой метрики на панели мониторинга метрик. Добавьте его в группу размеров.

Создайте пользовательский метрический класс.

className = 'nonvirtualblockcount';
slmetric.metric.createNewMetricClass(className);

Создайте метрику количества невоиртуальных блоков, добавив этот код в nonvirtualblockcount.m файл.

classdef nonvirtualblockcount < slmetric.metric.Metric
    %nonvirtualblockcount calculates number of nonvirtual blocks per level.
    % BusCreator, BusSelector and BusAssign are treated as nonvirtual.
    properties
        VirtualBlockTypes = {'Demux','From','Goto','Ground', ...
            'GotoTagVisiblity','Mux','SignalSpecification', ...
            'Terminator','Inport'};
    end
    
    methods
    function this = nonvirtualblockcount()
        this.ID = 'nonvirtualblockcount';
        this.Name = 'Nonvirtual Block Count';
        this.Version = 1;
        this.CompileContext = 'None';
        this.Description = 'Algorithm that counts nonvirtual blocks per level.';
        this.AggregatedValueName = 'Nonvirtual Blocks (incl. Descendants)'
        this.ValueName = 'Nonvirtual Blocks'
        this.ComponentScope = [Advisor.component.Types.Model, ...
            Advisor.component.Types.SubSystem];
        this.AggregationMode = slmetric.AggregationMode.Sum;
        this.ResultChecksumCoverage = true;
        this.SupportsResultDetails = true;
            
    end

    function res = algorithm(this, component)
        % create a result object for this component
        res = slmetric.metric.Result();	

        % set the component and metric ID
        res.ComponentID = component.ID;
        res.MetricID = this.ID;
        
        % Practice
        D1=slmetric.metric.ResultDetail('identifier 1','Name 1');
        D1.Value=0;
        D1.setGroup('Group1','Group1Name');
        D2=slmetric.metric.ResultDetail('identifier 2','Name 2');
        D2.Value=1;
        D2.setGroup('Group1','Group1Name');
        
        

        % use find_system to get all blocks inside this component
        blocks = find_system(getPath(component), ...
            'SearchDepth', 1, ...
            'Type', 'Block');

        isNonVirtual = true(size(blocks));

        for n=1:length(blocks)
            blockType = get_param(blocks{n}, 'BlockType');

            if any(strcmp(this.VirtualBlockTypes, blockType))
                isNonVirtual(n) = false;
            else
                switch blockType
                    case 'SubSystem'
                        % Virtual unless the block is conditionally executed
                        % or the Treat as atomic unit check box is selected.
                        if strcmp(get_param(blocks{n}, 'IsSubSystemVirtual'), ...
                                'on')
                            isNonVirtual(n) = false;
                        end
                    case 'Outport'
                        % Outport: Virtual when the block resides within
                        % SubSystem block (conditional or not), and 
                        % does not reside in the root (top-level) Simulink window.
                        if component.Type ~= Advisor.component.Types.Model
                            isNonVirtual(n) = false;
                        end
                    case 'Selector'
                        % Virtual only when Number of input dimensions 
                        % specifies 1 and Index Option specifies Select 
                        % all, Index vector (dialog), or Starting index (dialog).
                        nod = get_param(blocks{n}, 'NumberOfDimensions');
                        ios = get_param(blocks{n}, 'IndexOptionArray');

                        ios_settings = {'Assign all', 'Index vector (dialog)', ...
                            'Starting index (dialog)'};

                        if nod == 1 && any(strcmp(ios_settings, ios))
                            isNonVirtual(n) = false;
                        end
                    case 'Trigger'
                        % Virtual when the output port is not present.
                        if strcmp(get_param(blocks{n}, 'ShowOutputPort'), 'off')
                            isNonVirtual(n) = false;
                        end
                    case 'Enable'
                        % Virtual unless connected directly to an Outport block.
                        isNonVirtual(n) = false;

                        if strcmp(get_param(blocks{n}, 'ShowOutputPort'), 'on')
                            pc = get_param(blocks{n}, 'PortConnectivity');

                            if ~isempty(pc.DstBlock) && ...
                                    strcmp(get_param(pc.DstBlock, 'BlockType'), ...
                                    'Outport')
                                isNonVirtual(n) = true;
                            end
                        end
                end
            end
        end

        blocks = blocks(isNonVirtual);

        res.Value = length(blocks);
    end
    end
end

Зарегистрируйте новую метрику в репозитории метрик.

[id_metric,err_msg] = slmetric.metric.registerMetric(className);

Для начала откройте конфигурацию по умолчанию для макета панели мониторинга метрик.

conf = slmetric.dashboard.Configuration.open();

Получить slmetric.dashboard.Layout объект из slmetric.dashboard.Configuration объект.

layout = getDashboardLayout(conf);

Получение объектов виджета, находящихся в объекте компоновки.

layoutWidget=getWidgets(layout);

Удалите виджет, представляющий метрику количества блоков Simulink.

sizeGroup = layoutWidget(2); 
sizeGroupWidgets = sizeGroup.getWidgets(); 
sizeGroup.removeWidget(sizeGroupWidgets(1));

Добавьте виджет, отображающий метрику количества невоиртуальных блоков. Для пользовательских виджетов типом визуализации по умолчанию является одно значение. Если требуется использовать другой метод визуализации, укажите другое значение для VisualizationType собственность.

newWidget = sizeGroup.addWidget('Custom', 1);
newWidget.Title=('Nonvirtual Block Count'); 
newWidget.setMetricIDs('nonvirtualblockcount');
newWidget.setWidths(slmetric.dashboard.Width.Medium);
newWidget.setHeight(70);

Укажите, существуют ли линии, отделяющие пользовательский виджет от других виджетов в группе. Эти команды указывают на наличие линии справа от графического элемента.

s.top = false;
s.bottom = false;
s.left= false;
s.right= true;
newWidget.setSeparators([s, s, s, s]);

Сохраните объект конфигурации. Эта команда сериализует информацию API в XML-файл.

save(conf,'Filename','DashboardConfig.xml');

Установите активную конфигурацию.

slmetric.dashboard.setActiveConfiguration(fullfile(pwd,'DashboardConfig.xml'));

Для модели откройте панель мониторинга метрик.

metricsdashboard sf_car

Нажмите кнопку «Все метрики» и запустите все метрики.

Представлен в R2018b