exponenta event banner

Наблюдать объекты с помощью симуляторов. Класс CounterObserver

В этом примере показано, как использовать simevents.SimulationObserver объект для подсчета вылетов объекта и получения временных меток отправления.

Используйте simevents.SimulationObserver объект для наблюдения или визуализации объектов и реализация аниматоров для отладки моделирования модели. Дополнительные сведения см. в разделе Использование класса Observer для мониторинга модели SimEvents.

В этой модели simevents.SimulationObserver объект используется для получения количества объектов, отходящих от блока или набора блоков в модели, и метки времени их отходов. Модель имеет два блока «Генератор сущностей» и «Терминатор сущностей» и «Блок сервера сущностей». В блоках «Scope» отображается число удаляемых сущностей, d - статистика для блоков «Entity Generator» и «Entity Server».

Создание наблюдателя

Откройте новый сценарий и запустите simevents.SimulationObserver объект по этому коду.

classdef myObserverPreexit < simevents.SimulationObserver
    % Add the observer properties.
    properties
    Model
    % Initialize the property count.
    count
    end
properties (Constant, Access=private)
    increment = 1;
end
methods
     % Observe any model by incorporating its name to MyObserverPreexit.
     function this = myObserverPreexit(Model)
         % Input model name to the simulation observer.
         this@simevents.SimulationObserver(Model);
         this.Model = Model;
     end
     % Initialize the count in the simulation start.
     function simStarted(this)
         this.count = 0;
     end
     % Specify list of blocks to be notified of entity entry and exit
     % events.
     function Block = getBlocksToNotify(this)
         Block = this.getAllBlockWithStorages();
     end
     function preExit(this,evSrc,Data)
         % Get the names of all storage blocks that the entities depart.
         % This returns the block with its path.
         Block = Data.Block.BlockPath;
         % Remove the path to display only the
         % block name.
         Block = regexprep(Block,'ObserverPreexitModel/' ,'');
         % Initialize the blocks to observe.
         BlockName = 'Entity Server';
         % If the block that entity exits contains the block name
         % acquire data for exit time and block name.
         if contains(Block, BlockName)
             % Get time for entity preexit from event calendar.
             evCal = this.getEventCalendars;
             Time = evCal(1).TimeNow;
             % Increase the count for departing entities.
             this.count = this.count + this.increment;
             myInfo = [' At time ',num2str(Time), ...
             ' an entity departs ', Block, ', Total entity count is ', ...
             num2str(this.count)];
             disp(myInfo);
             end
         end
     end
 end

Сохранить файл как myObserverPreexit.m файл.

Мониторинг модели

Включить мониторинг объекта-наблюдателя ObserverPreexitModel модель.

obj  = myObserverPreexit('ObserverPreexitModel');

Наблюдатель контролирует блок сервера сущностей, который определяется BlockName параметр в файле наблюдателя myObserverPreexit.m.

  • Моделирование модели. Щелкните Вид (View) Диагностика (Diagnostics) в окне модели и обратите внимание, что количество объектов, покидающих блок сервера сущностей, и временные метки отхода.

  • Для проверки просмотрите блок Scope (Область), в котором отображается Число отклоненных сущностей (Number of entities departed), статистику для блока Entity Server (Сервер сущностей).

Мониторинг нескольких блоков в модели

Используйте одного и того же наблюдателя для мониторинга отклонений объекта от всех блоков генератора объектов в модели.

  • Изменить BlockName в параметре preExit метод для 'Entity Generator'. Блоки генератора объектов в модели помечены как Generator1 объектов и Generator2 объектов.

function preExit(this,evSrc,Data)
    % Get the names of all storage blocks that the entities depart.
    % returns the block with its path.
    Block = Data.Block.BlockPath;
    % Remove the path to display only the block name
    Block = regexprep(Block,'ObserverPreexitModel/' ,'');
    % Initialize the common Entity Generator phrase
    BlockName = 'Entity Generator';
    % If the block that the entity exits contains the block name
    % acquire the exit time and the block name.
    if contains(Block, BlockName)
        % Get the time of entity preexit from the event calendar.
        evCal = this.getEventCalendars;
        Time = evCal(1).TimeNow;
        % Increase the count of departing entities.
        this.count = this.count + this.increment;
         myInfo = [' At time ',num2str(Time), ...
             ' an entity departs ', Block, ', Total entity count is ', ...
         num2str(this.count)];
         disp(myInfo);
    end
end
  • Включить мониторинг объекта-наблюдателя ObserverPreexitModel модель.

obj  = myObserverPreexit('ObserverPreexitModel');
  • Моделирование модели. Наблюдайте за программой Diagnostic Viewer, которая отображает информацию для 15 объекты, отходящие от обоих блоков генератора объектов.

  • Для проверки наблюдайте за тем, как блоки Scope1 и Scope2 отображают количество удаляемых сущностей, статистику d для Generator1 сущностей и Generator2 сущностей.

Обратите внимание, что 4 сущности отходят от Generator1 сущностей.

Также, 11 сущности отходят от Generator2 сущностей. Всего, 15 объекты, удаленные из блоков генератора объектов в модели.

См. также

| | | |

Связанные темы