floating-凯发k8网页登录
this example shows how to use the fixed-point converter app to convert an iir filter from a floating-point to a fixed-point implementation. second-order sections (also referred as biquadratic) structures work better when using fixed-point arithmetic than structures that implement the transfer function directly. we will show that the surest path to a successful "float-to-fixed" conversion consists of the following steps:
select a second-order sections (sos) structure, i.e.
dsp.biquadfilter
perform dynamic range analysis for each node of the filter, i.e. use a test bench approach with simulation minimum and simulation maximum instrumentation
compare alternative biquadratic scaling implementations and view quantization effects due to different choices using '
fvtool
' and spectrumanalyzer
for analysis and verification.
introduction
an efficient way to implement an iir filter is using a second order section (sos) biquad filter structure. suppose for example that we need to remove an interfering high frequency tone signal from a system. one way to achieve this is to use a lowpass filter design.
design a lowpass elliptic filter
use a minimum-order lowpass elliptic direct-form i design for the purpose of this example. the design specifications of the filter are:
passband frequency edge:
stopband frequency edge:
passband ripple:
stopband attenuation:
visualize the cumulative filter response of all the second-order sections using the filter visualization tool.
biquad = design(fdesign.lowpass('fp,fst,ap,ast',0.4,0.45,0.5,80), ... 'ellip',filterstructure='df1sos', systemobject=true, uselegacybiquadfilter=true); fvt = fvtool(biquad, legend='on'); fvt.sosviewsettings.view = 'cumulative';
obtain filter coefficients (sos, b, a) for float vs. fixed comparison
note that the sos filter coefficient values lead to a nearly identical filter response (whether they are double or 16-bit fixed-point values).
sosmatrix = biquad.sosmatrix; sclvalues = biquad.scalevalues; fvt_comp = fvtool(sosmatrix,fi(sosmatrix,1,16)); legend(fvt_comp,'floating-point (double) sos','fixed-point (16-bit) sos');
b = repmat(sclvalues(1:(end-1)),1,3) .* sosmatrix(:,(1:3)); a = sosmatrix(:,(5:6)); num = b'; % matrix of scaled numerator sections den = a'; % matrix of denominator sections
close(fvt); % clean up close(fvt_comp); % clean up
default floating-point operation
verify the filter operation by streaming some data through it and viewing its input-output response. first try filtering a (floating-point) pseudorandom noise signal (sampled at 300 hz) with an interfering additive high-frequency tone, to see if the tone is removed. this will also serve later as our reference signal for a test bench.
wo = 75/(300/2); % 75 hz tone; system running at 300 hz inp_len = 4000; % number of input samples (signal length) inp_itf = 0.5 .* sin((pi*wo) .* (0:(inp_len-1))'); % tone interferer scope = spectrumanalyzer(samplerate=300, ... plotastwosidedspectrum=false, ... showlegend=true, ylimits=[-85 25], ... title='floating-point input signal and filter output signal', ... channelnames={'floating-point input','filter output'}); rng(12345); % seed the rng for repeatable results biquadlpfiltfloat = dsp.biquadfilter(sosmatrixsource='input port', ... scalevaluesinputport=false); for k = 1:10 inp_sig = rand(inp_len,1) - 0.5; % random values in range (-0.5, 0.5) input = inp_sig inp_itf; % combined input signal, range (-1.0, 1.0) out_1 = biquadlpfiltfloat(input,num,den); % filter scope([input,out_1]) % visualize input and filtered output end
clear scope biquadlpfiltfloat; % clean up
default fixed-point operation
now run some fixed-point data through the filters, using the object default settings. note that the default fixed-point behavior leads to incorrect results.
scope = spectrumanalyzer(samplerate=300, ... plotastwosidedspectrum=false, ... showlegend=true, ylimits=[-85 25], ... title='fixed-point input signal and filter output signal', ... channelnames={'fixed-point input','default (incorrect) fixed-point output'}); rng(12345); % seed the rng for repeatable results bqlpfiltfixpt = dsp.biquadfilter(sosmatrixsource='input port', ... scalevaluesinputport=false); for k = 1:10 inp_sig = rand(inp_len,1) - 0.5; % random values in range (-0.5, 0.5) inputfi = fi(inp_sig inp_itf, 1, 16, 15); % signal range (-1.0, 1.0) out_2 = bqlpfiltfixpt(inputfi,fi(num,1,16),fi(den,1,16)); scope([inputfi,out_2]) % visualize end
clear scope bqlpfiltfixpt; % clean up
convert floating-point biquad iir filter function to fixed-point
instead of relying on the default fixed-point settings of the object, convert the object to fixed-point using the fixed-point converter app. this approach yields more visibility and control over individual fixed-point types within the filter implementation, and leads to more correct fixed-point operation.
to first prepare for using the fixed-point converter app, create a function to convert, setting all filter data type choices to ''custom'':
type myiirlowpassbiquad;
function output = myiirlowpassbiquad(inp,num,den) %myiirnotchbiquad biquad lowpass filter implementation % used as part of a matlab fixed point converter app example. % 凯发官网入口首页 copyright 2016-2021 the mathworks, inc. persistent bqlpfilter; if isempty(bqlpfilter) bqlpfilter = dsp.biquadfilter( ... 'sosmatrixsource','input port', ... 'scalevaluesinputport', false, ... 'sectioninputdatatype', 'custom', ... 'sectionoutputdatatype', 'custom', ... 'numeratorproductdatatype', 'custom', ... 'denominatorproductdatatype', 'custom', ... 'numeratoraccumulatordatatype', 'custom', ... 'denominatoraccumulatordatatype', 'custom', ... 'statedatatype', 'custom', ... 'outputdatatype', 'custom'); end output = bqlpfilter(inp, num, den); end
create test bench script
create a test bench to simulate and collect instrumented simulation minimum and simulation maximum values for all of our data type controlled signal paths. this will allow the tool to later propose autoscaled fixed-point settings. use parts of the code above as a test bench script, starting with floating-point inputs and verifying the test bench before simulating and collecting minimum and maximum data. afterward, use the fixed-point converter app to convert the floating-point function implementation to a fixed-point function implementation.
type myiirlowpassbiquad_tb.m;
%% test bench for myiirlowpassbiquad.m % 凯发官网入口首页 copyright 2016-2021 the mathworks, inc. %% pre-designed filter (coefficients stored in mat file): % f = design(fdesign.lowpass('fp,fst,ap,ast',0.4,0.45,0.5,80), ... % 'ellip', filterstructure='df1sos',systemobject=true); % sosmatrix = f.sosmatrix; % sclvalues = f.scalevalues; % b = repmat(sclvalues(1:(end-1)),1,3) .* sosmatrix(:,(1:3)); % a = sosmatrix(:,(5:6)); % num = b'; % den = a'; % save('myiirlowpassbiquaddesign.mat', 'b', 'a', 'num', 'den'); load('myiirlowpassbiquaddesign.mat'); %% interference signal, using values in range (-0.5, 0.5) wo = 75/(300/2); % 75 hz tone; system running at 300 hz inp_len = 4000; sintvec = (0:(inp_len-1))'; inp_itf = 0.5 .* sin((pi*wo) .* sintvec); %% filtering and visualization % filter an input signal, including an interference % tone, to see if the tone is successfully removed. rng(12345); % seed the rng for repeatable results scope = spectrumanalyzer(samplerate=300,... plotastwosidedspectrum=false,showlegend=true,ylimits=[-125 25],... title='input signal and filter output signal', ... channelnames={'input', 'filter output'}); for k = 1:10 inp_sig = rand(inp_len,1) - 0.5; % random values in range (-0.5, 0.5) inp = inp_sig inp_itf; out_1 = myiirlowpassbiquad(inp,num,den); % filter scope([inp,out_1]); % visualize end
convert to fixed-point using the fixed-point converter app
launch the fixed-point converter app. there are two ways to launch the tool: via the matlab® apps menu or via the command 'fixedpointconverter'.
enter the function to convert in the entry-point functions field.
define inputs by entering the test bench script name.
click 'analyze' to collect ranges by simulating the test bench.
observe the collected 'sim min', 'sim max', and 'proposed type' values.
make adjustments to the 'proposed type' fields as needed.
click 'convert' to generate the fixed-point code and view the report.
resulting fixed-point matlab implementation
the generated fixed-point function implementation is as follows:
type myiirlowpassbiquad_fixpt;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % generated by matlab 9.3 and fixed-point designer 6.0 % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %#codegen function output = myiirlowpassbiquad_fixpt(inp,num,den) %myiirnotchbiquad biquad lowpass filter implementation % used as part of a matlab fixed point converter app example. % 凯发官网入口首页 copyright 2016 the mathworks, inc. fm = get_fimath(); persistent bqlpfilter; if isempty(bqlpfilter) bqlpfilter = dsp.biquadfilter( ... 'sosmatrixsource', 'input port', ... 'scalevaluesinputport', false, ... 'sectioninputdatatype', 'custom', ... 'sectionoutputdatatype', 'custom', ... 'numeratorproductdatatype', 'custom', ... 'denominatorproductdatatype', 'custom', ... 'numeratoraccumulatordatatype', 'custom', ... 'denominatoraccumulatordatatype', 'custom', ... 'statedatatype', 'custom', ... 'outputdatatype', 'custom' , ... 'customsectioninputdatatype', numerictype([], 16, 8), ... 'customsectionoutputdatatype', numerictype([], 16, 8), ... 'customnumeratorproductdatatype', numerictype([], 32, 26), ... 'customdenominatorproductdatatype', numerictype([], 32, 23), ... 'customnumeratoraccumulatordatatype', numerictype([], 32, 24), ... 'customdenominatoraccumulatordatatype', numerictype([], 32, 23), ... 'customstatedatatype', numerictype([], 16, 8), ... 'customoutputdatatype', numerictype([], 16, 15)); end output = fi(bqlpfilter(inp, num, den), 1, 16, 15, fm); end function fm = get_fimath() fm = fimath('roundingmethod', 'floor',... 'overflowaction', 'wrap',... 'productmode','fullprecision',... 'maxproductwordlength', 128,... 'summode','fullprecision',... 'maxsumwordlength', 128); end
automation of fixed-point conversion using the command line api
alternatively the fixed-point conversion may be automated using the command line api:
type myiirlowpassf2f_prj_script;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % script generated from project 'myiirlowpassbiquad.prj' on 16-oct-2014. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % create configuration object of class 'coder.fixptconfig'. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% cfg = coder.config('fixpt'); cfg.testbenchname = { sprintf('s:\\work\\15afeatureexamples\\biquad_notch_f2f\\myiirlowpassbiquad_tb.m') }; cfg.defaultwordlength = 16; cfg.logioforcomparisonplotting = true; cfg.testnumerics = true; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % define argument types for entry-point 'myiirlowpassbiquad'. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% args = cell(1,1); args{1} = cell(3,1); args{1}{1} = coder.typeof(0,[4000 1]); args{1}{2} = coder.typeof(0,[3 5]); args{1}{3} = coder.typeof(0,[2 5]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % invoke matlab coder. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% codegen -float2fixed cfg myiirlowpassbiquad -args args{1}
test the converted matlab fixed-point implementation
run the converted fixed-point function and view input-output results.
scope = spectrumanalyzer(samplerate=300, ... plotastwosidedspectrum=false, ... showlegend=true, ylimits=[-85 25], ... title='fixed-point input signal and filter output signal', ... channelnames={'fixed-point input','fixed-point filter output'}); rng(12345); % seed the rng for repeatable results for k = 1:10 inp_sig = rand(inp_len,1) - 0.5; % random values in range (-0.5, 0.5) inputfi = fi(inp_sig inp_itf, 1, 16, 15); % signal range (-1.0, 1.0) out_3 = myiirlowpassbiquad_fixpt(inputfi,fi(num,1,16),fi(den,1,16)); scope([inputfi,out_3]) % visualize end
clear scope; % clean up
the error between the floating-point and fixed-point outputs is shown on the next plot. the error seems rather high. the reason for these differences in output values is dominated by the choice of scaling and ordering of the second-order sections. in the next section, we illustrate a way to reduce this error earlier in the implementation.
fig = figure; subplot(3,1,1); plot(out_1); title('floating-point filter output'); subplot(3,1,2); plot(out_3); title('fixed-point filter output'); subplot(3,1,3); plot(out_1 - double(out_3)); axis([0 4000 -4e-2 7e-2]); title('error');
close(fig); % clean up
re-designing the elliptic filter using infinity-norm scaling
elliptic filter designs have the characteristic of being relatively well scaled when using the 'linf' second-order section scaling (i.e., infinity norm). using this approach often leads to smaller quantization errors.
biquad_linf = design(fdesign.lowpass('fp,fst,ap,ast',0.4,0.45,0.5,80), ... 'ellip',filterstructure='df1sos', ... sosscalenorm='linf', systemobject=true, uselegacybiquadfilter=true); fvt_linf = fvtool(biquad_linf,legend='on'); fvt_linf.sosviewsettings.view = 'cumulative';
notice that none of the cumulative internal frequency responses, measured from the input to the filter to the various states of each section, exceed 0 db. thus, this design is a good candidate for a fixed-point implementation.
obtain linf-norm filter coefficients for float vs. fixed comparison
note that the sos filter coefficient values lead to a nearly identical filter response (whether they are double or 16-bit fixed-point values).
sosmtrlinf = biquad_linf.sosmatrix; sclvallinf = biquad_linf.scalevalues; fvt_comp_linf = fvtool(sosmtrlinf,fi(sosmtrlinf,1,16)); legend(fvt_comp_linf,'floating-point (double) sos, linf scaling', ... 'fixed-point (16-bit) sos, linf scaling');
blinf = repmat(sclvallinf(1:(end-1)),1,3) .* sosmtrlinf(:,(1:3)); alinf = sosmtrlinf(:,(5:6)); numlinf = blinf'; % matrix of scaled numerator sections denlinf = alinf'; % matrix of denominator sections
close(fvt_linf); % clean up close(fvt_comp_linf); % clean up
test the converted matlab fixed-point linf-norm biquad filter
after following the fixed-point converter procedure again, as above, but using the linf-norm scaled filter coefficient values, run the new converted fixed-point function and view input-output results.
scope = spectrumanalyzer(samplerate=300, ... plotastwosidedspectrum=false,showlegend=true, ... ylimits=[-85 25],... title='fixed-point input signal and linf-norm filter output signal', ... channelnames={'fixed-point input','fixed-point linf-norm filter output'}); rng(12345); % seed the rng for repeatable results for k = 1:10 inp_sig = rand(inp_len,1) - 0.5; % random values in range (-0.5, 0.5) inputfi = fi(inp_sig inp_itf, 1, 16, 15); % signal range (-1.0, 1.0) out_4 = myiirlinfbiquad_fixpt( ... inputfi,fi(numlinf,1,16),fi(denlinf,1,16)); scope([inputfi,out_4]) % visualize end
clear scope; % clean up
reduced fixed-point implementation error using linf-norm sos scaling
infinity-norm sos scaling often produces outputs with lower error.
fig1 = figure; subplot(3,1,1); plot(out_1); title('floating-point filter output'); subplot(3,1,2); plot(out_4); title('fixed-point (linf-norm sos) filter output'); subplot(3,1,3); plot(out_1 - double(out_4)); axis([0 4000 0 1e-3]); title('error');
fig2 = figure; subplot(2,1,1); plot(out_1 - double(out_3)); axis([0 4000 -4e-2 7e-2]); title('fixed-point error (default sos filter scaling)'); subplot(2,1,2); plot(out_1 - double(out_4)); axis([0 4000 0 1e-3]); title('fixed-point error (''linf'' sos filter scaling)');
close(fig1); % clean up close(fig2); % clean up
summary
we have outlined a procedure to convert a floating-point iir filter to a fixed-point implementation. the dsp.biquadfilter
objects of the dsp system toolbox™ are equipped with simulation minimum and maximum instrumentation capabilities that help the fixed-point converter app automatically and dynamically scale internal filter signals. in addition, various 'fvtool' and spectrumanalyzer analyses provide tools to the user to perform verifications at each step of the process.