getGroupName

Класс: slmetric.metric. ResultDetail
Пакет: slmetric.metric

Получите имя для группы объектов slmetric.metric.ResultDetail

Синтаксис

groupName = getGroupName(mrd)

Описание

Получите имя группы объектов slmetric.metric.ResultDetail. Вызов метода execute собирает метрические данные. Вызов getMetrics получает доступ к объектам slmetric.metric.Result, которые включают объекты slmetric.metric.ResultDetail. Примените метод getGroupName к объекту slmetric.metric.ResultDetail.

пример

groupName = getGroupName(mrd) получает имя для объекта slmetric.metric.ResultDetail mrd.

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

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

Вызов метода slmetric.Engine.execute создает объекты slmetric.metric.Result, которые включают объекты slmetric.metric.ResultDetail.

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

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

Назовите для группы объектов slmetric.metric.ResultDetail

Примеры

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

Используйте getGroupName и методы getGroupIdentifier, чтобы получить имя и идентификатор для группы клонов.

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

open_system([docroot '\toolbox\simulink\examples\ex_clone_detection.slx']);

Сохраните модель в качестве примера в свою текущую рабочую папку.

Вызовите метод execute. Примените метод getMetrics для метрик mathworks.metric.CloneDetection.

metric_engine = slmetric.Engine();
setAnalysisRoot(metric_engine,'Root','ex_clone_detection','RootType','Model');
execute(metric_engine);
rc = getMetrics(metric_engine,'mathworks.metrics.CloneDetection');

Для каждого объекта slmetric.metric.Result отобразите ComponentPath. Для каждого объекта slmetric.metric.ResultDetail отобразите имя группы клонов и идентификатор.

for n=1:length(rc.Results)
    if rc.Results(n).Value > 0
	for m=1:length(rc.Results(n).Details)
	  disp(['ComponentPath: ',rc.Results(n).ComponentPath]);
          disp(['Group Name: ',rc.Results(n).Details(m).getGroupName]);
          disp(['Group Identifier: ',rc.Results(n).Details(m).getGroupIdentifier]);
        end
    else
        disp(['No results for ComponentPath: ',rc.Results(n).ComponentPath]);
    end
    disp(' ');
end

Результаты показывают, что модель содержит одну группу клонов, CloneGroup1, который содержит два клона.

Используйте метод setGroup, чтобы сгруппировать подробные результаты. Когда вы создаете пользовательскую образцовую метрику, вы применяете этот метод как часть метода algorithm.

Используя функцию createNewMetricClass, создайте метрический класс под названием DataStoreCount. Эта метрика рассчитывает, количество Записи Чтения и Хранилища данных Хранилища данных блокирует и собирает в группу их соответствующим Блоком памяти Хранилища данных. Функция createNewMetricClass создает файл, DataStoreCount.m, в текущей рабочей папке. Файл содержит конструктора и пустой метрический метод алгоритма. В данном примере убедитесь, что вы работаете в перезаписываемой папке.

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

Чтобы написать метрический алгоритм, откройте файл DataStoreCount.m и добавьте метрику в файл. В данном примере можно создать метрический алгоритм путем копирования этой логики в файл DataStoreCount.m.

classdef DataStoreCount < slmetric.metric.Metric
    % Count the number of Data Store Read and Data Store Write
    % blocks and correlate them across components.
    
    methods
        function this = DataStoreCount()
            this.ID = 'DataStoreCount';
            this.ComponentScope = [Advisor.component.Types.Model, ...
                Advisor.component.Types.SubSystem];
            this.AggregationMode = slmetric.AggregationMode.Sum;
            this.AggregateComponentDetails = true;
            this.CompileContext = 'None';
            this.Version = 1;
            this.SupportsResultDetails = true;
            
            %Textual information on the metric algorithm
            this.Name = 'Data store usage';
            this.Description = 'Metric that counts the number of Data Store Read and Write'; 
                  'blocks and groups them by the corresponding Data Store Memory block.';
            
        end
        
        function res = algorithm(this, component)
            % Use find_system to get all blocks inside this component.
            dswBlocks = find_system(getPath(component), ...
                'SearchDepth', 1, ...
                'BlockType', 'DataStoreWrite');
            dsrBlocks = find_system(getPath(component), ...
                'SearchDepth', 1, ...
                'BlockType', 'DataStoreRead');          
            
            % Create a ResultDetail object for each data store read and write block.
			% Group ResultDetails by the data store name.
            details1 = slmetric.metric.ResultDetail.empty();
            for i=1:length(dswBlocks)
                details1(i) = slmetric.metric.ResultDetail(getfullname(dswBlocks{i}),...
                            get_param(dswBlocks{i}, 'Name'));
		   groupID = get_param(dswBlocks{i},'DataStoreName');
		   groupName = get_param(dswBlocks{i},'DataStoreName');
                details1(i).setGroup(groupID, groupName);                
                details1(i).Value = 1;
            end
            
            details2 = slmetric.metric.ResultDetail.empty();
            for i=1:length(dsrBlocks)
                details2(i) = slmetric.metric.ResultDetail(getfullname(dsrBlocks{i}),...
                   get_param(dsrBlocks{i}, 'Name'));
                groupID = get_param(dsrBlocks{i},'DataStoreName');
				groupName = get_param(dsrBlocks{i},'DataStoreName');
                details2(i).setGroup(groupID, groupName);
                details2(i).Value = 1;
            end
            
            res = slmetric.metric.Result();
            res.ComponentID = component.ID;
            res.MetricID = this.ID;
            res.Value = length(dswBlocks)+ length(dsrBlocks);
            res.Details = [details1 details2];
        end
    end
end

В метрическом классе DataStoreCount метод SupportsResultDetail установлен в истину. Метрический алгоритм содержит логику для метода setGroup.

Теперь, когда ваша новая образцовая метрика задана в DataStoreCount.m, укажите новую метрику.

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

Чтобы собрать метрические данные по моделям, используйте экземпляры slmetric.Engine. Используя метод getMetrics, задайте метрику, которую вы хотите собрать. В данном примере укажите, что хранилище данных считает метрику для thesldemo_mdlref_dsm модели.

Загрузите модель sldemo_mdlref_dsm.

model = 'sldemo_mdlref_dsm';
load_system(model);

Создайте метрический объект механизма и установите аналитический корень.

metric_engine = slmetric.Engine();
setAnalysisRoot(metric_engine,'Root',model,'RootType','Model');

Соберите метрические данные для метрики количества Хранилища данных.

execute(metric_engine);
rc=getMetrics(metric_engine, id_metric);

Для каждого объекта slmetric.metric.Result отобразите ComponentPath. Для каждого объекта slmetric.metric.ResultDetails отобразите название группы Хранилища данных и идентификатор.

for n=1:length(rc.Results)
    if rc.Results(n).Value > 0
	for m=1:length(rc.Results(n).Details)
	  disp(['ComponentPath: ',rc.Results(n).ComponentPath]);
          disp(['Group Name: ',rc.Results(n).Details(m).getGroupName]);
          disp(['Group Identifier: ',rc.Results(n).Details(m).getGroupIdentifier]);
        end
    else
        disp(['No results for ComponentPath: ',rc.Results(n).ComponentPath]);
    end
    disp(' ');
end

Вот результаты.

ComponentPath: sldemo_mdlref_dsm
Group Name: ErrorCond
Group Identifier: ErrorCond
 
No results for ComponentPath: sldemo_mdlref_dsm/More Info1
 
ComponentPath: sldemo_mdlref_dsm_bot
Group Name: RefSignalVal
Group Identifier: RefSignalVal
 
ComponentPath: sldemo_mdlref_dsm_bot2
Group Name: ErrorCond
Group Identifier: ErrorCond
 
ComponentPath: sldemo_mdlref_dsm_bot/PositiveSS
Group Name: RefSignalVal
Group Identifier: RefSignalVal
 
ComponentPath: sldemo_mdlref_dsm_bot/NegativeSS
Group Name: RefSignalVal
Group Identifier: RefSignalVal

В данном примере не укажите метрику количества хранилища данных.

slmetric.metric.unregisterMetric(id_metric);

Закройте модель.

clear;
bdclose('all');

Введенный в R2017b

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