exponenta event banner

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

В этом примере показано, как оптимизировать типы данных с фиксированной точкой с помощью fxpopt использование пользовательских поведенческих ограничений в частотной области. Модели Simulink ® в этом примере демонстрируют два способа использования блоков из библиотеки проверки модели для создания пользовательских поведенческих ограничений на SNR (отношение сигнал/шум) фильтра нижних частот. В первом примере вычисляют приближение уровня шума; во втором примере вычисляют разность SNR между исходной моделью и квантованной моделью, которая использует типы данных с фиксированной точкой.

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

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

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

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

2. Проверки утверждения на основе моделирования - блоки в библиотеке блоков проверки модели можно использовать для создания пользовательских выражений проверки. Разрешенные блоки проверки модели в модели интерпретируются решателем оптимизации как поведенческие ограничения.

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

Пример 1. Расчет аппроксимации уровня шума

В этом примере выполняется преобразование фильтра нижних частот для использования оптимизированных типов данных с фиксированной точкой с помощью fxpopt. Для обеспечения соответствия встроенной версии требованиям SNR модель mLowPass_NoiseFloor содержит дополнительную логику для вычисления уровня шума сигнала на выходе фильтра. Этот сигнал затем направляется в Validate , которая использует блок Check State Range из библиотеки блоков проверки модели. Если значения уровня шума, рассчитанные при моделировании, выходят за пределы заданного статического диапазона, 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: Расчет разности SNR между исходной и квантованной моделями

В этом примере оптимизируйте типы данных с фиксированной точкой для модели фильтра нижних частот. mLowPass_SNR, используя другой набор поведенческих ограничений, которые сравнивают SNR встроенного фильтра с SNR исходного фильтра, который использует типы данных с двойной точностью. ValidateSNR подсистема сначала вычисляет SNR, затем использует блок Check Static Lower Bound из библиотеки проверки модели, чтобы подтвердить, что SNR больше 60. Если SNR падает ниже указанного значения, то 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 1007, meets the behavioral constraints.
		- Updated best found solution, cost: 1007
		- Evaluating new solution: cost 1006, meets the behavioral constraints.
		- Updated best found solution, cost: 1006
		- Evaluating new solution: cost 1005, meets the behavioral constraints.
		- Updated best found solution, cost: 1005
		- Evaluating new solution: cost 1004, meets the behavioral constraints.
		- Updated best found solution, cost: 1004
		- Evaluating new solution: cost 1003, meets the behavioral constraints.
		- Updated best found solution, cost: 1003
		- Evaluating new solution: cost 1002, meets the behavioral constraints.
		- Updated best found solution, cost: 1002
		- Evaluating new solution: cost 1000, meets the behavioral constraints.
		- Updated best found solution, cost: 1000
		- Evaluating new solution: cost 999, does not meet the behavioral constraints.
		- Evaluating new solution: cost 999, does not meet the behavioral constraints.
		- Evaluating new solution: cost 999, does not meet the behavioral constraints.
		- Evaluating new solution: cost 999, does not meet the behavioral constraints.
		- Evaluating new solution: cost 999, does not meet the behavioral constraints.
		- Evaluating new solution: cost 999, does not meet the behavioral constraints.
		- Evaluating new solution: cost 999, meets the behavioral constraints.
		- Updated best found solution, cost: 999
		- Evaluating new solution: cost 998, meets the behavioral constraints.
		- Updated best found solution, cost: 998
		- Evaluating new solution: cost 997, meets the behavioral constraints.
		- Updated best found solution, cost: 997
		- Evaluating new solution: cost 996, meets the behavioral constraints.
		- Updated best found solution, cost: 996
		- 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 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, meets the behavioral constraints.
		- Updated best found solution, cost: 979
		- Evaluating new solution: cost 978, meets the behavioral constraints.
		- Updated best found solution, cost: 978
		- Evaluating new solution: cost 977, meets the behavioral constraints.
		- Updated best found solution, cost: 977
		- Evaluating new solution: cost 976, does not meet the behavioral constraints.
		- Evaluating new solution: cost 976, meets the behavioral constraints.
		- Updated best found solution, cost: 976
		- Evaluating new solution: cost 975, does not meet the behavioral constraints.
		- 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, 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, does not meet the behavioral constraints.
		- Evaluating new solution: cost 965, does not meet the behavioral constraints.
		- Evaluating new solution: cost 965, does not meet the behavioral constraints.
		- Evaluating new solution: cost 965, meets the behavioral constraints.
		- Updated best found solution, cost: 965
		- Evaluating new solution: cost 964, does not meet the behavioral constraints.
		- Evaluating new solution: cost 964, does not meet the behavioral constraints.
		- Evaluating new solution: cost 964, does not meet the behavioral constraints.
		- Evaluating new solution: cost 964, does not meet the behavioral constraints.
		- Evaluating new solution: cost 964, meets the behavioral constraints.
		- Updated best found solution, cost: 964
		- 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);