Выполните оптимизацию типа данных с пользовательскими поведенческими ограничениями

В этом примере показано, как оптимизировать типы данных с фиксированной точкой с fxpopt использование пользовательских поведенческих ограничений в частотном диапазоне. Модели Simulink® в этом примере демонстрируют два способа использовать блоки от библиотеки Model Verification до автора пользовательские поведенческие ограничения на ОСШ (отношение сигнал-шум) фильтра lowpass. В первом примере вычислите приближение уровня шума; во втором примере вычислите разность в ОСШ между исходной моделью и квантованной моделью, которая использует типы данных с фиксированной точкой.

Поведенческие ограничения для оптимизации типа данных

Оптимизация типа данных стремится минимизировать целевую функцию, такую как общая битная ширина, при поддержании исходного поведения системы в заданном допуске. Во время оптимизации программное обеспечение устанавливает базовую линию путем симуляции исходной модели. Программное обеспечение затем создает различные версии фиксированной точки вашей модели и запускает симуляции, чтобы определить поведение с помощью новых типов данных. Оптимизация выбирает модель, которая минимизирует целевую функцию, также соответствуя заданным поведенческим ограничениям.

Чтобы определить, приемлемо ли поведение новой реализации фиксированной точки, оптимизация требует четко определенных поведенческих ограничений. Необходимо задать по крайней мере одно поведенческое ограничение. Существует два способа задать поведенческие ограничения для использования с fxpopt:

1. Основанные на допуске сравнения симуляции с базовой ссылкой - можно добавить допуски к сигналам, которые имеют сигнал, регистрирующий, позволил использовать addTolerance метод fxpOptimizationOptions. Допуск задает конверт передающего поведения относительно базовой симуляции модели.

2. Основанные на симуляции проверки утверждения - можно использовать блоки в библиотеке блоков Model Verification, чтобы создать пользовательские выражения верификации. Enabled блоки верификации модели в вашей модели интерпретированы как поведенческие ограничения решателем оптимизации.

Можно также использовать комбинацию допусков сигнала и блоков верификации модели, чтобы задать поведенческие ограничения для модели. Для получения дополнительной информации смотрите, Задают Поведенческие Ограничения.

Пример 1: вычислите приближение уровня шума

В этом примере вы преобразуете фильтр lowpass, чтобы использовать оптимизированные типы данных с фиксированной точкой с помощью fxpopt. Гарантировать, что встроенная версия все еще удовлетворяет требования ОСШ, модель mLowPass_NoiseFloor содержит дополнительную логику, чтобы вычислить уровень шума сигнала при выходе фильтра. Этот сигнал затем направляется к Validate подсистема, которая использует блок Check State Range из библиотеки блоков Model Verification. Если значения уровня шума, вычисленные в процессе моделирования, находятся вне указанного статического диапазона, fxpopt интерпретирует модель как не передачу поведенческих ограничений.

Чтобы начаться, откройте систему, для которой вы хотите оптимизировать типы данных.

model = 'mLowPass_NoiseFloor';
sud = [model '/Embedded_Filter'];
open_system(model);

Используйте fxpopt функционируйте, чтобы запустить оптимизацию. Поскольку блок верификации модели используется, чтобы задать ограничения, он не требуется, чтобы задавать допуски сигнала с помощью addTolerance метод fxpOptimizationOptions.

result = fxpopt(model,sud)
	+ Starting data type optimization...
	+ Checking for unsupported constructs.
	+ Preprocessing
	+ Modeling the optimization problem
		- Constructing decision variables
	+ Running the optimization solver
		- Evaluating new solution: cost 110, meets the behavioral constraints.
		- Updated best found solution, cost: 110
	+ Optimization has finished.
		- Neighborhood search complete.
		- Reached limit of number of iterations without updates to the current best solution.
	+ Fixed-point implementation that satisfies the behavioral constraints found. The best found solution is applied on the model.
		- Total cost: 110
		- Use the explore method of the result to explore the implementation.

result = 

  OptimizationResult with properties:

                  Model: 'mLowPass_NoiseFloor'
      SystemUnderDesign: 'mLowPass_NoiseFloor/Embedded_Filter'
           FinalOutcome: 'Fixed-point implementation that satisfies the behavioral constraints found. The best found solution is applied on the model.'
    OptimizationOptions: [1x1 fxpOptimizationOptions]
              Solutions: [1x1 DataTypeOptimization.OptimizationSolution]

Используйте explore метод, чтобы исследовать проект, содержащий оптимизированные типы данных с фиксированной точкой.

explore(result);

Пример 2: вычислите ОСШ Diffierence между исходными и квантованными моделями

В этом примере оптимизируйте типы данных с фиксированной точкой для модели фильтра lowpass, mLowPass_SNR, использование различного набора поведенческих ограничений, которые сравнивают ОСШ встроенного фильтра с ОСШ исходного фильтра, который использует типы данных с двойной точностью. ValidateSNR подсистема сначала вычисляет ОСШ, затем использует блок Check Static Lower Bound из библиотеки Model Verification, чтобы утверждать, что ОСШ больше 60. Если ОСШ опускается ниже этого заданного значения, то fxpopt интерпретирует модель как не передачу поведенческих ограничений.

Чтобы начаться, откройте систему, для которой вы хотите оптимизировать типы данных.

model = 'mLowPass_SNR';
sud = [model '/Embedded_Filter'];
Source = 1;
open_system(model);

В данном примере задайте сценарии дополнительной симуляции путем создания Simulink.SimulationInput объект. Используйте один вход синусоиды с частотой 100 рад/секунда и второй вход синусоиды с частотой 500 рад/секунда. fxpopt рассмотрит оба сценария симуляции во время оптимизации. Исчерпывающий набор входных сигналов может помочь гарантировать, что полный рабочий диапазон вашего проекта осуществлен во время процесса оптимизации.

si(1) = Simulink.SimulationInput(model);
si(1) = si(1).setVariable('Source',1);
si(2) = Simulink.SimulationInput(model);
si(2) = si(2).setVariable('Source',2);

Создайте fxpOptimizationOptions объект. Используйте расширенные настройки, чтобы задать сценарии симуляции, чтобы рассмотреть во время оптимизации.

options = fxpOptimizationOptions();
options.AdvancedOptions.SimulationScenarios = si;

Используйте fxpopt функционируйте, чтобы запустить оптимизацию. Поскольку блок верификации модели используется, чтобы задать ограничения, он не требуется, чтобы задавать допуски сигнала с помощью addTolerance метод fxpOptimizationOptions.

result = fxpopt(model,sud,options);
	+ Starting data type optimization...
	+ Checking for unsupported constructs.
	+ Preprocessing
	+ Modeling the optimization problem
		- Constructing decision variables
	+ Running the optimization solver
		- Evaluating new solution: cost 112, does not meet the behavioral constraints.
		- Evaluating new solution: cost 168, does not meet the behavioral constraints.
		- Evaluating new solution: cost 224, does not meet the behavioral constraints.
		- Evaluating new solution: cost 280, does not meet the behavioral constraints.
		- Evaluating new solution: cost 336, does not meet the behavioral constraints.
		- Evaluating new solution: cost 392, does not meet the behavioral constraints.
		- Evaluating new solution: cost 448, does not meet the behavioral constraints.
		- Evaluating new solution: cost 504, does not meet the behavioral constraints.
		- Evaluating new solution: cost 560, does not meet the behavioral constraints.
		- Evaluating new solution: cost 616, does not meet the behavioral constraints.
		- Evaluating new solution: cost 672, does not meet the behavioral constraints.
		- Evaluating new solution: cost 728, does not meet the behavioral constraints.
		- Evaluating new solution: cost 784, does not meet the behavioral constraints.
		- Evaluating new solution: cost 840, does not meet the behavioral constraints.
		- Evaluating new solution: cost 896, does not meet the behavioral constraints.
		- Evaluating new solution: cost 952, does not meet the behavioral constraints.
		- Evaluating new solution: cost 1008, meets the behavioral constraints.
		- Updated best found solution, cost: 1008
		- Evaluating new solution: cost 995, meets the behavioral constraints.
		- Updated best found solution, cost: 995
		- Evaluating new solution: cost 994, meets the behavioral constraints.
		- Updated best found solution, cost: 994
		- Evaluating new solution: cost 993, meets the behavioral constraints.
		- Updated best found solution, cost: 993
		- Evaluating new solution: cost 992, meets the behavioral constraints.
		- Updated best found solution, cost: 992
		- Evaluating new solution: cost 991, meets the behavioral constraints.
		- Updated best found solution, cost: 991
		- Evaluating new solution: cost 990, meets the behavioral constraints.
		- Updated best found solution, cost: 990
		- Evaluating new solution: cost 989, meets the behavioral constraints.
		- Updated best found solution, cost: 989
		- Evaluating new solution: cost 988, meets the behavioral constraints.
		- Updated best found solution, cost: 988
		- Evaluating new solution: cost 987, meets the behavioral constraints.
		- Updated best found solution, cost: 987
		- Evaluating new solution: cost 986, meets the behavioral constraints.
		- Updated best found solution, cost: 986
		- Evaluating new solution: cost 985, meets the behavioral constraints.
		- Updated best found solution, cost: 985
		- Evaluating new solution: cost 984, meets the behavioral constraints.
		- Updated best found solution, cost: 984
		- Evaluating new solution: cost 982, meets the behavioral constraints.
		- Updated best found solution, cost: 982
		- Evaluating new solution: cost 981, does not meet the behavioral constraints.
		- Evaluating new solution: cost 981, does not meet the behavioral constraints.
		- Evaluating new solution: cost 981, does not meet the behavioral constraints.
		- Evaluating new solution: cost 981, does not meet the behavioral constraints.
		- Evaluating new solution: cost 981, does not meet the behavioral constraints.
		- Evaluating new solution: cost 981, does not meet the behavioral constraints.
		- Evaluating new solution: cost 981, meets the behavioral constraints.
		- Updated best found solution, cost: 981
		- Evaluating new solution: cost 980, meets the behavioral constraints.
		- Updated best found solution, cost: 980
		- Evaluating new solution: cost 979, does not meet the behavioral constraints.
		- Evaluating new solution: cost 979, meets the behavioral constraints.
		- Updated best found solution, cost: 979
		- Evaluating new solution: cost 978, does not meet the behavioral constraints.
		- Evaluating new solution: cost 978, meets the behavioral constraints.
		- Updated best found solution, cost: 978
		- Evaluating new solution: cost 977, does not meet the behavioral constraints.
		- Evaluating new solution: cost 977, meets the behavioral constraints.
		- Updated best found solution, cost: 977
		- Evaluating new solution: cost 976, meets the behavioral constraints.
		- Updated best found solution, cost: 976
		- Evaluating new solution: cost 975, meets the behavioral constraints.
		- Updated best found solution, cost: 975
		- Evaluating new solution: cost 974, does not meet the behavioral constraints.
		- Evaluating new solution: cost 974, meets the behavioral constraints.
		- Updated best found solution, cost: 974
		- Evaluating new solution: cost 973, does not meet the behavioral constraints.
		- Evaluating new solution: cost 973, meets the behavioral constraints.
		- Updated best found solution, cost: 973
		- Evaluating new solution: cost 972, does not meet the behavioral constraints.
		- Evaluating new solution: cost 972, meets the behavioral constraints.
		- Updated best found solution, cost: 972
		- Evaluating new solution: cost 971, meets the behavioral constraints.
		- Updated best found solution, cost: 971
		- Evaluating new solution: cost 970, meets the behavioral constraints.
		- Updated best found solution, cost: 970
		- Evaluating new solution: cost 969, meets the behavioral constraints.
		- Updated best found solution, cost: 969
		- Evaluating new solution: cost 968, meets the behavioral constraints.
		- Updated best found solution, cost: 968
		- Evaluating new solution: cost 967, meets the behavioral constraints.
		- Updated best found solution, cost: 967
		- Evaluating new solution: cost 966, meets the behavioral constraints.
		- Updated best found solution, cost: 966
		- Evaluating new solution: cost 965, meets the behavioral constraints.
		- Updated best found solution, cost: 965
		- Evaluating new solution: cost 964, meets the behavioral constraints.
		- Updated best found solution, cost: 964
		- Evaluating new solution: cost 951, does not meet the behavioral constraints.
		- Evaluating new solution: cost 963, does not meet the behavioral constraints.
		- Evaluating new solution: cost 963, does not meet the behavioral constraints.
		- Evaluating new solution: cost 963, does not meet the behavioral constraints.
		- Evaluating new solution: cost 963, does not meet the behavioral constraints.
		- Evaluating new solution: cost 963, does not meet the behavioral constraints.
	+ Optimization has finished.
		- Neighborhood search complete.
		- Maximum number of iterations completed.
	+ Fixed-point implementation that satisfies the behavioral constraints found. The best found solution is applied on the model.
		- Total cost: 964
		- Use the explore method of the result to explore the implementation.

Используйте explore метод, чтобы исследовать проект, содержащий оптимизированные типы данных с фиксированной точкой.

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