getMetricIDs

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

Получите метрический идентификатор для пользовательского Метрического виджета Инструментальной панели

Синтаксис

metricID = getMetricIDs(CustomWidget)

Описание

metricID = getMetricIDs(CustomWidget) возвращает метрику identifer для объекта slmetric.dashboard.CustomWidget.

Входные параметры

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

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

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

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

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

Метрический идентификатор сопоставлен с объектом slmetric.dashboard.CustomWidget.

Примеры

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

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

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

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.AggregateComponentDetails = true;
        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 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

Нажмите кнопку All Metrics и запустите все метрики.

Введенный в R2018b

Для просмотра документации необходимо авторизоваться на сайте