├── .coveragerc ├── .github ├── FUNDING.yml └── workflows │ ├── python-package-conda.yml │ └── python-package.yml ├── .gitignore ├── .travis.yml ├── CHANGES.rst ├── LICENSE ├── MANIFEST.in ├── README.md ├── ROADMAP.md ├── delsig ├── Contents.m ├── DSToolbox.pdf ├── DocumentNTF.m ├── ESLselect.m ├── LCObj.m ├── LCObj1.m ├── LCoptparam2tf.m ├── LCparam2tf.m ├── LCplotTF.m ├── OnePageStory.pdf ├── PlotExampleSpectrum.m ├── PosInvSet │ ├── dotplot.m │ ├── dscut.m │ ├── dsexpand.m │ ├── dsisPlot.m │ ├── dsistest.m │ ├── dsmap.m │ ├── dssplit2d.m │ ├── edgeplot.m │ ├── find2dPIS.m │ ├── findPIS.m │ ├── hull2d.m │ ├── leftof.m │ ├── outconvex2d.m │ ├── outsideConvex.m │ ├── polyplot.m │ ├── qhull.m │ ├── qhull │ │ ├── COPYING.txt │ │ ├── MEXChanges.txt │ │ ├── Makefile │ │ ├── geom.c │ │ ├── geom.h │ │ ├── geom2.c │ │ ├── global.c │ │ ├── io.c │ │ ├── io.h │ │ ├── mem.c │ │ ├── mem.h │ │ ├── merge.c │ │ ├── merge.h │ │ ├── mex.c │ │ ├── poly.c │ │ ├── poly.h │ │ ├── poly2.c │ │ ├── qhull.c │ │ ├── qhull.h │ │ ├── qhull_a.h │ │ ├── set.c │ │ ├── set.h │ │ ├── stat.c │ │ ├── stat.h │ │ ├── unix.c │ │ └── user.h │ ├── sgn.m │ └── uvar.m ├── Readme.m ├── SIunits.m ├── addPIS.m ├── ai2mif.c ├── axisLabels.m ├── bilogplot.m ├── bplogsmooth.m ├── bquantize.m ├── bunquantize.m ├── calculateQTF.m ├── calculateSNR.m ├── calculateTF.m ├── cancelPZ.m ├── changeFig.m ├── circ_smooth.m ├── clans.m ├── clans5.m ├── clans6.m ├── dbm.m ├── dbp.m ├── dbv.m ├── delay.m ├── demo22mash.m ├── demoLPandBP.m ├── designHBF.m ├── designHBF6.m ├── designHBF7.m ├── designLCBP.m ├── designLCBP6.m ├── designPBF.m ├── ds_f1f2.m ├── ds_filt.m ├── ds_freq.m ├── ds_hann.m ├── ds_optzeros.m ├── ds_orderString.m ├── ds_quantize.m ├── ds_synNTFobj1.m ├── ds_therm.m ├── dsclansNTF.m ├── dsclansObj.m ├── dsdemo1.m ├── dsdemo2.m ├── dsdemo3.m ├── dsdemo4.m ├── dsdemo4.mat ├── dsdemo4fig.m ├── dsdemo5.m ├── dsdemo6.m ├── dsdemo7.m ├── dsdemo8.m ├── dsexample1.m ├── dsexample2.m ├── dsexample3.m ├── dsexample4.m ├── evalF0.m ├── evalF1.m ├── evalMixedTF.m ├── evalRPoly.m ├── evalTF.m ├── evalTFP.m ├── exampleHBF.m ├── figureMagic.m ├── findPattern.m ├── flattenStruct.c ├── flattenStruct.m ├── frespF1.m ├── frespHBF.m ├── frespPBF.m ├── impL1.m ├── impulsePBF.m ├── infnorm.m ├── l1norm.m ├── logsmooth.m ├── lollipop.m ├── mapABCD.m ├── mapCtoD.m ├── mapQtoR.m ├── mapRtoQ.m ├── mod1.m ├── mod2.m ├── nabsH.m ├── padb.m ├── padl.m ├── padr.m ├── padt.m ├── partitionABCD.m ├── peakSNR.m ├── plotPZ.m ├── plotSpectrum.m ├── plotUsage.m ├── predictSNR.m ├── printmif.m ├── pulse.m ├── realizeNTF.m ├── realizeNTF_ct.m ├── realizeQNTF.m ├── rms.m ├── rmsGain.m ├── scaleABCD.m ├── selectElement.m ├── selectQESL.m ├── shiftPBF.m ├── simulateBiDWA.m ├── simulateDSM.c ├── simulateDSM.m ├── simulateESL.c ├── simulateESL.m ├── simulateHBF.m ├── simulateMS.c ├── simulateMS.m ├── simulateMXS.m ├── simulateQDSM.m ├── simulateQESL.m ├── simulateQSNR.m ├── simulateSNR.m ├── simulateSwap.m ├── simulateTSMS.m ├── simulateXS.m ├── sinc_decimate.m ├── stuffABCD.m ├── synthesizeChebyshevNTF.m ├── synthesizeNTF.m ├── synthesizeNTF0.m ├── synthesizeNTF1.m ├── synthesizeQNTF.m ├── thermometer.m ├── undbm.m ├── undbp.m ├── undbv.m └── zinc.m ├── deltasigma ├── _DocumentNTF.py ├── _PlotExampleSpectrum.py ├── _SIunits.py ├── __init__.py ├── _axisLabels.py ├── _bilogplot.py ├── _bplogsmooth.py ├── _bquantize.py ├── _bunquantize.py ├── _calculateQTF.py ├── _calculateSNR.py ├── _calculateTF.py ├── _cancelPZ.py ├── _changeFig.py ├── _circ_smooth.py ├── _clans.py ├── _config.py ├── _constants.py ├── _db.py ├── _dbm.py ├── _dbp.py ├── _dbv.py ├── _delay.py ├── _ds_f1f2.py ├── _ds_freq.py ├── _ds_hann.py ├── _ds_optzeros.py ├── _ds_quantize.py ├── _ds_synNTFobj1.py ├── _dsclansNTF.py ├── _evalF0.py ├── _evalF1.py ├── _evalMixedTF.py ├── _evalRPoly.py ├── _evalTF.py ├── _evalTFP.py ├── _figureMagic.py ├── _frespF1.py ├── _impL1.py ├── _infnorm.py ├── _l1norm.py ├── _logsmooth.py ├── _lollipop.py ├── _mapABCD.py ├── _mapCtoD.py ├── _mapQtoR.py ├── _mapRtoQ.py ├── _mod1.py ├── _mod2.py ├── _nabsH.py ├── _padb.py ├── _padl.py ├── _padr.py ├── _padt.py ├── _partitionABCD.py ├── _peakSNR.py ├── _plotPZ.py ├── _plotSpectrum.py ├── _predictSNR.py ├── _pulse.py ├── _realizeNTF.py ├── _realizeNTF_ct.py ├── _realizeQNTF.py ├── _rms.py ├── _rmsGain.py ├── _scaleABCD.py ├── _simulateDSM.py ├── _simulateDSM_cblas.pyx ├── _simulateDSM_helper.pxi ├── _simulateDSM_python.py ├── _simulateDSM_scipy_blas.pyx ├── _simulateQDSM.py ├── _simulateQDSM_core.pxd ├── _simulateQDSM_core.py ├── _simulateQSNR.py ├── _simulateSNR.py ├── _sinc_decimate.py ├── _stuffABCD.py ├── _synthesizeChebyshevNTF.py ├── _synthesizeNTF.py ├── _synthesizeNTF0.py ├── _synthesizeNTF1.py ├── _synthesizeQNTF.py ├── _thermometer.py ├── _undbm.py ├── _undbp.py ├── _undbv.py ├── _utils.py ├── _zinc.py └── tests │ ├── __init__.py │ ├── test_DocumentNTF.py │ ├── test_PlotExampleSpectrum.py │ ├── test_SIunits.py │ ├── test_axisLabels.py │ ├── test_bilogplot.py │ ├── test_bplogsmooth.py │ ├── test_bquantize.py │ ├── test_bunquantize.py │ ├── test_calculateQTF.py │ ├── test_calculateSNR.py │ ├── test_calculateTF.py │ ├── test_cancelPZ.py │ ├── test_changeFig.py │ ├── test_circ_smooth.py │ ├── test_clans.py │ ├── test_data │ ├── test_bplogsmooth.mat │ ├── test_bquantize.mat │ ├── test_bquantize.txt │ ├── test_circ_smooth.mat │ ├── test_circ_smooth.txt │ ├── test_ds_optzeros.mat │ ├── test_ds_optzeros.txt │ ├── test_dsdemo3.mat │ ├── test_logsmooth.mat │ ├── test_peak_snr.mat │ ├── test_pulse.mat │ ├── test_pulse.txt │ ├── test_simulateDSM.mat │ ├── test_simulateDSM.txt │ ├── test_simulateSNR.m │ ├── test_snr_amp.mat │ ├── test_snr_amp.txt │ └── test_snr_amp2.mat │ ├── test_db.py │ ├── test_dbm.py │ ├── test_dbp.py │ ├── test_dbv.py │ ├── test_delay.py │ ├── test_ds_f1f2.py │ ├── test_ds_freq.py │ ├── test_ds_hann.py │ ├── test_ds_optzeros.py │ ├── test_ds_quantize.py │ ├── test_ds_synNTFobj1.py │ ├── test_dsclansNTF.py │ ├── test_dsdemo3.py │ ├── test_evalF0.py │ ├── test_evalF1.py │ ├── test_evalMixedTF.py │ ├── test_evalRPoly.py │ ├── test_evalTF.py │ ├── test_evalTFP.py │ ├── test_exampleMASH.py │ ├── test_figureMagic.py │ ├── test_impL1.py │ ├── test_infnorm.py │ ├── test_l1norm.py │ ├── test_logsmooth.py │ ├── test_lollipop.py │ ├── test_mapABCD.py │ ├── test_mapCtoD.py │ ├── test_mapQtoR.py │ ├── test_mapRtoQ.py │ ├── test_mod1.py │ ├── test_mod2.py │ ├── test_nabsH.py │ ├── test_padb.py │ ├── test_padl.py │ ├── test_padr.py │ ├── test_padt.py │ ├── test_partitionABCD.py │ ├── test_peakSNR.py │ ├── test_plotPZ.py │ ├── test_plotSpectrum.py │ ├── test_predictSNR.py │ ├── test_pulse.py │ ├── test_realizeNTF.py │ ├── test_realizeNTF_ct.py │ ├── test_realizeQNTF.py │ ├── test_rms.py │ ├── test_rmsGain.py │ ├── test_scaleABCD.py │ ├── test_simulateDSM.py │ ├── test_simulateQSNR.py │ ├── test_simulateSNR.py │ ├── test_sinc_decimate.py │ ├── test_stuffABCD.py │ ├── test_synthesizeChebyshevNTF.py │ ├── test_synthesizeNTF.py │ ├── test_synthesizeNTF0.py │ ├── test_synthesizeQNTF.py │ ├── test_thermometer.py │ ├── test_undbm.py │ ├── test_undbp.py │ ├── test_undbv.py │ ├── test_utils.py │ └── test_zinc.py ├── doc ├── Makefile ├── _static │ ├── CIFB.png │ ├── CIFB.svg │ ├── CIFF.png │ ├── CIFF.svg │ ├── CRFB.png │ ├── CRFB.svg │ ├── CRFBD.png │ ├── CRFBD.svg │ ├── CRFF.png │ ├── CRFF.svg │ ├── CRFFD.png │ ├── CRFFD.svg │ ├── DS_equivalence_DT_CT.png │ ├── DS_equivalence_DT_CT.svg │ ├── functionality.png │ ├── functionality.svg │ ├── mapCtoD.png │ ├── mapCtoD.svg │ ├── modulator_model.png │ ├── modulator_model.svg │ ├── predictSNR.png │ ├── predictSNR.svg │ ├── quantizer_model.png │ ├── quantizer_model.svg │ └── synthesizeQNTF.png ├── conf.py ├── deltasigma_theme │ ├── __init__.py │ ├── layout.html │ ├── relbar.html │ ├── sourcelink.html │ ├── static │ │ ├── deltasigma_theme.css_t │ │ └── deltasigma_theme_basic.css_t │ └── theme.conf ├── index.rst ├── make.bat └── requirements.txt ├── environment.yml ├── examples ├── MASH_example.ipynb ├── README.md ├── dsdemo1.ipynb ├── dsdemo2.ipynb ├── dsdemo3.ipynb ├── dsdemo4.ipynb ├── dsexample1.ipynb ├── dsexample2.ipynb ├── dsexample3.ipynb ├── dsexample4.ipynb └── sax.wav.b64 ├── files.csv ├── misc └── test_template.py ├── pypi_description.rst ├── requirements.txt └── setup.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | source = deltasigma 4 | include = deltasigma/* 5 | omit = 6 | */python?.?/* 7 | */lib-python/?.?/*.py 8 | */lib_pypy/_*.py 9 | */site-packages/ordereddict.py 10 | */site-packages/nose/* 11 | */unittest2/* 12 | 13 | [report] 14 | show_missing = True 15 | 16 | [html] 17 | title = python-deltasigma coverage report 18 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: Y-F-Acoustics 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.github/workflows/python-package-conda.yml: -------------------------------------------------------------------------------- 1 | name: Python Package using Conda 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | max-parallel: 5 10 | fail-fast: false 11 | matrix: 12 | os: [ubuntu-latest] 13 | python-version: ['3.7', '3.8', '3.9', '3.10'] 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python ${{ matrix.python-version }} 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: ${{ matrix.python-version }} 21 | - name: Add conda to system path 22 | run: | 23 | # $CONDA is an environment variable pointing to the root of the miniconda directory 24 | echo $CONDA/bin >> $GITHUB_PATH 25 | - name: Install dependencies 26 | run: | 27 | conda env update --file environment.yml --name base 28 | # - name: Lint with flake8 29 | # run: | 30 | # conda install flake8 31 | # # stop the build if there are Python syntax errors or undefined names 32 | # flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 33 | # # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 34 | # flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 35 | - name: Test with pytest 36 | run: | 37 | conda install pytest 38 | pytest 39 | -------------------------------------------------------------------------------- /.github/workflows/python-package.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Python package 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | os: [ubuntu-latest, windows-latest] 20 | python-version: ['3.7', '3.8', '3.9', '3.10'] 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Set up Python ${{ matrix.python-version }} 25 | uses: actions/setup-python@v2 26 | with: 27 | python-version: ${{ matrix.python-version }} 28 | - name: Install dependencies 29 | run: | 30 | pip install -r requirements.txt 31 | python -m pip install --upgrade pip 32 | python -m pip install pytest 33 | # if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 34 | # - name: Lint with flake8 35 | # run: | 36 | # # stop the build if there are Python syntax errors or undefined names 37 | # flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 38 | # # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 39 | # flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 40 | - name: Test with pytest 41 | run: | 42 | pytest 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Editor temporary/working/backup files # 2 | ######################################### 3 | .#* 4 | [#]*# 5 | *~ 6 | *$ 7 | *.bak 8 | *.kdev4 9 | .project 10 | .pydevproject 11 | #backups 12 | 13 | # Python # 14 | ################ 15 | *.py[cod] 16 | # setup.py working directory 17 | build 18 | # sphinx build directory 19 | doc/_build 20 | doc/*.html 21 | doc/_static 22 | # setup.py dist directory 23 | dist 24 | # Egg metadata 25 | *.egg-info 26 | # Egg 27 | *.egg 28 | # Installer logs 29 | pip-log.txt 30 | 31 | .ipynb_checkpoints 32 | 33 | # Compiled source # 34 | ################### 35 | *.a 36 | *.com 37 | *.class 38 | *.dll 39 | *.exe 40 | *.o 41 | *.so 42 | 43 | # Unit test / coverage reports # 44 | ################################ 45 | .coverage 46 | .tox 47 | nosetests.xml 48 | 49 | # OS generated cruft # 50 | ###################### 51 | .directory 52 | .gdb_history 53 | .DS_Store? 54 | ehthumbs.db 55 | Icon? 56 | Thumbs.db 57 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - 3.7 4 | - 3.8 5 | - 3.9 6 | # - 3.10 7 | # no virtualenv 8 | #virtualenv: 9 | # system_site_packages: false 10 | 11 | # Setup anaconda 12 | before_install: 13 | # we need blas.h 14 | - sudo apt-get update 15 | - sudo apt-get install -qq libblas-dev 16 | - if [ ${TRAVIS_PYTHON_VERSION:0:1} == "2" ]; then wget http://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh -O miniconda.sh; else wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh; fi 17 | - chmod +x miniconda.sh 18 | - ./miniconda.sh -b 19 | - if [ ${TRAVIS_PYTHON_VERSION:0:1} == "2" ]; then export PATH=/home/travis/miniconda/bin:$PATH; else export PATH=/home/travis/miniconda3/bin:$PATH; fi 20 | - conda update --yes conda 21 | 22 | # Install packages 23 | install: 24 | - conda create --quiet --yes -n buildenv python=$TRAVIS_PYTHON_VERSION 25 | - source activate buildenv 26 | - conda install --yes numpy scipy matplotlib cython nose setuptools coverage 27 | - pip install python-coveralls 28 | - python setup.py install 29 | 30 | # Run the tests 31 | script: nosetests --with-coverage --cover-package=deltasigma deltasigma 32 | 33 | # Calculate coverage 34 | after_success: 35 | - coveralls 36 | 37 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include deltasigma *.pyx *.px[di] 2 | -------------------------------------------------------------------------------- /ROADMAP.md: -------------------------------------------------------------------------------- 1 | ## Versions 2 | 3 | The feature support, split by release, is expected as follows: 4 | 5 | **V. 0.1** Support for all base band Delta Sigma topologies. Continuous time and discrete time. 6 | 7 | **V. 0.2** Support for Quadrature modulators. 8 | 9 | **V. 0.4** LC topologies. 10 | 11 | **V. 0.3** HBF and PIS set calculation. 12 | 13 | ## Porting 14 | 15 | The conversion will be performed according to the following steps: 16 | 17 | 1. **MATLAB/Python conversion** 18 | 1. Convert the M-files to Python, whenever possible, to have several Python 19 | modules providing a 1:1 replacement of the original MATLAB functions. 20 | 1. Whenever possible keep the exact function signatures, return values and 21 | default parameters. 22 | 1. Have a working unit test developed at the same time as each function. 23 | 1. Have documentation developed at the same time as each function. 24 | 1. Do not address the C Matlab EXtension (C MEX) files at this stage. 25 | 26 | 2. **C MEX / Cython conversion and other Cython files** 27 | 2. For those modules which need to be implemented in C as a Cython extension, 28 | look into a possible Cython implementation. 29 | 30 | 3. Have fun. 31 | -------------------------------------------------------------------------------- /delsig/DSToolbox.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/delsig/DSToolbox.pdf -------------------------------------------------------------------------------- /delsig/ESLselect.m: -------------------------------------------------------------------------------- 1 | function sv = ESLselect(v,sy,dw,df) 2 | %sv = ESLselect(v,sy,dw,df) Select the elements of a multi-element 3 | %DAC to minimize the selection error, subject to the constraint that 4 | %the nominal DAC output is v, i.e. v = sv'*dw. 5 | %df is a vector of dac error factors. de is defined s.t. df'*de = 0. 6 | %Assume that the preferred usage order is that given by dw. 7 | 8 | % Go through sv possibilities one by one, until one which meets the 9 | % v = sv'*dw constraint is found. 10 | 11 | if nargin<4 12 | df = ones(length(sy),1); 13 | if nargin<3 14 | dw = ones(length(sy),1); 15 | end 16 | end 17 | if v<0 | v>sum(dw) 18 | error('v argument is invalid (too large or too small)'); 19 | end 20 | 21 | n = length(dw); 22 | sv = zeros(n,1); 23 | if v==0; return; end; 24 | 25 | [junk possibilities] = sort(-sy); %Determine the element priority 26 | 27 | % Code to speed up selection in the usual case where all 28 | % DAC elements are weighted at one. Suggested by J. A. Cherry, 5-Mar-97 29 | if dw==ones(n,1); 30 | sv(possibilities(1:v)) = ones(1,v); 31 | return; 32 | end; 33 | 34 | i = 1; % Selection level 35 | pointer = 1; % Array of pointers to selected elements 36 | selected = []; % Selected elements 37 | while 1 38 | while pointer(i)>n; 39 | % backtrack 40 | i = i-1; 41 | if i==0 42 | break; %failure! 43 | end 44 | pointer(i) = pointer(i)+1; 45 | selected = selected(1:i); 46 | end 47 | selected(i) = possibilities(pointer(i)); 48 | dv = sum(dw(selected)); 49 | if dv==v 50 | break; %success! 51 | elseif dv3 & nargout==2) 7 | op = o + k*(o+c'*n); 8 | end 9 | -------------------------------------------------------------------------------- /delsig/PosInvSet/dsisPlot.m: -------------------------------------------------------------------------------- 1 | function dsisPlot(dbg,itn,order,x,s,e,ns,out) 2 | % Show some pretty pictures 3 | if dbg==0 4 | return; 5 | elseif dbg==2 6 | fprintf('Iteration %d: %d/%d image vertices outside\n',itn, sum(out),size(ns,2)); 7 | return 8 | end 9 | 10 | if itn>0 11 | str = sprintf('Iteration %d: %d/%d image points outside',itn, sum(out), size(ns,2)); 12 | else 13 | str = sprintf('Final object: %d vertices and %d edges', size(s,2), size(e,2)); 14 | end 15 | clf; 16 | 17 | if order == 2 18 | dotplot(x); 19 | hold on; grid; 20 | polyplot(s,'k'); 21 | dotplot(ns,'ko'); 22 | dotplot(ns(:,logical(out)),'rs'); 23 | title(str); 24 | drawnow; 25 | elseif order >= 3 26 | dotplot(x); 27 | edgeplot(e,s); 28 | dotplot(ns,'+'); 29 | dotplot(ns(:,logical(out)),'rs'); 30 | subplot(222); 31 | title(str); 32 | drawnow; 33 | end 34 | -------------------------------------------------------------------------------- /delsig/PosInvSet/dsistest.m: -------------------------------------------------------------------------------- 1 | % parameters which may be defaulted: u, order, dbg, expFactor 2 | if exist('u')~=1, u = 1/pi; end 3 | if exist('order')~=1, order = 2; end 4 | if exist('dbg')~=1, dbg = 1; end 5 | if exist('expFactor')~=1 expFactor=0.01; end 6 | if exist('nlev')~=1, nlev = 2; end 7 | if exist('qhullArgA')~=1, qhullArgA=0.999; end 8 | if exist('qhullArgC')~=1, qhullArgC=.001; end 9 | 10 | figure(1); 11 | if order==2 12 | mod = mod2; 13 | ABCD = mod.ABCD; 14 | t = cputime; 15 | [s e n o] = findPIS(u,ABCD,nlev, ... 16 | [dbg NaN expFactor NaN NaN qhullArgA qhullArgC]); 17 | t = cputime - t 18 | else 19 | H = synthesizeNTF(order); 20 | [a,g,b,c] = realizeNTF(H); 21 | ABCD = stuffABCD(a,g,b,c); 22 | t = cputime; 23 | [s e n o] = findPIS(u,ABCD,nlev, ... 24 | [dbg NaN expFactor NaN NaN qhullArgA qhullArgC]); 25 | t = cputime - t 26 | end 27 | 28 | figure(2); 29 | clf; 30 | if isempty(n) 31 | fprintf('No positively invariant set found.\n'); 32 | else 33 | N=10000; skip=100; 34 | if length(u)==1 35 | uu = u(ones(1,N+skip)); 36 | else 37 | uu = uvar(u,N+skip); 38 | end 39 | [junk x] = simulateDSM(uu,ABCD,nlev); 40 | x = x(:,1+skip:N+skip); 41 | 42 | ns = dsmap(u,ABCD,nlev,s,e); 43 | out = outsideConvex(ns,n,o); 44 | dsisPlot(1,0,order,x,s,e,ns,out); 45 | if(order==3) 46 | subplot(222); 47 | view(20,20); 48 | end; 49 | 50 | fprintf('%d points from the %d simulated states are outside.\n', sum(outsideConvex(x,n,o)),N); 51 | fprintf('%d image points are outside.\n', sum(out)); 52 | fprintf('The returned object has %d vertices, %d edges and %d faces.\n', ... 53 | size(s,2),size(e,2),size(n,2)); 54 | %fprintf('order=%d, u=%f, expFactor=%f\n', order, u, expFactor ); 55 | end 56 | -------------------------------------------------------------------------------- /delsig/PosInvSet/dssplit2d.m: -------------------------------------------------------------------------------- 1 | function [pplus, eplus, pminus, eminus] = dssplit2d(u,ABCD,p) 2 | %function [pplus, eplus, pminus, eminus] = dssplit2d(u,ABCD,p) 3 | %Split a convex polygon p into "plus" and "minus" polygons. 4 | % C * pplus + D1*u >=0, C * pminus + D1*u <=0. 5 | %p is given as a sequential list of vertices 6 | %with the first vertex replicated at the end of the list. 7 | %ABCD describes the modulator structure, 8 | %and u is the modulator input. 9 | %Limitation: D1 must be zero if u is a range. 10 | 11 | n = size(ABCD,1)-1; 12 | C = ABCD(n+1, 1:n); 13 | D1= ABCD(n+1, n+1); % D2=ABCD(n+1,n+2) must be zero 14 | N = size(p,2); 15 | if length(u)==1 16 | D1u = D1*u; 17 | y = C*p + D1u(ones(1,N)); 18 | else 19 | if D1 ~= 0 20 | fprintf('%s: Error. D1 must be zero when u is a range.\n'); 21 | return; 22 | else 23 | y = C*p; 24 | end 25 | end 26 | 27 | sign1 = sgn(y(1)); 28 | i = find( sgn(y) ~= sign1 ); 29 | i1 = i(1); % First change of sign. 30 | pa = dscut( p(:,i1-1),y(i1-1), p(:,i1),y(i1) ); 31 | i2 = i(length(i)); % Second change of sign. 32 | pb = dscut( p(:,i2),y(i2), p(:,i2+1),y(i2+1) ); 33 | if sign1 > 0 34 | pminus = [pa p(:,i) pb pa ]; 35 | pplus = [p(:,1:i1-1) pa pb p(:,i2+1:N)]; 36 | else 37 | pplus = [pa p(:,i) pb pa ]; 38 | pminus = [p(:,1:i1-1) pa pb p(:,i2+1:N)]; 39 | end 40 | ne = size(pplus,2); 41 | eplus = [1:ne; [2:ne] 1]; 42 | ne = size(pminus,2); 43 | eminus = [1:ne; [2:ne] 1]; 44 | -------------------------------------------------------------------------------- /delsig/PosInvSet/edgeplot.m: -------------------------------------------------------------------------------- 1 | function edgeplot(e,s,fmt) 2 | %function edgeplot(e,s,fmt) Plot edges e with format fmt 3 | if nargin < 3 4 | fmt = '-'; 5 | end 6 | if size(s,1) == 2 7 | hold on; grid on; 8 | % Assume that the s points are in order. 9 | plot([s(1,:) s(1,1)], [s(2,:) s(2,1)], fmt); 10 | elseif size(s,1) == 3 11 | tbl = [ 1 1 2; 4 1 3; 3 2 3; 2 9 9 ]; 12 | for p=1:3 13 | subplot(2,2,tbl(p,1)) 14 | hold on; grid on; 15 | x = tbl(p,2); y = tbl(p,3); 16 | xlabel(['x' num2str(x)]); ylabel(['x' num2str(y)]); 17 | for i=1:size(e,2) 18 | p1 = s(:,e(1,i)); p2 = s(:,e(2,i)); 19 | plot([p1(x) p2(x)], [p1(y) p2(y)], fmt); 20 | end 21 | end 22 | subplot(2,2,tbl(4,1)); 23 | hold on; grid on; 24 | xlabel('x1'); ylabel('x2'); zlabel('x3'); 25 | for i=1:size(e,2) 26 | p1 = s(:,e(1,i)); p2 = s(:,e(2,i)); 27 | plot3([p1(1) p2(1)], [p1(2) p2(2)], [p1(3) p2(3)], fmt); 28 | end 29 | elseif size(s,1) == 4 30 | tbl = [ 1 1 2 3; 2 1 2 4; 3 1 3 4; 4 2 3 4 ]; 31 | for p=1:4 32 | subplot(2,2,tbl(p,1)) 33 | hold on; grid on; 34 | x = tbl(p,2); y = tbl(p,3); z = tbl(p,4); 35 | xlabel(['x' num2str(x)]); ylabel(['x' num2str(y)]); zlabel(['x' num2str(z)]); 36 | for i=1:size(e,2) 37 | p1 = s(:,e(1,i)); p2 = s(:,e(2,i)); 38 | plot3([p1(x) p2(x)], [p1(y) p2(y)], [p1(z) p2(z)], fmt); 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /delsig/PosInvSet/leftof.m: -------------------------------------------------------------------------------- 1 | function y=leftof(p,a,b) 2 | %function y=leftof(p,a,b) 3 | %Return 1 if the point p is to the left of the line ab. 4 | %For a n x 2 list of points p, return a vector of results. 5 | % 6 | % Author: Richard Schreier, Oregon State University. 7 | 8 | %Translate to the origin and do the check 9 | p = p - a(ones(1,size(p,1)),:); 10 | b = b-a; 11 | y= b(1)*p(:,2) > b(2)*p(:,1); 12 | -------------------------------------------------------------------------------- /delsig/PosInvSet/outconvex2d.m: -------------------------------------------------------------------------------- 1 | function out = outconvex2d(x,p) 2 | %function out = outconvex2d(x,p) 3 | %Test if each of the x points are inside the convex polygon p, 4 | %and return the number of inequalities failed by each point. 5 | %p is a 2xn counter-clockwise list of vertices, 6 | %with the first vertex duplicated. 7 | n = size(p,2); 8 | 9 | % form A,B such that internal points satisfy Ax <= B 10 | A = [ p(2,2:n) - p(2,1:n-1); 11 | p(1,1:n-1) - p(1,2:n)]'; 12 | B = zeros(n-1,1); 13 | for i=1:n-1 14 | B(i) = A(i,:)*p(:,i); 15 | end 16 | 17 | out = sum( A*x > B(:,ones(1,size(x,2))) ); 18 | -------------------------------------------------------------------------------- /delsig/PosInvSet/outsideConvex.m: -------------------------------------------------------------------------------- 1 | function i=outsideConvex(x,n,o,tol) 2 | % function i=outsideConvex(x,n,o,tol<0>). Determine which points are outside 3 | % the convex object described by n'*x+o<=0. Positive tol reduces the number 4 | % of outside points. 5 | if nargin<4 6 | tol=0; 7 | end 8 | if( size(x,2)*size(n,2) < 1e5 ) 9 | i = sign(sum(n'*x + o(ones(size(x,2),1),:)' >tol)); 10 | else % Matrices are too big. Break into chunks 11 | chunk = round(1e5/size(n,2)); 12 | i = zeros(1,size(x,2)); 13 | for j=1:chunk:size(x,2) 14 | j2 = min(j+chunk-1,size(x,2)); 15 | i(j:j2) = sign(sum(n'*x(:,j:j2) + o(ones(j2-j+1,1),:)' >tol)); 16 | end 17 | end 18 | 19 | -------------------------------------------------------------------------------- /delsig/PosInvSet/polyplot.m: -------------------------------------------------------------------------------- 1 | function h = polyplot(p,fmt) 2 | %function polyplot(p,fmt) 3 | %Plot a polygon given by the point list p, with format fmt 4 | if nargin < 2 5 | fmt = '-'; 6 | end 7 | n = size(p,2); 8 | if p(:,n) == p(:,1) 9 | h = plot( p(1,:), p(2,:), fmt ); 10 | else 11 | h = plot( [p(1,:) p(1,1)], [p(2,:) p(2,1)], fmt ); 12 | end 13 | -------------------------------------------------------------------------------- /delsig/PosInvSet/qhull.m: -------------------------------------------------------------------------------- 1 | function [vertices, edges, normals, offsets] = qhull(points,str) 2 | % function [V E N O] = qhull(P,str): Convex hull finder based on qhull 3 | % P is an nxm list of m n-dimensional points. 4 | % V is the vertices of the hull. 5 | % E is the edges of the hull: pairs of indices into the V array. 6 | % N is the normals for the facets and O is their offsets. 7 | % Points inside the hull are characterized by x'*N + O < 0 8 | % 9 | % str is the argument string to qhull, the default is 10 | % 'qhull(mex) Qcx C0.001 A0.999'. 11 | % 12 | % See the documentation on qhull for more information. 13 | % 14 | % NOTE: In 2D, qhull() modifies those points in P that are vertices of 15 | % merged facets. 16 | -------------------------------------------------------------------------------- /delsig/PosInvSet/qhull/COPYING.txt: -------------------------------------------------------------------------------- 1 | Qhull, Copyright (c) 1993-1995 2 | 3 | The National Science and Technology Research Center for 4 | Computation and Visualization of Geometric Structures 5 | (The Geometry Center) 6 | University of Minnesota 7 | 1300 South Second Street 8 | Minneapolis, MN 55454 USA 9 | 10 | email: qhull@geom.umn.edu 11 | 12 | This software is copyrighted as noted above. It is free software and 13 | may be obtained via anonymous ftp from geom.umn.edu. It may be freely 14 | copied, modified, and redistributed under the following conditions: 15 | 16 | 1. All copyright notices must remain intact in all files. 17 | 18 | 2. A copy of this file (COPYING.txt) must be distributed along with any 19 | copies which you redistribute; this includes copies which you have 20 | modified, or copies of programs or other software products which 21 | include this software. 22 | 23 | 3. If you modify this software, you must include a notice giving the 24 | name of the person performing the modification, the date of 25 | modification, and the reason for such modification. 26 | 27 | 4. When distributing modified versions of this software, or other 28 | software products which include this software, you must provide 29 | notice that the original source code may be obtained as noted 30 | above. 31 | 32 | 5. There is no warranty or other guarantee of fitness for this 33 | software, it is provided solely "as is". Bug reports or fixes may 34 | be sent to qhull_bug@geom.umn.edu; the authors may or may not act 35 | on them as they desire. 36 | 37 | -------------------------------------------------------------------------------- /delsig/PosInvSet/qhull/MEXChanges.txt: -------------------------------------------------------------------------------- 1 | The following files were changed to create a MATLAB mex interface 2 | 3 | 1) Add mex.c 4 | This file contains the code for my interface. 5 | 6 | 2) Changed Makefile 7 | Added commands for compilation on an HP 9000/series 700. 8 | Made the MEX-file the default makefile target. 9 | 10 | 3) Changed merge.c & merge.h 11 | These were changed according to my desire for facet merging to 12 | correct the vertices. Code for this in 3 and higher dimensions 13 | does not exist. These changes are not necessary for the MEX interface. 14 | 15 | 4) set qh_RANDOMtype to 4 in user.h. 16 | 17 | Richard Schreier 18 | Dec 1995 19 | -------------------------------------------------------------------------------- /delsig/PosInvSet/sgn.m: -------------------------------------------------------------------------------- 1 | function y=sgn(x) 2 | %y=sgn(x) The signum function. Unlike sign(), sgn(0)=1. 3 | y=sign(sign(x)+.5); 4 | -------------------------------------------------------------------------------- /delsig/PosInvSet/uvar.m: -------------------------------------------------------------------------------- 1 | function un=uvar(u,N); 2 | %un = uvar(u,N); Compute a bounded sequence that has 90% of its 3 | %values at the extremes. 4 | 5 | u1 = u(1); u2=u(2); 6 | un = u1(ones(1,N)); 7 | r = rand(1,N); 8 | ri2 = r > 0.55; 9 | ri1 = r > 0.45 & ~ri2; 10 | un(ri1) = u1 + (u2-u1)*10*(r(ri1)-.45); 11 | un(ri2) = u2(ones(1,sum(ri2))); 12 | -------------------------------------------------------------------------------- /delsig/Readme.m: -------------------------------------------------------------------------------- 1 | % Delta-Sigma Toolbox for Matlab 2 | % Copyright (c) 1993-2016 R. Schreier 3 | % 4 | % Required Toolboxes: 5 | % Signal-Processing Toolbox 6 | % Control Toolbox 7 | % A few non-critical functions also use the Optimization Toolbox. 8 | % 9 | -------------------------------------------------------------------------------- /delsig/SIunits.m: -------------------------------------------------------------------------------- 1 | function [factor,prefix] = SIunits(x) 2 | % [factor,prefix] = SIunits(x) 3 | % The factors and suffixes supported are: 4 | % 1e-3 m milli 1e3 k kilo 5 | % 1e-6 u micro 1e6 M mega 6 | % 1e-9 n nano 1e9 G giga 7 | % 1e-12 p pico 1e12 T tera 8 | % 1e-15 f femto 1e15 P peta 9 | % 1e-18 a atto 1e18 E exa 10 | % 1e-21 z zepto 1e21 Z zeta 11 | % 1e-24 y yocto 1e24 Y yotta 12 | prefixes_n = {'m';'u';'n';'p';'f';'a';'z';'y'}; 13 | prefixes_p = {'k';'M';'G';'T';'P';'E';'Z';'Y'}; 14 | if x~=0 15 | p = floor( log10( abs(x) ) / 3 + eps); 16 | else 17 | p = 0; 18 | end 19 | if p>0 20 | p = min(p,length(prefixes_p)); 21 | prefix = prefixes_p{p}; 22 | factor = 10^(3*p); 23 | elseif p<0 24 | p = min(-p,length(prefixes_n)); 25 | prefix = prefixes_n{p}; 26 | factor = 10^(-3*p); 27 | else 28 | prefix = ''; 29 | factor = 1; 30 | end 31 | 32 | -------------------------------------------------------------------------------- /delsig/addPIS.m: -------------------------------------------------------------------------------- 1 | function addPIS 2 | % Add the PosInvSet subdirectory of the toolbox to the current path 3 | tb_dir = which('dsdemo5'); 4 | slash = find(tb_dir==filesep); 5 | if isempty(slash) 6 | tb_dir = ''; 7 | else 8 | tb_dir = tb_dir(1:slash(end)); 9 | end 10 | addpath([tb_dir 'PosInvSet']); 11 | -------------------------------------------------------------------------------- /delsig/axisLabels.m: -------------------------------------------------------------------------------- 1 | function s = axisLabels(range,incr) 2 | %function s = axisLabels(range,incr) 3 | range(abs(range)<1e-6) = 0; 4 | s = cell(1,length(range)); 5 | if length(incr) == 2 6 | first = incr(2); 7 | incr = incr(1); 8 | else 9 | first = 1; 10 | end 11 | for i=first:incr:length(range) 12 | s{i}=sprintf('%g',range(i)); 13 | end 14 | -------------------------------------------------------------------------------- /delsig/bplogsmooth.m: -------------------------------------------------------------------------------- 1 | function [f,p] = bplogsmooth(X,tbin,f0) 2 | % Smooth the fft, X, and convert it to dB. 3 | % Use 8 bins from the bin corresponding to f0 to tbin and again as far. 4 | % Thereafter increase bin sizes by a factor of 1.1, staying less than 2^10. 5 | % For tbin, group the bins together. TBIN IS ASSUMED TO BE IN THE UPPER SIDEBAND! 6 | % Use this for nice double-sided log-log plots 7 | N=length(X); 8 | n=8; 9 | 10 | bin0 = round(f0*N); 11 | bin1 = rem(tbin-bin0,n)+bin0; 12 | bind = bin1-bin0; 13 | usb1 = [bin1:n:tbin tbin+3:8:tbin+bind ]; 14 | m = usb1(length(usb1))+n; 15 | while m+n/2 < N/2 16 | usb1 = [usb1 m]; 17 | n = min(n*1.1,2^10); 18 | m = m+n; 19 | end 20 | usb2 = [usb1(2:length(usb1))-1 N/2]; 21 | 22 | n=8; 23 | lsb2 = [bin1:-n:bin1-2*bind]-1; 24 | m = lsb2(length(lsb2))-n; 25 | while m-n/2 > 1 26 | lsb2 = [lsb2 m]; 27 | n = min(n*1.1,2^10); 28 | m = m-n; 29 | end 30 | lsb1 = [lsb2(2:length(lsb2))+1 1]; 31 | 32 | startbin=[lsb1(length(lsb1):-1:1) usb1]; 33 | stopbin=[lsb2(length(lsb2):-1:1) usb2]; 34 | 35 | f = ((startbin+stopbin)/2 -1)/N -f0; 36 | p = zeros(size(f)); 37 | for i=1:length(f) 38 | p(i) = dbp(norm(X(startbin(i):stopbin(i)))^2 / ... 39 | (stopbin(i)-startbin(i)+1)); 40 | end 41 | -------------------------------------------------------------------------------- /delsig/bquantize.m: -------------------------------------------------------------------------------- 1 | function y = bquantize(x,nsd,abstol,reltol) 2 | %y = bquantize(x,nsd=3,abstol=eps,reltol=10*eps) 3 | % Bidirectionally quantize a n by 1 vector x to nsd signed digits, 4 | % Terminate early if the error is less than the specified tolerances. 5 | % y is a structure array with the following fields: 6 | % y(i).val is the quantized value in floating-point form 7 | % y(i).csd is a 2-by-nsd (or less) matrix containing 8 | % the powers of two (first row) and their signs (second row). 9 | % See also bunquantize.m. 10 | 11 | % Handle the input arguments 12 | parameters = {'x' 'nsd' 'abstol' 'reltol'}; 13 | defaults = { NaN 3 eps 10*eps }; 14 | for i=1:length(defaults) 15 | parameter = char(parameters(i)); 16 | if i>nargin | ( eval(['isnumeric(' parameter ') ']) & ... 17 | eval(['any(isnan(' parameter ')) | isempty(' parameter ') ']) ) 18 | eval([parameter '=defaults{i};']) 19 | end 20 | end 21 | 22 | n = length(x); 23 | q = zeros(2*n,nsd); 24 | y = struct('val',cell(1,n),'csd',cell(1,n)); 25 | offset = -log2(0.75); 26 | 27 | for i = 1:n 28 | xp = x(i); 29 | y(i).val = 0; 30 | for j = 1:nsd 31 | error = abs(y(i).val-x(i)); 32 | if error <= abstol | error <= abs(x(i))*reltol 33 | break; 34 | end 35 | p = floor( log2(abs(xp)) + offset ); 36 | p2 = pow2( p ); 37 | sx = sign(xp); 38 | xp = xp- sx*p2; 39 | y(i).val = y(i).val + sx*p2; 40 | y(i).csd(1:2,j) = [p;sx]; 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /delsig/bunquantize.m: -------------------------------------------------------------------------------- 1 | function y = bunquantize(q) 2 | % Calculate the value corresponding to a bidirectionally quantized quantity. 3 | % q is a 2n by m matrix containing the powers of 2 and their signs for each 4 | % quantized value. 5 | % See also bquantize.m. 6 | 7 | n = size(q,1)/2; 8 | y = zeros(n,1); 9 | signs = 2:2:2*n; 10 | powers = signs - 1; 11 | for i = 1:size(q,2); 12 | y = y + 2.^q(powers,i).*q(signs,i); 13 | end 14 | -------------------------------------------------------------------------------- /delsig/calculateQTF.m: -------------------------------------------------------------------------------- 1 | function [ntf,stf,intf,istf] = calculateQTF(ABCDr) % [ntf stf intf istf] = calculateQTF(ABCDr) % Calculate the noise and signal transfer functions for a quadrature modulator [A B C D] = partitionABCD(ABCDr,4); %Construct an ABCD description of the closed-loop system sys = ss(A+B(:,3:4)*C, B, C, [D(:,1:2) eye(2)], 1); %Calculate the 2x4 matrix of transfer functions tfs = tf(sys); %Reduce these to NTF, STF, INTF and ISTF if any( tfs(1,3).den{1} ~= tfs(2,4).den{1} ) error('TF Denominator mismatch. Location 1'); end ntf_x = tf(0.5*(tfs(1,3).num{1} + tfs(2,4).num{1}), tfs(1,3).den{1}, 1); intf_x = tf(0.5*(tfs(1,3).num{1} - tfs(2,4).num{1}), tfs(1,3).den{1}, 1); if any( tfs(1,4).den{1} ~= tfs(2,3).den{1} ) error('TF Denominator mismatch. Location 2'); end ntf_y = tf(0.5*(tfs(2,3).num{1} - tfs(1,4).num{1}), tfs(2,3).den{1}, 1); intf_y = tf(0.5*(tfs(2,3).num{1} + tfs(1,4).num{1}), tfs(2,3).den{1}, 1); if any( ntf_x.den{1} ~= ntf_y.den{1} ) error('TF Denominator mismatch. Location 3'); end if any( tfs(1,1).den{1} ~= tfs(2,2).den{1} ) error('TF Denominator mismatch. Location 4'); end stf_x = tf(0.5*(tfs(1,1).num{1} + tfs(2,2).num{1}), tfs(1,1).den{1}, 1); istf_x = tf(0.5*(tfs(1,1).num{1} - tfs(2,2).num{1}), tfs(1,1).den{1}, 1); if any( tfs(1,2).den{1} ~= tfs(2,1).den{1} ) error('TF Denominator mismatch. Location 5'); end stf_y = tf(0.5*(tfs(2,1).num{1} - tfs(1,2).num{1}), tfs(2,1).den{1}, 1); istf_y = tf(0.5*(tfs(2,1).num{1} + tfs(1,2).num{1}), tfs(2,1).den{1}, 1); if any( stf_x.den{1} ~= stf_y.den{1} ) error('TF Denominator mismatch. Location 6'); end warning('off'); % suppress warnings about complex TFs ntf = cancelPZ( zpk( tf(ntf_x.num{1} + 1i* ntf_y.num{1}, ntf_x.den{1}, 1) ) ); intf = cancelPZ( zpk( tf(intf_x.num{1} + 1i* intf_y.num{1}, intf_x.den{1}, 1) ) ); stf = cancelPZ( zpk( tf(stf_x.num{1} + 1i* stf_y.num{1}, ntf_x.den{1}, 1) ) ); istf = cancelPZ( zpk( tf(istf_x.num{1} + 1i* istf_y.num{1}, intf_x.den{1}, 1) ) ); warning('on'); return -------------------------------------------------------------------------------- /delsig/calculateSNR.m: -------------------------------------------------------------------------------- 1 | function snr = calculateSNR(hwfft,f,nsig) 2 | % snr = calculateSNR(hwfft,f,nsig=1) Estimate the signal-to-noise ratio, 3 | % given the in-band bins of a (Hann-windowed) fft and 4 | % the location of the input signal (f>0). 5 | % For nsig=1, the input tone is contained in hwfft(f:f+2); 6 | % this range is appropriate for a Hann-windowed fft. 7 | % Each increment in nsig adds a bin to either side. 8 | % The SNR is expressed in dB. 9 | if nargin<3 10 | nsig = 1; 11 | end 12 | signalBins = [f-nsig+1:f+nsig+1]; 13 | signalBins = signalBins(signalBins>0); 14 | signalBins = signalBins(signalBins<=length(hwfft)); 15 | s = norm(hwfft(signalBins)); % *4/(N*sqrt(3)) for true rms value; 16 | noiseBins = 1:length(hwfft); 17 | noiseBins(signalBins) = []; 18 | n = norm(hwfft(noiseBins)); 19 | if n==0 20 | snr = Inf; 21 | else 22 | snr = dbv(s/n); 23 | end 24 | -------------------------------------------------------------------------------- /delsig/calculateTF.m: -------------------------------------------------------------------------------- 1 | function [ntf,stf] = calculateTF(ABCD,k) 2 | % [ntf,stf] = calculateTF(ABCD,k=1) 3 | % Calculate the NTF and STF of a delta-sigma modulator whose loop filter 4 | % is described by the ABCD matrix, assuming a quantizer gain of k. 5 | % The NTF and STF are zpk objects. 6 | if nargin < 2 | isnan(k) 7 | k = 1; 8 | end 9 | nq = length(k); 10 | n = size(ABCD,1) - nq; 11 | nu = size(ABCD,2) - size(ABCD,1); 12 | [A,B,C,D] = partitionABCD(ABCD,nu+nq); 13 | B1 = B(:,1:nu); 14 | B2 = B(:,nu+1:end); 15 | D1 = D(:,1:nu); 16 | if any(any( D(:,nu+1:end) ~= 0 )) 17 | error('D2 must be zero'); 18 | end 19 | K = diag(k); 20 | % Find the noise transfer function by forming the closed-loop 21 | % system (sys_cl) in state-space form. 22 | Acl = A + B2*K*C; 23 | Bcl = [B1 + B2*K*D1, B2]; 24 | Ccl = K*C; 25 | Dcl = [K*D1 eye(nq)]; 26 | vn = sscanf(version,'%d'); 27 | if vn>6 | all(imag(ABCD)==0) % real modulator or recent version of MATLAB 28 | sys_cl = ss(Acl,Bcl,Ccl,Dcl,1); 29 | tfs = zpk(sys_cl); 30 | tol = min(1e-3,max(1e-6,eps^(1/(size(ABCD,1))))); 31 | mtfs = minreal(tfs,tol); 32 | stf = mtfs(:,1:nu); 33 | ntf = mtfs(:,nu+1:nu+nq); 34 | else % quadrature modulator and old version of MATLAB 35 | p = eig(Acl); 36 | ntfz = eig(A); 37 | ntf = setPolesAndZeros(ntfz,p,1); 38 | if nargout>1 39 | fprintf(1,'Sorry. calculateTF cannot compute the STF for a complex modulator with this version of matlab.\n'); 40 | end 41 | stf=[]; 42 | end 43 | return 44 | 45 | % Use a loophole to set complex poles and zeros in zpk objects 46 | function ztf = setPolesAndZeros(z,p,k) 47 | tol = 3e-5; % tolerance for pole-zero cancellation 48 | Z = zpk(0,[],1,1); 49 | ztf = zpk([],[],k,1); 50 | for i = 1:length(p) 51 | match = abs(p(i)-z)nargin | ( eval(['isnumeric(' parameter ') ']) & ... 10 | eval(['any(isnan(' parameter ')) | isempty(' parameter ') ']) ) 11 | eval([parameter '=defaults{i};']) 12 | end 13 | end 14 | 15 | children = get(gcf,'children'); 16 | children = children(:)'; 17 | for child=children 18 | type = get(child,'type'); 19 | if type=='axes' 20 | set(child,'fontsize',fontsize) 21 | axisChildren = get(child,{'children' 'xlabel' 'ylabel' 'title'}); 22 | axisChildren = [axisChildren{1}' axisChildren{2:4}]; 23 | for axisChild=axisChildren 24 | type = get(axisChild,'type'); 25 | switch type 26 | case 'line' 27 | set(axisChild,'linewidth',linewidth); 28 | set(axisChild,'markersize',markersize); 29 | case 'text' 30 | set(axisChild,'fontsize',fontsize); 31 | otherwise 32 | ; 33 | end 34 | end 35 | else 36 | fprintf(1,'type is %s (not ''axes'')\n',type); 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /delsig/circ_smooth.m: -------------------------------------------------------------------------------- 1 | function y = circ_smooth(x,n) nx = length(x); w = ds_hann(n)/(n/2); xw = conv(x,w); y = circshift([ xw(n:nx) xw(1:n-1)+xw(nx+1:end)],[0 n/2-1]); -------------------------------------------------------------------------------- /delsig/clans.m: -------------------------------------------------------------------------------- 1 | function NTF=clans(order,OSR,Q,rmax,opt) %NTF = clans(order=4,OSR=64,Q=5,rmax=0.95,opt=0) Optimal NTF design %for a multi-bit modulator. %CLANS = "closed-loop analysis of noise-shapers," %and was originally developed by J.G. Kenney and L.R. Carley. % Handle the input arguments parameters = {'order';'OSR';'Q';'rmax';'opt'}; defaults = [ 4 64 5 0.95 0 ]; for i=1:length(defaults) parameter = char(parameters(i)); if i>nargin | ( eval(['isnumeric(' parameter ') ']) & ... eval(['any(isnan(' parameter ')) | isempty(' parameter ') ']) ) eval([parameter '=defaults(i);']) end end if exist('fmincon','file')==2 % Optimization Toolbox >=6 NTF=clans6(order,OSR,Q,rmax,opt); elseif exist('constr','file')==2 % Optimization Toolbox version < 6 NTF=clans5(order,OSR,Q,rmax,opt); else error('CLANS needs the optimization toolbox.'); end -------------------------------------------------------------------------------- /delsig/clans5.m: -------------------------------------------------------------------------------- 1 | function NTF=clans5(order,OSR,Q,rmax,opt) 2 | %Version of clans for MATLAB 5 or lower 3 | 4 | % Create the initial guess 5 | NTF = synthesizeNTF(order,OSR,opt,1+Q,0); 6 | Hz = NTF.z{1}; 7 | x = zeros(1,order); 8 | odd = rem(order,2); 9 | if odd 10 | z = NTF.p{1}(1)/rmax; 11 | if any(abs(z))>1 %project poles outside rmax onto the circle 12 | z = z./abs(z); 13 | end 14 | s = (z-1)./(z+1); 15 | x(1)= sqrt(-s); 16 | end 17 | for i=odd+1:2:order 18 | z = NTF.p{1}(i:i+1)/rmax; 19 | if any(abs(z))>1 %project poles outside rmax onto the circle 20 | z = z./abs(z); 21 | end 22 | s = (z-1)./(z+1); 23 | coeffs=poly(s); 24 | wn = sqrt(coeffs(3)); 25 | zeta = coeffs(2)/(2*wn); 26 | x(i) = sqrt(zeta); 27 | x(i+1) = sqrt(wn); 28 | end 29 | 30 | % Run the optimizer 31 | x=constr('dsclansObj',x,[],[],[],[],order,OSR,Q,rmax,Hz); 32 | NTF = dsclansNTF(x,order,rmax,Hz); 33 | return 34 | 35 | -------------------------------------------------------------------------------- /delsig/clans6.m: -------------------------------------------------------------------------------- 1 | function NTF=clans6(order,OSR,Q,rmax,opt) 2 | %Version of clans for MATLAB >=6 3 | 4 | %Incorporates Marko Neitola's (U. Oulu) 2014 suggestion to square f and g 5 | 6 | % Create the initial guess 7 | NTF = synthesizeNTF(order,OSR,opt,1+Q,0); 8 | Hz = NTF.z{1}; 9 | x = zeros(1,order); 10 | odd = rem(order,2); 11 | if odd 12 | z = NTF.p{1}(1)/rmax; 13 | if any(abs(z))>1 %project poles outside rmax onto the circle 14 | z = z./abs(z); 15 | end 16 | s = (z-1)./(z+1); 17 | x(1)= sqrt(-s); 18 | end 19 | for i=odd+1:2:order 20 | z = NTF.p{1}(i:i+1)/rmax; 21 | if any(abs(z))>1 %project poles outside rmax onto the circle 22 | z = z./abs(z); 23 | end 24 | s = (z-1)./(z+1); 25 | coeffs=poly(s); 26 | wn = sqrt(coeffs(3)); 27 | zeta = coeffs(2)/(2*wn); 28 | x(i) = sqrt(zeta); 29 | x(i+1) = sqrt(wn); 30 | end 31 | 32 | % Run the optimizer 33 | options = optimset('TolX',1e-6, 'TolFun',1e-6, 'TolCon',1e-6, 'MaxIter',1000 ); 34 | options = optimset(options,'Display','off'); 35 | options = optimset(options,'Diagnostics','off'); 36 | options = optimset(options,'LargeScale','off'); 37 | options = optimset(options,'Algorithm','active-set'); 38 | x = fmincon(@(x)dsclansObj6a(x,order,OSR,Q,rmax,Hz),x, ... 39 | [],[],[],[],[],[],@(x)dsclansObj6b(x,order,OSR,Q,rmax,Hz), options ); 40 | 41 | NTF = dsclansNTF(x,order,rmax,Hz); 42 | return 43 | 44 | function f=dsclansObj6a(x,order,OSR,Q,rmax,Hz) 45 | % Objective function for clans; Optimization Toolbox version >= 6 46 | % f is the mean-square value of H over the passband 47 | H = dsclansNTF(x,order,rmax,Hz); 48 | z = exp(1i*linspace(0,pi/OSR)); 49 | f = norm(evalTF(H,z))^2; 50 | return 51 | 52 | function [g,g_eq]=dsclansObj6b(x,order,OSR,Q,rmax,Hz) 53 | % Constraint function for clans; Optimization Toolbox version >= 6 54 | % g = (||h||_1 - Q)^2 55 | H = dsclansNTF(x,order,rmax,Hz); 56 | g = (sum(abs(impulse(H,100))) -1 - Q)^2; 57 | g_eq = []; 58 | return 59 | -------------------------------------------------------------------------------- /delsig/dbm.m: -------------------------------------------------------------------------------- 1 | function y=dbm(v,R) % dbm(v,R=50) = 10*log10(v^2/R*1000) The equivalent in dBm of an rms voltage v if isempty(v) return end if nargin<2 R = 50; end y = -Inf*ones(size(v)); nonzero = v~=0; y(nonzero) = 10*log10(abs(v(nonzero).^2)/R)+30; -------------------------------------------------------------------------------- /delsig/dbp.m: -------------------------------------------------------------------------------- 1 | function y=dbp(x) 2 | % dbp(x) = 10*log10(x): the dB equivalent of the power x 3 | y = -Inf*ones(size(x)); 4 | if isempty(x) 5 | return 6 | end 7 | nonzero = x~=0; 8 | y(nonzero) = 10*log10(abs(x(nonzero))); 9 | -------------------------------------------------------------------------------- /delsig/dbv.m: -------------------------------------------------------------------------------- 1 | function y=dbv(x) 2 | % dbv(x) = 20*log10(abs(x)); the dB equivalent of the voltage x 3 | y = -Inf*ones(size(x)); 4 | if isempty(x) 5 | return 6 | end 7 | nonzero = x~=0; 8 | y(nonzero) = 20*log10(abs(x(nonzero))); 9 | -------------------------------------------------------------------------------- /delsig/delay.m: -------------------------------------------------------------------------------- 1 | function y = delay(x,n) 2 | % y = delay(x,n=1) Delay signal x by n samples 3 | if nargin < 2 4 | n = 1; 5 | end 6 | nx = length(x); 7 | if nx <= n 8 | y = zeros(size(x)); 9 | else 10 | if size(x,1) > size(x,2) 11 | y = [zeros(n,1); x(1:nx-n)]; 12 | else 13 | y = [zeros(1,n) x(1:nx-n)]; 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /delsig/demo22mash.m: -------------------------------------------------------------------------------- 1 | ABCD = [ 1 0 0 0 1 -1 0 2 | 1 1 0 0 0 -2 0 3 | 0 1 1 0 0 0 -1 4 | 0 0 1 1 0 0 -2 5 | 0 1 0 0 0 0 0 6 | 0 0 0 1 0 0 0 ]; 7 | nlev = [9 9]; 8 | [ntf stf] = calculateTF(ABCD, [1 1]); 9 | ncf1 = -ntf(2,1); % 2*(z-0.5)^2/z^4 10 | ncf2 = ntf(1,1); % (z-1)^2/z^2 11 | % stf_eff = stf(1,1)*ncf1 + stf(2,1)*ncf2; 12 | stf_eff= cancelPZ( zpk(tf(stf(1,1)*ncf1) + tf(stf(2,1)*ncf2)) ); 13 | ntf_eff = ntf(2,2)*ncf2; % (z-1)^4/z^4 14 | 15 | osr = 16; 16 | M = nlev-1; 17 | N = 2^12; 18 | f_bin = round(0.01*N); 19 | t = 0:N-1; 20 | wdw = ds_hann(N)/(M(1)*N/4); 21 | 22 | u = undbv(-3)*M(1)*sin( 2*pi*f_bin/N*t); 23 | [v xn xmax ]= simulateDSM(u,ABCD,nlev); 24 | V1 = fft(v(1,:).*wdw); 25 | sqnr1 = calculateSNR(V1(1:N/(2*osr)+1), f_bin); 26 | [freq spec1] = logsmooth(V1,f_bin); 27 | 28 | vf = ds_filt([ncf1 ncf2],v); 29 | Vf = fft(vf.*wdw); 30 | sqnr2 = calculateSNR(Vf(1:N/(2*osr)+1), f_bin); 31 | [freq spec2] = logsmooth(Vf,f_bin); 32 | 33 | figure(1); clf; 34 | h = semilogx(freq,spec1, 'b'); 35 | set(h,'LineWidth',2); 36 | hold on; 37 | h = semilogx(freq,spec2, 'm'); 38 | set(h,'LineWidth',2); 39 | msg = sprintf('@ A = %.0f dBFS\n& OSR = %d,\nSQNR1 = %.0f dB\nSQNR = %.0f dB', dbv(Vf(f_bin+1)), osr, sqnr1, sqnr2 ); 40 | h = text(0.013,0,msg, 'Vert','Top', 'FontSize',20); 41 | text(0.5,-140,sprintf('NBW = %.1E',1.5/N), 'Hor','right', 'Vert','bot'); 42 | figureMagic([1e-3 0.5],[],[],[-140 5],10,2); 43 | plot([1e-3 0.5/osr], -140*[1 1], 'k', 'LineWidth',4); 44 | xlabel('Normalized Frequency'); 45 | ylabel('dBFS/NBW'); 46 | 47 | return; 48 | 49 | figure(1); clf 50 | t_plot = 100; 51 | stairs( t(1:t_plot), u(1:t_plot), 'm'); 52 | hold on; 53 | stairs( t(1:t_plot), v(1:t_plot), 'b'); 54 | 55 | figure(2); clf 56 | window = ds_hann(N)/(N/4); 57 | V = fft(v.*window); 58 | semilogx( dbv(V(2:N/2+1)) ); 59 | grid on; 60 | 61 | -------------------------------------------------------------------------------- /delsig/demoLPandBP.m: -------------------------------------------------------------------------------- 1 | %% Lowpass and Bandpass Demonstration Script % Type cmd-shift-return to evaluate each cell in turn close all; clear LiveDemo = 1; %% 2nd-order lowpass dsm.order = 2; dsm.osr = 16; dsm.opt = 0; dsm.Hinf = 2; dsm.M = 8; % nlev = M+1 dsexample1(dsm, LiveDemo); %% 5th-order lowpass dsm.order = 5; dsexample1(dsm, LiveDemo); %% 5th-order lowpass with optimized zeros dsm.opt = 1; dsexample1(dsm, LiveDemo); %% 5th-order lowpass with optimized zeros and larger Hinf dsm.Hinf = 3; dsexample1(dsm, LiveDemo); %% 7th-order lowpass; Hinf=2 dsm.order = 7; dsm.osr = 8; dsm.opt = 1; dsm.Hinf = 2; dsm.M = 16; % nlev = M+1 dsm.Atest = -6; dsexample1(dsm, LiveDemo); %% 7th-order lowpass; Hinf=8 dsm.Hinf = 8; dsexample1(dsm, LiveDemo); %% 6th-order bandpass clear LiveDemo = 1; dsm.order = 6; dsm.osr = 16; dsm.opt = 1; dsm.Hinf = 2; dsm.M = 8; dsm.f0 = 1/6; % Normalized center frequency dsexample1(dsm, LiveDemo); -------------------------------------------------------------------------------- /delsig/designHBF.m: -------------------------------------------------------------------------------- 1 | function [f1,f2,info]=designHBF(fp,delta,debug) %function [f1,f2,info]=designHBF(fp=0.2,delta=1e-5,debug=0) %Design a half-band filter which can be realized without general multipliers. %The filter is a composition of a prototype and sub- filter. %Input % fp The normalized cutoff frequency of the filter. Due to the % symmetry imposed by a HBF, the stopband begins at 0.5-fp. % delta The absolute value of the deviation of the frequency response from % the ideal values of 1 in the passband and 0 in the stopband. % %Output % f1,f2 The coefficients of the prototype and sub-filters % and their canonical-signed digit (csd) representation. % info A vector containing the following data (only set when debug=1): % complexity The number of additions per output sample. % n1,n2 The length of the f1 and f2 vectors. % sbr The achieved stob-band attenuation (dB). % phi The scaling factor for the F2 filter. %Handle the input arguments parameters = ['fp ';'delta';'debug']; defaults = [ 0.2 1e-5 0]; for i=1:length(defaults) if i>nargin eval([parameters(i,:) '=defaults(i);']) elseif eval(['any(isnan(' parameters(i,:) ')) | isempty(' parameters(i,:) ')']) eval([parameters(i,:) '=defaults(i);']) end end % This is a wrapper function if exist('firpm','file') [f1,f2,info]=designHBF7(fp,delta,debug); else [f1,f2,info]=designHBF6(fp,delta,debug); end -------------------------------------------------------------------------------- /delsig/ds_f1f2.m: -------------------------------------------------------------------------------- 1 | function [f1,f2] = ds_f1f2(OSR,f0,complex_flag); 2 | %[f1,f2] = ds_f1f2(OSR=64,f0=0,complex_flag=0); 3 | parameters = {'OSR' 'f0' 'complex_flag'}; 4 | defaults = { 64 0 0 }; 5 | for arg_i=1:length(defaults) 6 | parameter = char(parameters(arg_i)); 7 | if arg_i>nargin | ( eval(['isnumeric(' parameter ') ']) & ... 8 | eval(['any(isnan(' parameter ')) | isempty(' parameter ') ']) ) 9 | eval([parameter '=defaults{arg_i};']) 10 | end 11 | end 12 | 13 | if complex_flag 14 | f1 = f0-0.5/OSR; 15 | f2 = f0+0.5/OSR; 16 | else 17 | if f0>0.25/OSR 18 | f1 = f0-0.25/OSR; 19 | f2 = f0+0.25/OSR; 20 | else 21 | f1 = 0; 22 | f2 = 0.5/OSR; 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /delsig/ds_filt.m: -------------------------------------------------------------------------------- 1 | function y = ds_filt(H,x) % function y = ds_filt(H,x) % H is an LxM array of zpk transfer functions % x is an MxN matrix consisting of M time sequences of length N % y is an LxN matrix consisting of L time sequences of length N L = size(H,1); M = size(H,2); if M ~= size(x,1) error('size mismatch'); end N = size(x,2); y = zeros(L,N); for i = 1:L for j = 1:M b = H(i,j).k * poly(H(i,j).z{1}); a = poly(H(i,j).p{1}); m = length(b); n = length(a); if n>m b = [zeros(1,n-m) b]; elseif nnargin | ( eval(['isnumeric(' parameter ') ']) & ... eval(['any(isnan(' parameter ')) | isempty(' parameter ') ']) ) eval([parameter '=defaults{arg_ii};']) end end if quadrature f_left = -0.5; f_special = [f0 -f0]; else f_left = 0; f_special = f0; end f = linspace(f_left,0.5,100); % Use finer spacing in the vicinity of the passband for fx = f_special f1 = max(f_left, fx-1/osr); f2 = min(0.5,fx+2/osr); f( f<=f2 & f>=f1 ) = []; f = sort( [f linspace(f1,f2)] ); end -------------------------------------------------------------------------------- /delsig/ds_hann.m: -------------------------------------------------------------------------------- 1 | function w = ds_hann(n) 2 | % function w = ds_hann(n) 3 | % A Hann window of length n. Does not smear tones located exactly in a bin. 4 | 5 | % Note: This function was formerly just "hann." Re-naming 6 | % was necessary to avoid a conflict with Mathworks's function 7 | % of the same name. 8 | w = .5*(1 - cos(2*pi*(0:n-1)/n) ); 9 | -------------------------------------------------------------------------------- /delsig/ds_orderString.m: -------------------------------------------------------------------------------- 1 | function s=ds_orderString(n,capitalize) if nargin<2 capitalize=0; end strings = { 'zeroth' 'first' 'second' 'third' 'fourth' 'fifth' 'sixth' 'seventh' 'eighth' 'nineth' 'tenth' 'twelfth' 'thirteenth'}; if n<0 | n+1>length(strings) s = sprintf('%dth',n); else s = strings{n+1}; if capitalize s(1) = s(1) + 'A'-'a'; end end -------------------------------------------------------------------------------- /delsig/ds_quantize.m: -------------------------------------------------------------------------------- 1 | function v = ds_quantize(y,n) 2 | %v = ds_quantize(y,n=2) 3 | %Quantize y to 4 | % an odd integer in [-n+1, n-1], if n is even, or 5 | % an even integer in [-n+1, n-1], if n is odd. 6 | %This definition gives the same step height for both mid-rise 7 | %and mid-tread quantizers. 8 | %n can be a column vector which specifies how to quantize the rows of y 9 | if nargin<2 10 | n=2; 11 | end 12 | if length(n)==1 13 | n = n*ones(size(y)); 14 | elseif size(n,1)==size(y,1) 15 | n = n*ones(1,size(y,2)); 16 | end 17 | 18 | i = rem(n,2)==0; 19 | v = zeros(size(y)); 20 | v(i) = 2*floor(0.5*y(i))+1; % mid-rise quantizer 21 | v(~i) = 2*floor(0.5*(y(~i)+1)); % mid-tread quantizer 22 | 23 | % Limit the output 24 | L = n-1; 25 | for m=[-1 1] 26 | i = m*v>L; 27 | if any(i(:)) 28 | v(i) = m*L(i); 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /delsig/ds_synNTFobj1.m: -------------------------------------------------------------------------------- 1 | function y = ds_synNTFobj1(x,p,osr,f0) 2 | % y=ds_synNTFobj1(x,p,osr,f0) Objective function for synthesizeNTF() 3 | z = exp(2i*pi*(f0+0.5/osr*x)); 4 | if f0>0 5 | z = padt(z,length(p)/2,exp(2i*pi*f0)); 6 | end 7 | z = [z conj(z)]; z = z(:); 8 | if f0==0 9 | z = padb(z,length(p),1); 10 | end 11 | [f1,f2] = ds_f1f2(osr,f0); 12 | ntf = zpk(z,p,1,1); 13 | y = db(rmsGain(ntf,f1,f2)); 14 | -------------------------------------------------------------------------------- /delsig/ds_therm.m: -------------------------------------------------------------------------------- 1 | function sv = ds_therm(v,M) 2 | % sv = ds_therm(v,M) sv is an M by length(v) matrix of +/-1s 3 | % where sum(sv)=v and the -1s are located in the bottom rows 4 | sv = -ones(M,length(v)); 5 | for i=1:length(v) 6 | sv(1:(M+v(i))/2,i) = 1; 7 | end 8 | -------------------------------------------------------------------------------- /delsig/dsclansNTF.m: -------------------------------------------------------------------------------- 1 | function H = dsclansNTF(x,order,rmax,Hz) 2 | % Conversion of clans parameters into a NTF. 3 | 4 | % Translate x into H. 5 | % I've changed the relationships between (zeta,wn) and x 6 | % in order to guarantee LHP roots of the s-polynomial. 7 | Hp = zeros(1,length(Hz)); 8 | odd = rem(order,2); 9 | if odd 10 | s = -x(1)^2; 11 | Hp(1) = rmax*(1+s)./(1-s); 12 | end 13 | for i=1+odd:2:order 14 | zeta = x(i)^2; 15 | wn = x(i+1)^2; 16 | s = roots([1 2*zeta*wn wn^2]); 17 | Hp(i:i+1) = rmax*(1+s)./(1-s); 18 | end 19 | 20 | H = zpk(Hz,Hp,1,1); 21 | -------------------------------------------------------------------------------- /delsig/dsclansObj.m: -------------------------------------------------------------------------------- 1 | function [f,g]=dsclansObj(x,order,OSR,Q,rmax,Hz) 2 | % Objective function for clans.m 3 | % f is the mean-square value of H over the passband 4 | % g = (||h||_1 - Q)^2 5 | 6 | % Translate x into H. 7 | H = dsclansNTF(x,order,rmax,Hz); 8 | 9 | % Compute f and g 10 | z = exp(1i*linspace(0,pi/OSR)); 11 | f = norm(evalTF(H,z))^2; 12 | g = (sum(abs(impulse(H,100))) -1 - Q)^2; 13 | -------------------------------------------------------------------------------- /delsig/dsdemo4.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/delsig/dsdemo4.mat -------------------------------------------------------------------------------- /delsig/dsdemo6.m: -------------------------------------------------------------------------------- 1 | % Demonstrate Saramaki half-band filter design if exist('LiveDemo','var') == 0 LiveDemo=0; end J = sqrt(-1); format compact; clc fprintf(1,'\t\tHalf-band filter design\n\n'); fprintf(1,'\t\tALPHA VERSION\n\n'); if 0 % Use one of the canned examples [f1 f2] = exampleHBF(2); else fp = 0.9*0.25; delta = undbv( -100 ); figure(1); clf set(gcf,'Name','designHBF Iterations'); [f1,f2,info]=designHBF(fp,delta,1); end n1 = length(f1); n2 = length(f2); complexity = size([f1.csd],2) + (2*n1-1)*(n2+size([f2.csd],2)-1); % interleave the even and odd decimated impulse responses Nimp = 2^11; imp = simulateHBF([1 zeros(1,Nimp-1)],f1,f2); mag = abs(fft(imp)); mag = mag(1:end/2+1); figure(2); clf; set(gcf,'Name','designHBF Result'); plot(linspace(0,0.5,length(mag)),dbv(mag)); figureMagic([0 0.5],0.05,2, [-150 3],10,5); -------------------------------------------------------------------------------- /delsig/dsdemo7.m: -------------------------------------------------------------------------------- 1 | % demonstrate findPIS addPIS; % Add the PosInvSet directory to MATLAB's path clear; if exist('qhull')==3 clc; fprintf(1,'\t\tInvariant Set for MOD2 (findPIS) \n\n'); order=2; dsistest fprintf(1,'paused\n'); pause clc; fprintf(1,'\t\tInvariant Set for a 3rd-order modulator (findPIS) \n\n'); order=3; dsistest else clc; fprintf(1,'\t\tInvariant Set for MOD2 (find2dPIS) \n\n'); mod = mod2; ABCD = mod.ABCD; [A B C D] = partitionABCD(ABCD); order=2; figure(1); set(gcf,'NumberTitle','off'); set(gcf,'Name','Working Invariant Set'); echo on; u = 1/pi; t = cputime; s = find2dPIS(u,ABCD,1) t = cputime-t echo off; N=10000; skip=100; [junk x] = simulateDSM(u(ones(1,N+skip)),ABCD,2); x = x(:,1+skip:N+skip); nv = size(s,2); [splus, eplus, sminus, eminus] = dssplit2d(u,ABCD,s); Buv = B*[u;1]; s1 = A*splus + Buv(:,ones(1,size(splus,2))); Buv = B*[u;-1]; s2 = A*sminus + Buv(:,ones(1,size(sminus,2))); ns = [s1 s2]; out = outconvex2d(ns,s); figure(2); set(gcf,'NumberTitle','off'); set(gcf,'Name','Final Invariant Set'); clf; hold on; grid; dotplot(x,'k.'); polyplot(s,'b'); polyplot(s1,'m'); polyplot(s2,'c'); outi = logical(sign(out)); dotplot(ns(:,outi),'rs'); str = sprintf('Final Object: %d image vertices outside', sum(outi)); title(str); xlabel('x_1'); ylabel('x_2'); drawnow; fprintf(1,'%d points from the %d simulated states are outside.\n', sum(outconvex2d(x,s)),N); fprintf(1,'%d image points are outside.\n', sum(out)); fprintf(1,'The returned polygon has %d vertices.\n', size(s,2)); end -------------------------------------------------------------------------------- /delsig/dsdemo8.m: -------------------------------------------------------------------------------- 1 | % Demonstrate the designLCBP function clc; fprintf(1,'\t\t\t Continuous-Time LC Modulator Design\n\n'); %WARNING: designLCBP is very ill-behaved due to deficiencies % in MATLAB's constr() and minimax(). These functions frequently % take a viable set of parameters as a starting point and turn % them into an unstable modulator. I should provide a more robust % implementation... echo on; n = 3; OSR = 64; opt = 2; Hinf = 1.7; f0 = 1/16; t = [0.5 1]; form = 'FB'; dbg = 1; [param H L0 ABCD] = designLCBP(n,OSR,opt,Hinf,f0,t,form,[],dbg); echo off; -------------------------------------------------------------------------------- /delsig/evalF0.m: -------------------------------------------------------------------------------- 1 | function F0 = evalF0(f1,z,phi) 2 | %F0 = evalF0(f1,z,phi) Calculate the values of the F0 (prototype) filter 3 | %of a Saramaki HBF at the given points. 4 | F0 = evalF1( f1, 0.5*(z + 1./z), phi ); 5 | -------------------------------------------------------------------------------- /delsig/evalF1.m: -------------------------------------------------------------------------------- 1 | function F1 = evalF1(f1,z,phi) 2 | %F1 = evalF1(f1,z,phi) Calculate the values of the F1 filter 3 | %(tranformed prototype filter) of a Saramaki HBF at the given points. 4 | 5 | if nargin>2 6 | z = z/phi; 7 | end 8 | 9 | F1 = 0.5; 10 | for i = 1:length(f1); 11 | F1 = F1 + f1(i)*z.^(2*i-1); 12 | end 13 | -------------------------------------------------------------------------------- /delsig/evalMixedTF.m: -------------------------------------------------------------------------------- 1 | function H=evalMixedTF(tf,f,df) 2 | % H=evalMixedTF(tf,f) 3 | % Compute the mixed transfer function tf at a frequency f. 4 | % tf is a struct array with fields Hs and Hz wich represent 5 | % a continuous-time/discrete-time tfs which must be multiplied together 6 | % and then added up. 7 | if nargin<3 8 | df = 1e-5; 9 | end 10 | H = zeros(size(f)); 11 | for i = 1:length(tf) 12 | H = H + evalTFP(tf(i).Hs,tf(i).Hz,f); 13 | end 14 | 15 | err = find(isnan(H)|isinf(H)); 16 | if ~isempty(err) 17 | % Need to fill in the holes. !! Use a "nearby" frequency point 18 | for i=err 19 | H(i) = evalMixedTF(tf,f(i)+df,df*10); 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /delsig/evalRPoly.m: -------------------------------------------------------------------------------- 1 | function y = evalRPoly(roots,x,k) 2 | %function y = evalRPoly(roots,x,k=1) 3 | %Compute the value of a polynomial which is given in terms of its roots. 4 | if(nargin<3) 5 | k=1; 6 | end 7 | 8 | y = k(ones(size(x))); 9 | roots = roots(~isinf(roots)); % remove roots at infinity 10 | for(i=1:length(roots)) 11 | y = y.*(x-roots(i)); 12 | end 13 | -------------------------------------------------------------------------------- /delsig/evalTF.m: -------------------------------------------------------------------------------- 1 | function h = evalTF(tf,z) 2 | %h = evalTF(tf,z) 3 | %Evaluates the rational function described by the struct tf 4 | % at the point(s) given in the z vector. 5 | % TF must be either a zpk object or a struct containing 6 | % form 'zp' or 'coeff' 7 | % zeros,poles,k if form=='zp' 8 | % num,den if form=='coeff' 9 | % 10 | % In Matlab 5, the ss/freqresp() function does nearly the same thing. 11 | 12 | if isobject(tf) % zpk object 13 | if strcmp(class(tf),'zpk') 14 | % Speed improvement by D. Alldred (2013-02-01) 15 | [zs ps k] = zpkdata(tf); 16 | h = k * evalRPoly(zs{1},z) ./ evalRPoly(ps{1},z); 17 | else 18 | fprintf(1,'%s: Only zpk objects supported.\n', mfilename); 19 | end 20 | elseif any(strcmp(fieldnames(tf),'form')) 21 | if strcmp(tf.form,'zp') 22 | h = tf.k * evalRPoly(tf.zeros,z) ./ evalRPoly(tf.poles,z); 23 | elseif strcmp(tf.form,'coeff') 24 | h = polyval(tf.num,z) ./ polyval(tf.den,z); 25 | else 26 | fprintf(1,'%s: Unknown form: %s\n', mfilename, tf.form); 27 | end 28 | else % Assume zp form 29 | h = tf.k * evalRPoly(tf.zeros,z) ./ evalRPoly(tf.poles,z); 30 | end 31 | -------------------------------------------------------------------------------- /delsig/evalTFP.m: -------------------------------------------------------------------------------- 1 | function H=evalTFP(Hs,Hz,f) 2 | % H=evalTFP(Hs,Hz,f) 3 | % Compute the value of a transfer function product Hs*Hz at a frequency f, 4 | % where Hs is a cts-time TF and Hz is a discrete-time TF. 5 | % Both Hs and Hz are SISO zpk objects. 6 | % This function attempts to cancel poles in Hs with zeros in Hz. 7 | 8 | % szeros = Hs.z{1}; 9 | % spoles = Hs.p{1}; 10 | % zzeros = Hz.z{1}; 11 | % zpoles = Hz.p{1}; 12 | % sk = Hs.k; 13 | % zk = Hz.k; 14 | 15 | [szeros, spoles, sk] = zpkdata(Hs); 16 | szeros = szeros{1}; 17 | spoles = spoles{1}; 18 | [zzeros, zpoles, zk] = zpkdata(Hz); 19 | zzeros = zzeros{1}; 20 | zpoles = zpoles{1}; 21 | 22 | slim = min(1e-3,max(1e-5,eps^(1/(1+length(spoles))))); 23 | zlim = min(1e-3,max(1e-5,eps^(1/(1+length(zzeros))))); 24 | 25 | H = zeros(size(f)); 26 | w = 2*pi*f; s = j*w; z=exp(s); 27 | for i=1:length(f) 28 | wi = w(i); si = s(i); zi = z(i); 29 | if isempty(spoles) 30 | cancel = 0; 31 | else 32 | cancel = abs(si-spoles) sum(cancel) 44 | H(i) = 0; 45 | elseif sum(cancelz) < sum(cancel) 46 | H(i) = Inf; 47 | else 48 | H(i) = evalRPoly(szeros,si,Hs.k) * ... 49 | zi^sum(cancel) * evalRPoly(zzeros(~cancelz),zi,Hz.k) / ... 50 | (evalRPoly(spoles(~cancel),si,1)*evalRPoly(zpoles,zi,1)); 51 | end 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /delsig/figureMagic.m: -------------------------------------------------------------------------------- 1 | function figureMagic( xRange, dx, xLab, yRange, dy, yLab, size, name ) %figureMagic( xRange, dx, xLab, yRange, dy, yLab, size, name ) % Handle the input arguments nargin_new = nargin; if nargin_new==1 & iscell(xRange) % Parameters are in a cell arg_tmp = xRange; nargin_new = length(arg_tmp); parameters = { 'xRange', 'dx', 'xLab', 'yRange', ... 'dy', 'yLab', 'size', 'name' }; for arg_ii=1:nargin_new parameter = parameters{arg_ii}; eval([parameter '=arg_tmp{arg_ii};']) end end if nargin_new >=8 set(gcf,'MenuBar','none'); set(gcf,'NumberTitle','off'); set(gcf,'Name',name); end if nargin_new >=7 & ~isempty(size) set(gcf,'PaperUnits','inches','PaperPosition', [0.5 0.5 0.5+size]); end if nargin_new <6 % Defaulted yRange etc v = axis; yRange = v(3:4); DoYaxis = 0; else DoYaxis = 1; end axis([xRange yRange]); grid on; xlabel(''); ylabel(''); set(gca,'FontName','helvetica'); set(gca,'FontSize', 11); set(gca, 'Box', 'on'); if ~isempty(dx) xtix = xRange(1):dx:xRange(2); set(gca,'XTick', xtix); set(gca,'XTickLabel', axisLabels(xtix,xLab)); end if DoYaxis ytix = yRange(1):dy:yRange(2); set(gca,'YTick', ytix); set(gca,'YTickLabel', axisLabels(ytix,yLab)); end -------------------------------------------------------------------------------- /delsig/flattenStruct.c: -------------------------------------------------------------------------------- 1 | /* flattenStruct.c: A MATLAB MEX function for flattening a structure 2 | % flattenStruct( x ) sets variables in the current workspace to 3 | % the fields within x 4 | */ 5 | 6 | #include 7 | #include "mex.h" 8 | 9 | char *cmdName = "flattenStruct"; 10 | 11 | #ifdef __STDC__ 12 | void fatalError(char *s) 13 | #else 14 | fatalError(s) 15 | char *s; 16 | #endif 17 | { 18 | char msg[1024]; 19 | sprintf(msg, "%s: %s", cmdName, s); 20 | mexErrMsgTxt(msg); 21 | } 22 | 23 | #ifdef __STDC__ 24 | void mexFunction(int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs) 25 | #else 26 | mexFunction(nlhs, plhs, nrhs, prhs) 27 | int nlhs, nrhs; 28 | mxArray *plhs[], *prhs[]; 29 | #endif 30 | { 31 | const char *field_name; 32 | char command[256]; 33 | mxArray *field; 34 | int i; 35 | /* Check the arguments */ 36 | if( nlhs != 0 ) 37 | fatalError("Nothing is returned."); 38 | if( nrhs != 1 ) 39 | fatalError("You must supply exactly one argument."); 40 | if( mxIsStruct(prhs[0]) != 1 || mxGetNumberOfElements(prhs[0]) != 1 ) 41 | fatalError("The argurment must be a single struct."); 42 | for( i=0; inargin || eval(['isempty(' parameter ') ']) || ... 23 | ( eval(['isnumeric(' parameter ') ']) && ... 24 | eval(['length(' parameter ') <= 1']) && ... 25 | eval(['isnan(' parameter ')'])) 26 | if isnan(ArgumentsAndDefaults{i,2}) 27 | error('%s: Argument %d (%s) is required.',mfilename, i, parameter ) 28 | else 29 | eval([parameter '= ArgumentsAndDefaults{i,2};']) 30 | end 31 | end 32 | end 33 | f = f(:)'; % Make f a row vector 34 | 35 | [N Mp1] = size(C); 36 | M = Mp1 - 1; 37 | nf = length(f); 38 | nz = f~=0; 39 | w = 2*pi*f; 40 | % F(n+1,j) is the Fourier transform of one x^m segment evaluated at w_j. 41 | F = zeros(M+1,nf); 42 | % Handle f=0 43 | mp1 = 1:Mp1; 44 | if any(~nz) 45 | F(:,~nz) = ((x0+1).^mp1 - x0.^mp1) ./ mp1; 46 | end 47 | % Handle nonzero frequencies 48 | wnz = w(nz); 49 | F(1,nz) = sinc(f(nz)).*exp(-1i*(x0+0.5)*wnz); 50 | exp1 = exp(-1i*(x0+1)*wnz); 51 | exp0 = exp(-1i*(x0)*wnz); 52 | for m=1:M 53 | F(m+1,nz) = 1i./wnz.*( (x0+1)^m*exp1 - x0^m*exp0 - m*F(m,nz) ); 54 | end 55 | p = exp(-1i*w); 56 | ph = ones(size(w)); 57 | Hc = 0; 58 | for n = 1:N 59 | Hc = Hc + C(n,:)*F.*ph; 60 | ph = ph .* p; 61 | end 62 | 63 | -------------------------------------------------------------------------------- /delsig/impL1.m: -------------------------------------------------------------------------------- 1 | function y = impL1(arg1,n) % y=impL1(ntf,n=10) % Compute the impulse response from the comparator % output to the comparator input for the given NTF. % n is the (optional) number of points (10). % % This function is useful when verifying the realization % of a NTF with a specified topology. if nargin<2 n=10; end if isobject(arg1) & strcmp(class(arg1),'zpk') z = arg1.z{1}; p = arg1.p{1}; elseif isstruct(arg1) if any(strcmp(fieldnames(arg1),'zeros')) z = arg1.zeros; else error('No zeros field in the NTF.') end if any(strcmp(fieldnames(arg1),'poles')) p = arg1.poles; else error('No poles field in the NTF.') end end lf_den = padr(poly(z),length(p)+1); lf_num = lf_den-poly(p); if any(imag([lf_num lf_den])) % Complex loop filter lfr_den = real( conv(lf_den,conj(lf_den)) ); lfr_num = conv(lf_num,conj(lf_den)); lf_i = tf( real(lfr_num), lfr_den, 1); lf_q = tf( imag(lfr_num), lfr_den, 1); y = impulse(lf_i,n) + 1i * impulse(lf_q,n); else y = impulse(tf(lf_num,lf_den,1),n); end -------------------------------------------------------------------------------- /delsig/impulsePBF.m: -------------------------------------------------------------------------------- 1 | function [hc, t] = impulsePBF(C,x0,n,d) 2 | %[hc, t] = impulsePBF(C,x0=0,n=20,d=0) Impulse response of a continuous-time polynomial-based filter (PBF) 3 | %Input 4 | % C C(:,j) are the coefficients of segment j starting with the constant term 5 | % x0 offset on x 6 | % n n points per segment 7 | % d derivative d 8 | % 9 | %Output 10 | % hc 1x(n*size(C,2)) vector of the samples of the dth derivative of hc 11 | 12 | % Argument checking and default-setting 13 | ArgumentsAndDefaults = { 14 | 'C' NaN 15 | 'x0' 0 16 | 'n' 20 17 | 'd' 0 18 | }; 19 | for i = 1:size(ArgumentsAndDefaults,1) 20 | parameter = ArgumentsAndDefaults{i,1}; 21 | if i>nargin || eval(['isempty(' parameter ') ']) || ... 22 | ( eval(['isnumeric(' parameter ') ']) && ... 23 | eval(['length(' parameter ') <= 1']) && ... 24 | eval(['isnan(' parameter ')'])) 25 | if isnan(ArgumentsAndDefaults{i,2}) 26 | error('%s: Argument %d (%s) is required.',mfilename, i, parameter ) 27 | else 28 | eval([parameter '= ArgumentsAndDefaults{i,2};']) 29 | end 30 | end 31 | end 32 | 33 | N = size(C,1); 34 | if nargout > 1 35 | t = linspace(0,N-1/n,n*N); 36 | end 37 | 38 | M = size(C,2)-1; 39 | if Mnargin | ( eval(['isnumeric(' parameter ') ']) & ... eval(['any(isnan(' parameter ')) | isempty(' parameter ') ']) ) eval([parameter '=defaults{arg_i};']) end end N=length(X); N2=floor(N/2); f1 = rem(inBin-1,nbin)+1; startbin = [f1:nbin:inBin-1 inBin:inBin+2]; for i=1:n startbin = [startbin startbin(end)+1:nbin:i*inBin-1 i*inBin+[0:2] ]; end m = startbin(length(startbin))+nbin; while m < N2 startbin = [startbin m]; nbin = min(nbin*1.1,2^10); m = round(m+nbin); end stopbin = [startbin(2:length(startbin))-1 N2]; f = ((startbin+stopbin)/2 -1)/N; p = zeros(size(f)); for i=1:length(f) p(i) = dbp(norm(X(startbin(i):stopbin(i)))^2 / ... (stopbin(i)-startbin(i)+1)); end -------------------------------------------------------------------------------- /delsig/lollipop.m: -------------------------------------------------------------------------------- 1 | function lollipop(x,y,color,lw,ybot) 2 | % lollipop(x,y,color,lw,ybot) Plot lollipops (o's and sticks) 3 | if nargin<4 4 | ybot = 0; 5 | if nargin<4 6 | lw = 2; 7 | if nargin<3 8 | color = ''; 9 | end 10 | end 11 | end 12 | 13 | h = ishold; 14 | hold on; 15 | 16 | %Plot circles 17 | plot(x,y,['o' color], 'linewidth', lw); 18 | 19 | % Make x and y row vectors, then plot as sticks 20 | x = x(:)'; y = y(:)'; 21 | x = [x;x;nan*ones(size(x))]; 22 | y = [y;repmat(ybot,2,length(y))]; 23 | plot(x(:),y(:),color, 'linewidth', lw); 24 | 25 | if ~h 26 | hold off; 27 | end 28 | -------------------------------------------------------------------------------- /delsig/mapQtoR.m: -------------------------------------------------------------------------------- 1 | function A = mapQtoR(Z) 2 | % A = mapQtoR(Z) Convert a quadrature matrix into its real equivalent. 3 | % Each element in Z is represented by a 2x2 matrix in A: z -> [x -y; y x] 4 | A = zeros(2*size(Z)); 5 | A(1:2:end,1:2:end) = real(Z); 6 | A(2:2:end,2:2:end) = real(Z); 7 | A(1:2:end,2:2:end) = -imag(Z); 8 | A(2:2:end,1:2:end) = imag(Z); 9 | return 10 | -------------------------------------------------------------------------------- /delsig/mapRtoQ.m: -------------------------------------------------------------------------------- 1 | function [ABCDq, ABCDp] = mapR2Q( ABCDr ) 2 | % [ABCDq ABCDp] = mapR2Q( ABCDr ) Map a real ABCD to a quadrature ABCD 3 | % ABCDr has its states paired (real,imaginary) 4 | % 5 | % ABCDq is the quadrature (complex) version of ABCDr 6 | % ABCDp is the mirror-image system matrix 7 | % (ABCDp is zero if ABCDr has no quadrature errors) 8 | 9 | ABCD11 = ABCDr(1:2:end,1:2:end); 10 | ABCD12 = ABCDr(1:2:end,2:2:end); 11 | ABCD21 = ABCDr(2:2:end,1:2:end); 12 | ABCD22 = ABCDr(2:2:end,2:2:end); 13 | 14 | ABCDq = 0.5*(ABCD11+ABCD22) + 0.5i*(ABCD21-ABCD12); 15 | ABCDp = 0.5*(ABCD11-ABCD22) + 0.5i*(ABCD21+ABCD12); 16 | 17 | -------------------------------------------------------------------------------- /delsig/mod1.m: -------------------------------------------------------------------------------- 1 | function mod = mod1() 2 | % mod = mod1() 3 | % Populate a structure describing the first-order modulator 4 | A=1; 5 | B=[1 -1]; 6 | C=1; 7 | D=[0 0]; 8 | mod.ABCD=[A B; C D]; 9 | [mod.NTF mod.STF] = calculateTF(mod.ABCD); 10 | -------------------------------------------------------------------------------- /delsig/mod2.m: -------------------------------------------------------------------------------- 1 | function mod = mod2() 2 | % mod = mod2() 3 | % Populate a structure describing the second-order modulator 4 | A=[1 0; 1 1]; 5 | B=[1 -1; 1 -2]; 6 | C=[0 1]; 7 | D=[0 0]; 8 | ABCD=[A B; C D]; 9 | mod.ABCD=[A B; C D]; 10 | [mod.NTF mod.STF] = calculateTF(mod.ABCD); 11 | -------------------------------------------------------------------------------- /delsig/nabsH.m: -------------------------------------------------------------------------------- 1 | function y=nabsH(w,H) 2 | % nabsH computes the negative of the absolute value of H 3 | % at the specified frequency on the unit circle. 4 | % 5 | % This function is used by infnorm.m. 6 | z = exp(i*w); 7 | y = -abs(evalTF(H,z)); 8 | -------------------------------------------------------------------------------- /delsig/padb.m: -------------------------------------------------------------------------------- 1 | function y = padb(x, n, val) 2 | %y = padb(x, n, val) 3 | % Pad a matrix x on the bottom to length n with value val(0) 4 | % The empty matrix is assumed to be have 1 empty column 5 | if nargin < 3 6 | val = 0; 7 | end 8 | 9 | y = [ x ; val( ones( n-size(x,1), max(1,size(x,2)) ) ) ]; 10 | -------------------------------------------------------------------------------- /delsig/padl.m: -------------------------------------------------------------------------------- 1 | function y = padl(x, n, val) 2 | %y = padl(x, n, val) 3 | % Pad a matrix x on the left to length n with value val(0) 4 | % The empty matrix is assumed to be have 1 empty row 5 | if nargin < 3 6 | val = 0; 7 | end 8 | 9 | y = [ val(ones(max(1,size(x,1)),n-size(x,2))) x ]; 10 | -------------------------------------------------------------------------------- /delsig/padr.m: -------------------------------------------------------------------------------- 1 | function y = padr(x, n, val) 2 | %y = padr(x, n, val) 3 | % Pad a matrix x on the right to length n with value val(0) 4 | % The empty matrix is assumed to be have 1 empty row 5 | if nargin < 3 6 | val = 0; 7 | end 8 | 9 | y = [ x val(ones(max(1,size(x,1)),n-size(x,2))) ]; 10 | -------------------------------------------------------------------------------- /delsig/padt.m: -------------------------------------------------------------------------------- 1 | function y = padt(x, n, val) 2 | %y = padt(x, n, val) 3 | % Pad a matrix x on the top to length n with value val(0) 4 | % The empty matrix is assumed to be have 1 empty column 5 | if nargin < 3 6 | val = 0; 7 | end 8 | 9 | y = [ val( ones( n-size(x,1), max(1,size(x,2)) ) ); x ]; 10 | -------------------------------------------------------------------------------- /delsig/partitionABCD.m: -------------------------------------------------------------------------------- 1 | function [A, B, C, D] = partitionABCD(ABCD, m); 2 | % function [A B C D] = partitionABCD(ABCD, m); Partition ABCD into 3 | % A, B, C, D for an m-input state-space system. 4 | if nargin<2 5 | n = min(size(ABCD))-1; 6 | m = size(ABCD,2)-n; 7 | else 8 | n = size(ABCD,2)-m; 9 | end 10 | r = size(ABCD,1)-n; 11 | 12 | A = ABCD(1:n, 1:n); 13 | B = ABCD(1:n, n+1:n+m); 14 | C = ABCD(n+1:n+r, 1:n); 15 | D = ABCD(n+1:n+r, n+1:n+m); 16 | -------------------------------------------------------------------------------- /delsig/peakSNR.m: -------------------------------------------------------------------------------- 1 | function [peak_snr,peak_amp] = peakSNR(snr,amp) 2 | % [peak_snr,peak_amp] = peakSNR(snr,amp) Estimate the snr peak 3 | % by threading a line of slope 1 through the (amp,snr) data. 4 | % Both amp and snr are expressed in dB. 5 | 6 | % Delete garbage data 7 | i = abs(snr) == Inf; snr(i) = []; amp(i) = []; 8 | i = isnan(snr); snr(i) = []; amp(i) = []; 9 | i = snr<3; snr(i) = []; amp(i) = []; 10 | n = length(amp); 11 | 12 | 13 | % Sort by amplitude 14 | [amp, i] = sort(amp); snr = snr(i); 15 | 16 | i = 1; 17 | while any(i~=0) && n > 3 18 | % Draw a 45-degree median line through the data 19 | tmp = sort(snr-amp); 20 | if rem(n,2) == 0 21 | m = mean( tmp(n/2 +[1 0]) ); 22 | else 23 | m = tmp((n+1)/2); 24 | end 25 | % Discard data that is more than 6dB off 26 | i = abs(amp-snr+m) > 6; 27 | snr(i) = []; 28 | amp(i) = []; 29 | n = length(amp); 30 | end 31 | 32 | peak_amp = max(amp); 33 | peak_snr = peak_amp + m; 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /delsig/plotSpectrum.m: -------------------------------------------------------------------------------- 1 | function plotSpectrum(X,fin,fmt,nbin,n) 2 | % plotSpectrum(X,fin,fmt='-',nbin=8,n=3) Plot a smoothed spectrum 3 | if nargin<5 4 | n = 3; 5 | if nargin<4 6 | nbin = 8; 7 | if nargin<3 8 | fmt = '-'; 9 | end 10 | end 11 | end 12 | i = fmt=='.' | ( fmt>='0' & fmt <='9' ); 13 | if any(i) 14 | i = find(~i); i = i(end); % i = index of last character before the numeric suffix 15 | lw = str2num(fmt(i+1:end)); 16 | fmt = fmt(1:i); 17 | else 18 | lw = 0.5; 19 | end 20 | [f p] = logsmooth(X,fin,nbin,n); 21 | semilogx(f,p,fmt,'Linewidth',lw); 22 | -------------------------------------------------------------------------------- /delsig/plotUsage.m: -------------------------------------------------------------------------------- 1 | function plotUsage(sv,colors) 2 | % plotUsage(sv,colors='bgry') 3 | % Plot the elemet usage for a multi-elemet DAC. 4 | % The colors are for sv = 1,-1,i,-i. 5 | if nargin<2 6 | colors = 'bgry'; 7 | end 8 | T = size(sv,2); M = size(sv,1); 9 | 10 | % Plot the grid 11 | x=[0:T; 0:T]; x=x(:)'; 12 | T2 = ceil((T+1)/2); 13 | y=[zeros(1,T2); M*ones(2,T2); zeros(1,T2)]; y = y(1:2*(T+1))'; 14 | plot(x,y,'k'); 15 | hold on; 16 | M2 = ceil((M+1)/2); 17 | x=[zeros(1,M2); T*ones(2,M2); zeros(1,M2)]; x = x(1:2*(M+1))'; 18 | y=[0:M; 0:M]; y=y(:)'; 19 | plot(x,y,'k'); 20 | % axis([0 T 0 M]); 21 | axis('image'); 22 | 23 | for t=1:T 24 | for i=1:M 25 | if sv(i,t) == 1 26 | fill([t-1 t-1 t t],[i-1 i i i-1],colors(1)); 27 | elseif sv(i,t) == -1 28 | fill([t-1 t-1 t t],[i-1 i i i-1],colors(2)); 29 | elseif sv(i,t) == 1i 30 | fill([t-1 t-1 t t],[i-1 i i i-1],colors(3)); 31 | elseif sv(i,t) == -1i 32 | fill([t-1 t-1 t t],[i-1 i i i-1],colors(4)); 33 | end 34 | end 35 | end 36 | hold off 37 | % xlabel('time'); 38 | % ylabel('element number'); 39 | -------------------------------------------------------------------------------- /delsig/rms.m: -------------------------------------------------------------------------------- 1 | function y = rms(x,no_dc) 2 | % y = rms(x,no_dc(0)) 3 | if nargin<2 4 | no_dc=0; 5 | end 6 | if no_dc 7 | x = x - mean(x); 8 | end 9 | y = norm(x)/sqrt(length(x)); 10 | 11 | -------------------------------------------------------------------------------- /delsig/rmsGain.m: -------------------------------------------------------------------------------- 1 | function g = rmsGain(H,f1,f2,N) 2 | %function g = rmsGain(H,f1,f2,N=100) 3 | %Compute the root mean-square gain of the discrete-time 4 | %tf H in the frequency band (f1,f2) 5 | 6 | if nargin<4 7 | N = 100; 8 | end 9 | w = linspace(2*pi*f1,2*pi*f2,N); 10 | g = norm( evalTF(H,exp(j*w)) ) / sqrt(N); 11 | -------------------------------------------------------------------------------- /delsig/shiftPBF.m: -------------------------------------------------------------------------------- 1 | function Cp = shiftPBF(C,x0) 2 | % Cp = shiftPBF(C,x0) 3 | % Shift the polynomial argument of a polynomial-based filter by x0, 4 | % i.e. x' = x + x0 5 | 6 | [N, Mp1] = size(C); 7 | Cp = zeros(N,Mp1); 8 | M = Mp1 - 1; 9 | m = 0:M; 10 | x = (x0.^m)'; 11 | for i=1:size(C,2) 12 | Cp(:,i) = C*x; 13 | C = C .* repmat(m,N,1); 14 | C = C(:,2:end); 15 | m(end) = []; 16 | x(end) = []; 17 | end 18 | -------------------------------------------------------------------------------- /delsig/simulateBiDWA.m: -------------------------------------------------------------------------------- 1 | function [sv,sx] = simulateBiDWA(v,M,sx) 2 | % [sv,sx] = simulateBiDWA(v,M,sx=0) Simulate the Bi-directional DWA algorithm 3 | % I. Fujimori, L. Longo, A. Hairapetian, K. Seiyama, S. Kosic, J. Cao and S.L. Chan, 4 | % "A 90-dB SNR 2.5-MHz output-rate ADC using cascaded multibit delta-sigma modulation at 8x oversampling ratio," 5 | % IEEE Journal of Solid-State Circuits, vol.35, no.12, pp.1820-1828, Dec. 2000. 6 | 7 | % Argument checking and default-setting 8 | ArgumentsAndDefaults = { 9 | 'v' NaN 10 | 'M' 16 11 | 'sx' [0 0 0] 12 | }; 13 | for i = 1:size(ArgumentsAndDefaults,1) 14 | parameter = ArgumentsAndDefaults{i,1}; 15 | if i>nargin || eval(['isempty(' parameter ') ']) || ... 16 | ( eval(['isnumeric(' parameter ') ']) && ... 17 | eval(['length(' parameter ') <= 1']) && ... 18 | eval(['isnan(' parameter ')'])) 19 | if isnan(ArgumentsAndDefaults{i,2}) 20 | error('%s: Argument %d (%s) is required.',mfilename, i, parameter ) 21 | else 22 | eval([parameter '= ArgumentsAndDefaults{i,2};']) 23 | end 24 | end 25 | end 26 | 27 | N = length(v); 28 | p0 = sx(1); 29 | p1 = sx(2); 30 | dir = sx(3); 31 | 32 | v = (v+M)/2; % Translate -M:2:M to 0:M 33 | sv = zeros(M,N); 34 | for n=1:N 35 | if dir==0 36 | pp = p0+v(n); 37 | i = mod(p0:pp-1,M); 38 | sv(i+1,n) = 1; 39 | p0 = mod(pp,M); 40 | dir = 1; 41 | else 42 | pp = p1-v(n); 43 | i = mod(pp:p1-1,M); 44 | sv(i+1,n) = 1; 45 | p1 = mod(pp,M); 46 | dir = 0; 47 | end 48 | end 49 | 50 | sv = 2*sv - 1; % Translate [0 1] to [-1 1] 51 | sx = [p0 p1 dir]; 52 | 53 | 54 | -------------------------------------------------------------------------------- /delsig/sinc_decimate.m: -------------------------------------------------------------------------------- 1 | function y = sinc_decimate(x,m,r) 2 | % y = sinc_decimate(x,m,r) Decimate x by m-th order sinc of length r. 3 | x = x(:)'; 4 | for i=1:m 5 | x = cumsum(x); 6 | x = [x(1:r) x(r+1:end)-x(1:end-r)]/r; 7 | end 8 | y = x(r:r:end); 9 | -------------------------------------------------------------------------------- /delsig/thermometer.m: -------------------------------------------------------------------------------- 1 | function t = thermometer(x,m) 2 | % t = thermometer(x,m) t is an m by length(x) matrix wherein the first 3 | % x(i) components of column i are one; 4 | t = zeros(m,length(x)); 5 | for i=1:length(x) 6 | t(1:x(i),i) = ones(x(i),1); 7 | end 8 | -------------------------------------------------------------------------------- /delsig/undbm.m: -------------------------------------------------------------------------------- 1 | function v=undbm(p,z) 2 | % v=undbm(p,z=50) = sqrt(z*10^(p/10-3)) rms voltage equivalent to a power p indBm 3 | if nargin<2 4 | z = 50; 5 | end 6 | v = sqrt(z*10.^(p/10-3)); 7 | -------------------------------------------------------------------------------- /delsig/undbp.m: -------------------------------------------------------------------------------- 1 | function y = undbp(x) 2 | % y = undbp(x) Convert x from dB to a power 3 | y = 10.^(x/10); 4 | -------------------------------------------------------------------------------- /delsig/undbv.m: -------------------------------------------------------------------------------- 1 | function y = undbv(x) 2 | % y = undbv(x) Convert x from dB to a voltage 3 | y = 10.^(x/20); 4 | -------------------------------------------------------------------------------- /delsig/zinc.m: -------------------------------------------------------------------------------- 1 | function mag = zinc(f,n,m) 2 | % mag = zinc(f,n=64,m=1) 3 | % Calculate the magnitude response of a cascade of m sinc_n filters at frequencies f. 4 | if nargin<3 5 | m = 1; 6 | if nargin<2 7 | n = 64; 8 | end 9 | end 10 | 11 | mag = abs( sinc(n*f) ./ sinc(f) ).^m; 12 | -------------------------------------------------------------------------------- /deltasigma/_bunquantize.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _bunquantize.py 3 | # Module providing the bunquantize function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the bunquantize() function 17 | """ 18 | 19 | import numpy as np 20 | 21 | from ._utils import carray 22 | 23 | 24 | def bunquantize(q): 25 | """The value corresponding to a bidirectionally quantized quantity. 26 | 27 | ``q`` is a (2n, m) ndarray containing the powers of 2 and their signs 28 | for each quantized value. 29 | 30 | .. seealso:: 31 | :func:`bquantize` 32 | 33 | """ 34 | y = [] 35 | for qi in q: 36 | y += [(qi[1:qi.shape[0]+1:2, :]*2.**qi[:qi.shape[0]:2, :]).sum()] 37 | return carray(y) 38 | -------------------------------------------------------------------------------- /deltasigma/_constants.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _constants.py 3 | # This module holds a few constants that are built-in in MATLAB and that were 4 | # not found in Python. 5 | # Copyright 2013 Giuseppe Venturini 6 | # This file is part of python-deltasigma. 7 | # 8 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 9 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 10 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 11 | # 12 | # python-deltasigma is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # LICENSE file for the licensing terms. 16 | 17 | """This module holds a few constants that are built-in in MATLAB and that were 18 | not found in Python. 19 | """ 20 | 21 | import numpy as np 22 | 23 | eps = np.finfo(float).eps # x86 2.22044604925e-16 24 | -------------------------------------------------------------------------------- /deltasigma/_dbm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _dbm.py 3 | # This module provides the dbm function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the dbm() function, used to convert an RMS voltage to dBm. 17 | """ 18 | 19 | from __future__ import division 20 | 21 | import numpy as np 22 | 23 | from ._utils import carray, restore_input_form, save_input_form 24 | 25 | 26 | def dbm(v, R=50): 27 | """Calculate the dBm equivalent of an RMS voltage ``v``. 28 | 29 | .. math:: 30 | 31 | P_{dBm} = 10 \\mathrm{log}_{10}(1000 \\frac{v^2}{R} ) 32 | 33 | **Parameters:** 34 | 35 | v : scalar or sequence 36 | The voltages to be converted. 37 | 38 | R : scalar, optional 39 | The resistor value the power is calculated upon, defaults to 50 ohm. 40 | 41 | **Returns:** 42 | 43 | PdBm : scalar or sequence 44 | The input in dBm. 45 | 46 | .. seealso:: :func:`undbm`, :func:`db`, :func:`dbp`, :func:`dbv` 47 | 48 | """ 49 | iform = save_input_form(v) 50 | v = carray(v) 51 | y = -np.Inf * np.ones(np.size(v)) 52 | nonzero = (v != 0) 53 | y[nonzero] = 10. * np.log10(np.abs(v[nonzero] ** 2.) / R) + 30 54 | return restore_input_form(y, iform) 55 | -------------------------------------------------------------------------------- /deltasigma/_dbp.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _dbp.py 3 | # This module provides the dbp function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the dbp() function, used to convert a power gain to dB. 17 | """ 18 | 19 | import numpy as np 20 | 21 | from ._utils import carray, restore_input_form, save_input_form 22 | 23 | 24 | def dbp(x): 25 | """Calculate the dB equivalent of the power ratio ``x``. 26 | 27 | .. math:: 28 | 29 | P_{dB} = 10 \\mathrm{log}_{10}(x) 30 | 31 | **Parameters:** 32 | 33 | x : scalar or sequence 34 | The power ratio to be converted. 35 | 36 | **Returns:** 37 | 38 | PdB : scalar or sequence 39 | The input expressed in dB. 40 | 41 | .. seealso:: :func:`undbp`, :func:`db`, :func:`dbm`, :func:`dbv` 42 | 43 | """ 44 | iform = save_input_form(x) 45 | x = carray(x) 46 | y = -np.Inf * np.ones(x.shape) 47 | nonzero = (x != 0) 48 | y[nonzero] = 10. * np.log10(np.abs(x[nonzero])) 49 | return restore_input_form(y, iform) 50 | -------------------------------------------------------------------------------- /deltasigma/_dbv.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _dbv.py 3 | # This module provides the dbv function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the dbv() function, used to convert a voltage gain to dB. 17 | """ 18 | 19 | import numpy as np 20 | 21 | from ._undbv import undbv 22 | from ._utils import carray, restore_input_form, save_input_form 23 | 24 | 25 | def dbv(x): 26 | """Calculate the dB equivalent of the voltage ratio ``x``. 27 | 28 | .. math:: 29 | 30 | G_{dB} = 20 \\mathrm{log}_{10}(|x|) 31 | 32 | **Parameters:** 33 | 34 | x : scalar or sequence 35 | The voltage (ratio) to be converted. 36 | 37 | **Returns:** 38 | 39 | GdB : scalar or sequence 40 | The input voltage (ratio) expressed in dB. 41 | 42 | .. seealso:: :func:`undbv`, :func:`db`, :func:`dbp`, :func:`dbm` 43 | 44 | """ 45 | iform = save_input_form(x) 46 | x = carray(x) 47 | y = -np.inf*np.ones(x.shape) 48 | nonzero = (x != 0) 49 | y[nonzero] = 20.*np.log10(np.abs(x[nonzero])) 50 | return restore_input_form(y, iform) 51 | -------------------------------------------------------------------------------- /deltasigma/_delay.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _delay.py 3 | # This module provides the delay function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the delay() function, used to delay a signal by a 17 | specified amount of samples. 18 | """ 19 | 20 | import numpy as np 21 | 22 | 23 | def delay(x, n=1): 24 | """Delay signal ``x`` by ``n`` samples. 25 | """ 26 | x = np.atleast_1d(x) 27 | nx = max(x.shape) 28 | if nx <= n: 29 | y = np.zeros(x.shape) 30 | else: 31 | if len(x.shape) == 1: 32 | y = np.concatenate((np.zeros((n,)), x[:nx-n])) 33 | elif x.shape[0] > x.shape[1]: 34 | y = np.concatenate((np.zeros((n, x.shape[1])), x[:nx-n, :]), axis=0) 35 | else: 36 | y = np.concatenate((np.zeros((x.shape[0], n)), x[:, :nx-n]), axis=1) 37 | return y 38 | -------------------------------------------------------------------------------- /deltasigma/_ds_f1f2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _ds_f1f2.py 3 | # This module provides the ds_f1f2 function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the ds_f1f2() function. 17 | """ 18 | 19 | def ds_f1f2(OSR=64, f0=0., complex_flag=False): 20 | """[f1, f2] = ds_f1f2(OSR=64, f0=0, complex_flag=0) 21 | This function has no original docstring. 22 | """ 23 | if complex_flag: 24 | f1 = f0 - 0.5/OSR 25 | f2 = f0 + 0.5/OSR 26 | else: 27 | if f0 > 0.25/OSR: 28 | f1 = f0 - 0.25/OSR 29 | f2 = f0 + 0.25/OSR 30 | else: 31 | f1 = 0. 32 | f2 = 0.5/OSR 33 | return f1, f2 34 | -------------------------------------------------------------------------------- /deltasigma/_ds_freq.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _ds_freq.py 3 | # This module provides the ds_freq function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the ds_freq() function, used to generate a frequency 17 | vector suitable for plotting the frequency response of an NTF. 18 | """ 19 | 20 | from __future__ import division 21 | 22 | import numpy as np 23 | 24 | 25 | def ds_freq(osr=64., f0=0., quadrature=False): 26 | """Frequency vector suitable for plotting the frequency response of an NTF 27 | """ 28 | if quadrature: 29 | f_left = -0.5 30 | f_special = (f0, -f0) 31 | else: 32 | f_left = 0. 33 | f_special = (f0, ) 34 | f = np.linspace(f_left, 0.5, num=100) 35 | # Use finer spacing in the vicinity of the passband 36 | for fx in f_special: 37 | f1 = max(f_left, fx - 1./osr) 38 | f2 = min(0.5, fx + 2./osr) 39 | dels = np.where(np.logical_and(f <= f2, f >= f1)) 40 | f = np.delete(f, dels) 41 | f = np.sort(np.concatenate((f, np.linspace(f1, f2, num=100)))) 42 | return f 43 | -------------------------------------------------------------------------------- /deltasigma/_ds_synNTFobj1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _ds_synNTFobj1.py 3 | # Module providing the ds_synNTFobj1 function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the ds_synNTFobj1() function 17 | """ 18 | 19 | from __future__ import division 20 | import numpy as np 21 | 22 | from ._db import db 23 | from ._ds_f1f2 import ds_f1f2 24 | from ._padb import padb 25 | from ._padt import padt 26 | from ._rmsGain import rmsGain 27 | from ._utils import carray 28 | 29 | 30 | def ds_synNTFobj1(x, p, osr, f0): 31 | """Objective function for :func:`synthesizeNTF` 32 | 33 | This function is not meant to be used directly but it is provided for compliance with the 34 | MATLAB DS Toolbox. 35 | 36 | """ 37 | p = carray(p) 38 | z = np.exp(2j*np.pi*(f0 + 0.5/osr*x)) 39 | z = carray(z) 40 | if f0 > 0: 41 | z = padt(z, p.shape[0]//2., np.exp(2j*np.pi*f0)) 42 | 43 | z = np.hstack((z, np.conj(z))) 44 | z = z[:] 45 | if f0 == 0: 46 | z = padb(z, p.shape[0], 1) 47 | 48 | f1, f2 = ds_f1f2(osr, f0) 49 | ntf = (z, p, 1) 50 | y = db(rmsGain(ntf, f1, f2)) 51 | return y 52 | -------------------------------------------------------------------------------- /deltasigma/_dsclansNTF.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _dsclansNTF.py 3 | # Module providing the dsclansNTF function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the dsclansNTF() function 17 | """ 18 | 19 | import numpy as np 20 | 21 | from ._utils import carray 22 | 23 | 24 | def dsclansNTF(x, order, rmax, Hz): 25 | """ Conversion of clans parameters into a NTF. 26 | 27 | Translate x into H. 28 | I've changed the relationships between (zeta, wn) and x 29 | in order to guarantee LHP roots of the s-polynomial. 30 | 31 | Returns the NTF, a zpk tuple. 32 | """ 33 | x = x.squeeze() 34 | Hz = carray(Hz) 35 | Hz = Hz.reshape((-1,)) 36 | Hp = np.zeros((1,), dtype=np.complex128) 37 | odd = (order % 2 == 1) 38 | if odd: 39 | s = -x[0]**2. 40 | Hp[0] = rmax*(1. + s)/(1. - s) 41 | 42 | for i in range(0+1*odd, order, 2): 43 | Hp = np.hstack((Hp, np.zeros((2,)))) 44 | zeta = x[i]**2 45 | wn = x[i + 1]**2 46 | s = np.roots(np.array((1, 2*zeta*wn, wn**2))) 47 | Hp[i:i+2] = rmax*(1. + s)/(1. - s) 48 | 49 | H = (Hz, Hp, 1.) 50 | return H 51 | -------------------------------------------------------------------------------- /deltasigma/_evalF0.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _evalF0.py 3 | # Module providing the evalF0 function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the evalF0() function 17 | """ 18 | 19 | from __future__ import division 20 | 21 | from ._evalF1 import evalF1 22 | 23 | 24 | def evalF0(f1, z, phi): 25 | """Calculate the values of the F0 (prototype) filter 26 | of a Saramaki HBF at the given points. 27 | """ 28 | return evalF1(f1, 0.5*(z + 1./z), phi) 29 | -------------------------------------------------------------------------------- /deltasigma/_evalF1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _evalF1.py 3 | # Module providing the evalF1 function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the evalF1() function 17 | """ 18 | from __future__ import division 19 | 20 | import numpy as np 21 | 22 | 23 | def evalF1(f1, z, phi=None): 24 | """Calculate the values of the F1 filter 25 | (tranformed prototype filter) of a Saramaki HBF at the given points. 26 | """ 27 | if phi is not None: 28 | z = z/phi 29 | f1 = np.asarray(f1).squeeze() 30 | f1 = np.atleast_1d(f1) 31 | 32 | F1 = 0.5 33 | for i in range(f1.shape[0]): 34 | F1 = F1 + f1[i]*z**(2*i+1) 35 | 36 | return F1 37 | -------------------------------------------------------------------------------- /deltasigma/_evalRPoly.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _evalRPoly.py 3 | # This module provides the evalRPoly function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the evalRPoly() function, used to evaluate the value 17 | of a polynomial which is given in terms of its roots. 18 | """ 19 | 20 | import numpy as np 21 | 22 | from ._utils import carray 23 | 24 | 25 | def evalRPoly(roots, x, k=1): 26 | """Compute the value of a polynomial which is given in terms of its roots. 27 | """ 28 | roots = carray(roots) 29 | y = k 30 | roots = roots[~np.isinf(roots)] # remove roots at infinity 31 | for r in roots: 32 | y = y*(x - r) 33 | return y 34 | -------------------------------------------------------------------------------- /deltasigma/_frespF1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _frespF1.py 3 | # Module providing the frespF1 function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the frespF1() function 17 | """ 18 | 19 | from __future__ import division 20 | 21 | import numpy as np 22 | import matplotlib.pyplot as plt 23 | 24 | from ._dbv import dbv 25 | 26 | 27 | def frespF1(f1, f=None, phi=1, plot=False): 28 | """Plot/calculate the frequency response of the F1 filter 29 | in a Saramaki HBF at the points given in the optional f (n by 1) vector. 30 | """ 31 | if f is None: 32 | f = np.linspace(0, 0.5) 33 | cos_w = np.cos(2*np.pi*f) 34 | F1 = 0.5 35 | for i in range(max(f1.shape)): 36 | F1 = F1 + f1[i] * ((cos_w/phi)**(2*i + 1)) 37 | if plot: 38 | plt.plot(f, dbv(F1)) 39 | plt.grid('on') 40 | fresp = F1 41 | return fresp 42 | -------------------------------------------------------------------------------- /deltasigma/_l1norm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _l1norm.py 3 | # Module providing the l1norm function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the l1norm() function 17 | """ 18 | 19 | from __future__ import division 20 | 21 | from warnings import warn 22 | 23 | import numpy as np 24 | from scipy.signal import dimpulse, lti 25 | 26 | from ._utils import _get_zpk, _is_A_B_C_D, _is_num_den, _is_zpk 27 | 28 | 29 | def l1norm(H): 30 | """Compute the l1-norm of a z-domain transfer function. 31 | 32 | The norm is evaluated over the first 100 samples. 33 | 34 | **Parameters:** 35 | 36 | H : sequence or lti object 37 | Any supported LTI representation is accepted. 38 | 39 | **Returns:** 40 | 41 | l1normH : float 42 | The L1 norm of ``H``. 43 | 44 | .. note: 45 | LTI objects are translated to ZPK tuples, with possible 46 | rounding errors. 47 | 48 | """ 49 | if _is_zpk(H): 50 | z, p, k = H 51 | HP = (z, p, k, 1.) 52 | elif _is_num_den(H): 53 | num, den = H 54 | HP = (num, den, 1.) 55 | elif _is_A_B_C_D(H): 56 | A, B, C, D = H 57 | HP = (A, B, C, D, 1.) 58 | elif isinstance(H, lti): 59 | warn('l1norm() got an LTI object, translated to zpk form, rounding errors possible.') 60 | z, p, k = _get_zpk(H) 61 | HP = (z, p, k, 1.) 62 | _, y = dimpulse(HP, t=np.arange(100)) 63 | return np.sum(np.abs(y[0])) 64 | -------------------------------------------------------------------------------- /deltasigma/_mapRtoQ.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _mapRtoQ.py 3 | # Module providing the mapRtoQ function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the mapRtoQ() function 17 | """ 18 | 19 | from __future__ import division 20 | 21 | import numpy as np 22 | 23 | 24 | def mapRtoQ(ABCDr): 25 | """Map a real ABCD matrix to a quadrature one. 26 | 27 | **Parameters:** 28 | 29 | ABCDr : ndarray 30 | A real matrix describing a quadrature system. 31 | 32 | ``ABCDr`` has its states paired (real, imaginary). 33 | 34 | **Returns:** 35 | 36 | (ABCDq, ABCDp) : tuple 37 | 38 | Where: 39 | 40 | ABCDq : ndarray 41 | is the quadrature (complex) version of ABCDr. 42 | ABCDp : ndarray 43 | is the mirror-image system matrix. 44 | 45 | .. note:: ``ABCDp`` is zero if ``ABCDr`` has no quadrature errors. 46 | """ 47 | ABCD11 = ABCDr[::2, ::2] 48 | ABCD12 = ABCDr[::2, 1::2] 49 | ABCD21 = ABCDr[1::2, ::2] 50 | ABCD22 = ABCDr[1::2, 1::2] 51 | 52 | ABCDq = 0.5*(ABCD11 + ABCD22) + 0.5j*(ABCD21 - ABCD12); 53 | ABCDp = 0.5*(ABCD11 - ABCD22) + 0.5j*(ABCD21 + ABCD12); 54 | 55 | return ABCDq, ABCDp 56 | -------------------------------------------------------------------------------- /deltasigma/_mod1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _mod1.py 3 | # Module providing the mod1 function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the mod1() utility function 17 | """ 18 | 19 | import numpy as np 20 | 21 | from ._calculateTF import calculateTF 22 | 23 | 24 | def mod1(): 25 | """A description of the first-order modulator. 26 | 27 | **Returns:** 28 | 29 | ABCD, NTF, STF : a tuple of (ndarray, lti, lti) 30 | The elements are the ABCD matrix (ndarray), the NTF (LTI object), the 31 | STF (LTI object). 32 | 33 | .. note:: 34 | 35 | If a version of the ``scipy`` library equal to 0.16.x or greater is in 36 | use, the NTF and STF objects will be ``ZeroPolesGain`` objects, a 37 | subclass of the scipy LTI object (``scipy.signal.lti``). 38 | 39 | """ 40 | A = np.array([[1.]]) 41 | B = np.array([[1., -1.]]) 42 | C = np.array([[1.]]) 43 | D = np.array([[0., 0.]]) 44 | ABCD = np.vstack((np.hstack((A, B)), np.hstack((C, D)))) 45 | H, G = calculateTF(ABCD) 46 | return ABCD, H, G 47 | -------------------------------------------------------------------------------- /deltasigma/_mod2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _mod2.py 3 | # Module providing the mod2 function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the mod2() utility function 17 | """ 18 | 19 | import numpy as np 20 | 21 | from ._calculateTF import calculateTF 22 | 23 | 24 | def mod2(): 25 | """A description of the second-order modulator. 26 | 27 | **Returns:** 28 | 29 | ABCD, NTF, STF : a tuple of (ndarray, lti, lti) 30 | The elements are the ABCD matrix (ndarray), 31 | the NTF (LTI object), the STF (LTI object). 32 | 33 | .. note:: 34 | 35 | If a version of the ``scipy`` library equal to 0.16.x or greater is in 36 | use, the NTF and STF objects will be ``ZeroPolesGain`` objects, a 37 | subclass of the scipy LTI object (``scipy.signal.lti``). 38 | 39 | """ 40 | A = np.array([[1., 0.], [1., 1.]]) 41 | B = np.array([[1., -1.], [1., -2.]]) 42 | C = np.array([[0., 1.]]) 43 | D = np.array([[0., 0.]]) 44 | ABCD = np.vstack((np.hstack((A, B)), np.hstack((C, D)))) 45 | H, G = calculateTF(ABCD) 46 | return ABCD, H, G 47 | -------------------------------------------------------------------------------- /deltasigma/_nabsH.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _nabsH.py 3 | # This module provides the nabsH function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the nabsH() function, which computes the negative of 17 | the absolute value of H(z). 18 | """ 19 | 20 | import numpy as np 21 | 22 | from ._evalTF import evalTF 23 | 24 | 25 | def nabsH(w, H): 26 | """Computes the negative of the absolute value of H. 27 | 28 | The computation is performed at the specified angular 29 | frequency ``w``, on the unit circle. 30 | 31 | This function is used by :func:`infnorm`. 32 | """ 33 | z = np.exp(1j*w) 34 | return -np.abs(evalTF(H, z)) 35 | -------------------------------------------------------------------------------- /deltasigma/_padb.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _padb.py 3 | # This module provides the padb function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the padb() function, which pads a matrix on the 17 | bottom. 18 | """ 19 | 20 | import numpy as np 21 | 22 | 23 | def padb(x, n, val=0.): 24 | """Pad a matrix ``x`` on the bottom to length ``n`` with value ``val``. 25 | 26 | **Parameters:** 27 | 28 | x : ndarray 29 | The matrix to be padded. 30 | 31 | n : int 32 | The number of rows of the matrix after padding. 33 | 34 | val : scalar, optional 35 | The value to be used used for padding. 36 | 37 | .. note:: A 1-d array, for example ``a.shape == (N,)`` is reshaped to be 38 | a 1 column array: ``a.reshape((N, 1))`` 39 | 40 | The empty matrix is assumed to be have 1 empty column. 41 | 42 | **Returns:** 43 | 44 | xp : 2-d ndarray 45 | The padded matrix. 46 | """ 47 | if len(x.shape) == 1: 48 | xp = x.reshape((x.shape[0], 1)) 49 | else: 50 | xp = x 51 | y = np.concatenate((xp, 52 | val*np.ones((n - xp.shape[0], xp.shape[1])) 53 | ), axis=0) 54 | return y 55 | -------------------------------------------------------------------------------- /deltasigma/_padl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _padl.py 3 | # This module provides the padl function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the padl() function, which pads a matrix on the 17 | left. 18 | """ 19 | 20 | import numpy as np 21 | 22 | 23 | def padl(x, n, val=0.): 24 | """Pad a matrix ``x`` on the left to length ``n`` with value ``val``. 25 | 26 | **Parameters:** 27 | 28 | x : ndarray 29 | The matrix to be padded. 30 | 31 | n : int 32 | The number of columns of the matrix after padding. 33 | 34 | val : scalar, optional 35 | The value to be used used for padding. 36 | 37 | .. note:: A 1-d array, for example ``a.shape == (N,)`` is reshaped to be 38 | a 1 row array: ``a.reshape((1, N))`` 39 | 40 | The empty matrix is assumed to be have 1 empty row. 41 | 42 | **Returns:** 43 | 44 | xp : 2-d ndarray 45 | The padded matrix. 46 | """ 47 | if len(x.shape) == 1: 48 | xp = x.reshape((1, x.shape[0])) 49 | else: 50 | xp = x 51 | y = np.concatenate(( 52 | val*np.ones((int(xp.shape[0]), int(n - xp.shape[1]))), 53 | xp 54 | ), axis=1) 55 | return y 56 | -------------------------------------------------------------------------------- /deltasigma/_padr.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _padr.py 3 | # This module provides the padr function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the padr() function, which pads a matrix on the 17 | right. 18 | """ 19 | 20 | import numpy as np 21 | 22 | 23 | def padr(x, n, val=0.): 24 | """Pad a matrix ``x`` on the right to length ``n`` with value ``val``. 25 | 26 | **Parameters:** 27 | 28 | x : ndarray 29 | The matrix to be padded. 30 | 31 | n : int 32 | The number of columns of the matrix after padding. 33 | 34 | val : scalar, optional 35 | The value to be used used for padding. 36 | 37 | .. note:: A 1-d array, for example ``a.shape == (N,)`` is reshaped to be 38 | a 1 row array: ``a.reshape((1, N))`` 39 | 40 | The empty matrix is assumed to be have 1 empty row. 41 | 42 | **Returns:** 43 | 44 | xp : 2-d ndarray 45 | The padded matrix. 46 | """ 47 | if len(x.shape) == 1: 48 | xp = x.reshape((1, x.shape[0])) 49 | else: 50 | xp = x 51 | y = np.concatenate( 52 | (xp, 53 | val*np.ones((xp.shape[0], n - xp.shape[1])) 54 | ), axis=1 55 | ) 56 | return y 57 | -------------------------------------------------------------------------------- /deltasigma/_padt.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _padt.py 3 | # This module provides the padt function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the padt() function, which pads a matrix on the 17 | top. 18 | """ 19 | 20 | import numpy as np 21 | 22 | 23 | def padt(x, n, val=0.): 24 | """Pad a matrix ``x`` on the top to length ``n`` with value ``val``. 25 | 26 | **Parameters:** 27 | 28 | x : ndarray 29 | The matrix to be padded. 30 | 31 | n : int 32 | The number of rows of the matrix after padding. 33 | 34 | val : scalar, optional 35 | The value to be used used for padding. 36 | 37 | .. note:: A 1-d array, for example ``a.shape == (N,)`` is reshaped to be 38 | a 1 column array: ``a.reshape((N, 1))`` 39 | 40 | The empty matrix is assumed to be have 1 empty column. 41 | 42 | **Returns:** 43 | 44 | xp : 2-d ndarray 45 | The padded matrix. 46 | """ 47 | if len(x.shape) == 1: 48 | xp = x.reshape((x.shape[0], 1)) 49 | else: 50 | xp = x 51 | y = np.concatenate( 52 | (val*np.ones((int(n - xp.shape[0]), int(xp.shape[1]))), 53 | xp 54 | ), axis=0 55 | ) 56 | return y 57 | -------------------------------------------------------------------------------- /deltasigma/_rms.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _rms.py 3 | # This module provides the rms function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the rms() function, which calculates the Root Mean 17 | Square (RMS) of a vector. 18 | """ 19 | 20 | import numpy as np 21 | import numpy.linalg as la 22 | 23 | 24 | def rms(x, no_dc=False): 25 | """Calculate the RMS value of ``x``. 26 | 27 | The Root Mean Square value of an array :math:`x` of length :math:`n` is defined as: 28 | 29 | .. math:: 30 | 31 | x_{RMS} = \\sqrt{\\frac{1}{n}(x_1^2 + x_2^2 + ...+x_n^2)} 32 | 33 | **Parameters:** 34 | 35 | x : (N,) ndarray 36 | The input vector 37 | 38 | no_dc : boolean, optional 39 | If set to ``True``, the DC value gets subtracted from ``x`` first and the RMS is computed on the result. 40 | 41 | **Returns:** 42 | 43 | xrms : scalar 44 | as defined above 45 | 46 | """ 47 | if no_dc: 48 | x = x - np.mean(x) 49 | return la.norm(x)/np.sqrt(max(x.shape)) 50 | -------------------------------------------------------------------------------- /deltasigma/_rmsGain.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _rmsGain.py 3 | # Module providing the rmsGain function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the rmsGain() function 17 | """ 18 | 19 | import numpy as np 20 | from scipy.linalg import norm 21 | 22 | from ._evalTF import evalTF 23 | 24 | 25 | def rmsGain(H, f1, f2, N=100): 26 | """Compute the root mean-square gain of a discrete-time TF. 27 | 28 | The computation is carried out over the frequency band ``(f1, f2)``, 29 | employing ``N`` discretization steps. 30 | 31 | **Parameters:** 32 | 33 | H : object 34 | The discrete-time transfer function. See :func:`evalTF` for the supported types. 35 | 36 | f1 : scalar 37 | The start value in Hertz of the frequency band over which the gain is evaluated. 38 | 39 | f2 : scalar 40 | The end value (inclusive) in Hertz of the aforementioned frequency band. 41 | 42 | N : integer, optional 43 | The number of discretization points to be taken over specified interval. 44 | 45 | **Returns:** 46 | 47 | Grms : scalar 48 | The root mean-square gain 49 | """ 50 | 51 | w = np.linspace(2*np.pi*f1, 2*np.pi*f2, N) 52 | g = norm(evalTF(H, np.exp(1j*w))) / np.sqrt(N) 53 | 54 | return g 55 | -------------------------------------------------------------------------------- /deltasigma/_simulateQDSM_core.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _simulateQDSM.py 3 | # Module providing the simulateQDSM function 4 | # Copyright 2015 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Module providing the simulateQDSM() core function 17 | """ 18 | 19 | import numpy 20 | cimport numpy as np 21 | import cython 22 | 23 | #@cython.wraparound(False) 24 | #@cython.nonecheck(False) 25 | #@cython.boundscheck(False) 26 | @cython.locals(N=cython.int, k=cython.float, v=np.ndarray, 27 | y=np.ndarray,xn=np.ndarray,xmax=np.ndarray) 28 | 29 | #def simulateQDSM_core(u, A, B, C, D1, order, nlev, nq, x0): 30 | cpdef inline simulateQDSM_core(np.ndarray[complex, ndim=2] u, 31 | np.ndarray[complex, ndim=2] A, 32 | np.ndarray[complex, ndim=2] B, 33 | np.ndarray[complex, ndim=2] C, 34 | np.ndarray[complex, ndim=2] D1, 35 | int order, nlev, int nq, 36 | np.ndarray[complex, ndim=2] x0) 37 | 38 | @cython.locals(v=np.ndarray, ytmp=np.ndarray) 39 | cdef inline ds_qquantize(np.ndarray[complex, ndim=1] y, n) 40 | 41 | -------------------------------------------------------------------------------- /deltasigma/_sinc_decimate.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _sinc_decimate.py 3 | # This module provides the sinc_decimate function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the sinc_decimate() function, which decimates a vector 17 | by a sinc filter of specified order and length. 18 | """ 19 | 20 | from __future__ import division 21 | 22 | import numpy as np 23 | 24 | 25 | def sinc_decimate(x, m, r): 26 | """Decimate ``x`` by an ``m``-th order sinc filter of length ``r``. 27 | """ 28 | x = x[:] 29 | if len(x) < r: 30 | raise ValueError('Filter length longer than input data ( %d > %d )' % 31 | (r, len(x))) 32 | for _ in range(m): 33 | x = np.cumsum(x) 34 | x = np.concatenate((x[:r], x[r:] - x[:-r]), axis=0)/r 35 | return x[r-1::r] 36 | -------------------------------------------------------------------------------- /deltasigma/_thermometer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _thermometer.py 3 | # This module provides the thermometer function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the thermometer() function. 17 | """ 18 | 19 | import numpy as np 20 | 21 | 22 | def thermometer(x, m): 23 | """Convert x to thermometer (aka unary) code 24 | 25 | **Parameters:** 26 | 27 | x : 1-D ndarray 28 | The array of positive ints, each of which will be converted. 29 | 30 | m : int 31 | total length of the thermometer array. 32 | 33 | **Returns:** 34 | 35 | t : ndarray 36 | ``t`` is an m by ``len(x)`` matrix wherein the first 37 | ``x(i)`` components of column ``i`` are one. 38 | """ 39 | t = np.zeros((m, len(x))) 40 | for i in range(len(x)): 41 | t[:x[i], i] = np.ones((x[i], )) 42 | return t 43 | -------------------------------------------------------------------------------- /deltasigma/_undbm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _undbm.py 3 | # This module provides the undbm function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the undbm() function. 17 | """ 18 | 19 | import numpy as np 20 | 21 | from ._utils import carray, restore_input_form, save_input_form 22 | 23 | 24 | def undbm(p, z=50): 25 | """Calculate the RMS voltage equivalent of a power ``p`` expressed in dBm. 26 | 27 | .. math:: 28 | 29 | V_{\\mathrm{RMS}} = \\sqrt{z\\ 10^{p/10 - 3}} 30 | 31 | **Parameters:** 32 | 33 | p : scalar or sequence 34 | The power to be converted. 35 | 36 | z : scalar, optional 37 | The normalization resistance value, defaults to 50 ohm. 38 | 39 | **Returns:** 40 | 41 | Vrms : scalar or sequence 42 | The RMS voltage corresponding to ``p``. 43 | 44 | .. seealso:: :func:`undbp`, :func:`undbv`, :func:`dbm`, :func:`db` 45 | 46 | """ 47 | iform = save_input_form(p) 48 | p = carray(p) 49 | up = np.sqrt(z*10.**(p/10.-3)) 50 | return restore_input_form(up, iform) 51 | -------------------------------------------------------------------------------- /deltasigma/_undbp.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _undbp.py 3 | # This module provides the undbp function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the undbp() function. 17 | """ 18 | from __future__ import division 19 | 20 | import numpy as np 21 | 22 | from ._utils import carray, restore_input_form, save_input_form 23 | 24 | 25 | def undbp(x): 26 | """Convert ``x`` from dB to power. 27 | 28 | The conversion is carried out according to the relationship: 29 | 30 | .. math:: 31 | 32 | P_{\\mathrm{RMS}} = 10^{x/10} 33 | 34 | **Parameters:** 35 | 36 | x : scalar or sequence 37 | The signal in dB to be converted. 38 | 39 | **Returns:** 40 | 41 | Prms : scalar or sequence 42 | The RMS power corresponding to ``x``. 43 | 44 | .. seealso:: :func:`undbm`, :func:`undbv`, :func:`dbp`, :func:`db` 45 | 46 | """ 47 | iform = save_input_form(x) 48 | x = carray(x) 49 | up = 10.**(x/10.) 50 | return restore_input_form(up, iform) 51 | -------------------------------------------------------------------------------- /deltasigma/_undbv.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _undbv.py 3 | # This module provides the undbv function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the undbv() function. 17 | """ 18 | from __future__ import division 19 | 20 | import numpy as np 21 | 22 | from ._utils import carray, restore_input_form, save_input_form 23 | 24 | 25 | def undbv(x): 26 | """Convert ``x`` from dB to voltage. 27 | 28 | The conversion is carried out according to the relationship: 29 | 30 | .. math:: 31 | 32 | V_{\\mathrm{RMS}} = 10^{x/20} 33 | 34 | **Parameters:** 35 | 36 | x : scalar or sequence 37 | The signal in dB to be converted. 38 | 39 | **Returns:** 40 | 41 | Vrms : scalar or sequence 42 | The RMS voltage corresponding to ``x``. 43 | 44 | .. seealso:: :func:`undbm`, :func:`undbp`, :func:`dbv`, :func:`db` 45 | 46 | """ 47 | iform = save_input_form(x) 48 | x = carray(x) 49 | up = 10.**(x/20.) 50 | return restore_input_form(up, iform) 51 | -------------------------------------------------------------------------------- /deltasigma/_zinc.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # _zinc.py 3 | # The zinc function. 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the zinc() function which calculates the magnitude 17 | response of a cascade of comb filters. 18 | """ 19 | 20 | import numpy as np 21 | 22 | 23 | def zinc(f, m=64, n=1): 24 | """Calculate the magnitude response of a cascade of ``n`` ``m``-th order comb filters. 25 | 26 | The magnitude of the filter response is calculated mathematically as: 27 | 28 | .. math:: 29 | 30 | \\left|H(f)\\right| = \\left|\\frac{\\mathrm{sinc}(m f)}{\\mathrm{sinc}(f)}\\right|^n 31 | 32 | **Parameters:** 33 | 34 | f : ndarray 35 | The frequencies at which the magnitude response is evaluated. 36 | 37 | m : int, optional 38 | The order of the comb filters. 39 | 40 | n : int, optional 41 | The number of comb filters in the cascade. 42 | 43 | **Returns:** 44 | 45 | HM : ndarray 46 | The magnitude of the frequency response of the cascade filter. 47 | 48 | """ 49 | return np.fabs(np.sinc(m * f) / np.sinc(f)) ** n 50 | -------------------------------------------------------------------------------- /deltasigma/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/__init__.py -------------------------------------------------------------------------------- /deltasigma/tests/test_SIunits.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_SIunits.py 3 | # This module provides the tests for the SIunits function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the SIunits() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | 22 | from deltasigma import SIunits 23 | 24 | class TestSIunits(unittest.TestCase): 25 | """Test class for SIunits()""" 26 | 27 | def setUp(self): 28 | pass 29 | 30 | def test_SIunits(self): 31 | """Test function for SIunits() 1/2""" 32 | tv = (0, 1, 1e3, 2100312.24, .32545, 21e-9, 34e-12, 9569300e-12) 33 | correct = (0, ''), (1, ''), (1e3, 'k'), (1e6, 'M'), (1e-3, 'm'), \ 34 | (1e-9, 'n'), (1e-12, 'p'), (1e-6, 'u') 35 | f, p = SIunits(tv) 36 | res = zip(f,p) 37 | for r, c in zip(res, correct): 38 | self.assertTrue(r[0] == c[0] and r[1] == c[1]) 39 | 40 | def test_SIunits_2(self): 41 | """Test function for SIunits() 2/2""" 42 | # test scalars 43 | tv = 2100312.24 44 | correct = (1e6, 'M') 45 | f, p = SIunits(tv) 46 | self.assertTrue(f == correct[0] and p == correct[1]) 47 | 48 | -------------------------------------------------------------------------------- /deltasigma/tests/test_axisLabels.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import numpy as np 3 | import deltasigma as ds 4 | 5 | # from nose.tools import raises 6 | 7 | class TestAxisLabels(unittest.TestCase): 8 | """Test function for axisLabels()""" 9 | def setUp(self): 10 | self.ran = np.arange(100) 11 | 12 | def test_axis_label_geneation_part1(self): 13 | """Test function for axisLabels() 1/3""" 14 | ss = ds.axisLabels(self.ran, incr=10) 15 | r = ['0', '10', '20', '30', '40', '50', '60', '70', '80', '90'] 16 | self.assertTrue(r == ss) 17 | 18 | def test_axis_label_generation_part2(self): 19 | """Test function for axisLabels() 2/3""" 20 | ss = ds.axisLabels(self.ran, incr=(15, 10)) 21 | r = ['10', '25', '40', '55', '70', '85'] 22 | self.assertTrue(r == ss) 23 | 24 | # @raises(ValueError) 25 | def test_axis_label_incr_length(self): 26 | """Test function for axisLabels() 3/3""" 27 | with self.assertRaises(ValueError): 28 | ds.axisLabels([1., 2., 3., 4.], [1, 2, 3]) 29 | 30 | -------------------------------------------------------------------------------- /deltasigma/tests/test_bilogplot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_bilogplot.py 3 | # Test module for the bilogplot function 4 | # Copyright 2013 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """Test module for the bilogplot function 17 | """ 18 | 19 | from __future__ import division 20 | 21 | import unittest 22 | import numpy as np 23 | import matplotlib.pyplot as plt 24 | import deltasigma as ds 25 | 26 | class TestBiLogPlot(unittest.TestCase): 27 | """Test function for bilogplot()""" 28 | 29 | def setUp(self): 30 | pass 31 | 32 | def test_bilogplot(self): 33 | """Test function for bilogplot()""" 34 | f0 = 1./8 35 | OSR = 64 36 | order = 8 37 | N = 8192 38 | H = ds.synthesizeNTF(order, OSR, 1, 1.5, f0) 39 | fB = int(np.ceil(N/(2. * OSR))) 40 | ftest = int(np.round(f0*N + 1./3 * fB)) 41 | u = 0.5*np.sin(2*np.pi*ftest/N*np.arange(N)) 42 | v, xn, xmax, y = ds.simulateDSM(u, H) 43 | spec = np.fft.fft(v*ds.ds_hann(N))/(N/4) 44 | X = spec[:N//2 + 1] 45 | plt.figure() 46 | # graphical function: we check it doesn't fail 47 | ds.bilogplot(X, int(f0*N), ftest, (.03, .3, .3), (-140, 0, 10, 20)) 48 | -------------------------------------------------------------------------------- /deltasigma/tests/test_bplogsmooth.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | import unittest 3 | import numpy as np 4 | import deltasigma as ds 5 | import scipy.io 6 | import pkg_resources 7 | from deltasigma._utils import mround 8 | 9 | 10 | class TestBplogsmooth(unittest.TestCase): 11 | """Test class for bplogsmooth()""" 12 | 13 | def setUp(self): 14 | fname = pkg_resources.resource_filename( 15 | __name__, "test_data/test_bplogsmooth.mat") 16 | self.data = scipy.io.loadmat(fname) 17 | f0 = 1./8 18 | OSR = 64 19 | order = 8 20 | N = 8192 21 | H = ds.synthesizeNTF(order, OSR, 1, 1.5, f0) 22 | fB = int(np.ceil(N/(2. * OSR))) 23 | ftest = int(mround(f0*N + 1./3*fB)) 24 | u = 0.5*np.sin(2*np.pi*ftest/N*np.arange(N)) 25 | v, xn, xmax, y = ds.simulateDSM(u, H) 26 | spec = np.fft.fft(v*ds.ds_hann(N))/(N/4) 27 | X = spec[:N//2 + 1] 28 | self.f, self.p = ds.bplogsmooth(X, ftest, f0) 29 | 30 | def test_one(self): 31 | """Test function 1/2 for bplogsmooth()""" 32 | data = self.data 33 | f = self.f 34 | self.assertTrue(np.allclose(f, data['f'], atol=1e-9, rtol=1e-5)) 35 | 36 | def test_two(self): 37 | """Test function 2/2 for bplogsmooth()""" 38 | data = self.data 39 | p = self.p 40 | self.assertTrue(np.allclose(p, data['p'], atol=1e-9, rtol=1e-5)) 41 | -------------------------------------------------------------------------------- /deltasigma/tests/test_bquantize.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_bquantize.py 3 | # Bipolar quantization test module 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This is the test module for bquantize()""" 17 | 18 | from __future__ import division, print_function 19 | import unittest 20 | import numpy as np 21 | import deltasigma as ds 22 | import scipy.io 23 | import pkg_resources 24 | 25 | 26 | class TestBQuantize(unittest.TestCase): 27 | """Test class for bquantize()""" 28 | def setUp(self): 29 | self.ran = np.arange(100) 30 | 31 | def test_bquantize(self): 32 | """Test function for bquantize() 33 | """ 34 | x = np.linspace(-10, 10, 101) 35 | y = ds.bquantize(x) 36 | yval = [yi.val for yi in y] 37 | ycsd = [yi.csd for yi in y] 38 | fname = pkg_resources.resource_filename(__name__, "test_data/test_bquantize.mat") 39 | s = scipy.io.loadmat(fname)['s'] 40 | mval = [] 41 | mcsd = [] 42 | for i in range(s.shape[1]): 43 | mval.append(float(s[0, i][0])) 44 | mcsd.append(s[0, i][1]) 45 | for i in range(len(mval)): 46 | self.assertTrue(np.allclose(mval[i], yval[i], atol=1e-8, rtol=1e-5)) 47 | self.assertTrue(np.prod(mcsd[i].shape) + np.prod(ycsd[i].shape) == 0 or \ 48 | mcsd[i].shape == ycsd[i].shape) 49 | if 0 not in ycsd[i].shape: 50 | self.assertTrue(np.allclose(mcsd[i], ycsd[i], atol=1e-8, rtol=1e-5)) 51 | 52 | -------------------------------------------------------------------------------- /deltasigma/tests/test_bunquantize.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_bunquantize.py 3 | # This module provides the tests for the bunquantize function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the bunquantize() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | import deltasigma as ds 22 | 23 | class TestBUnQuantize(unittest.TestCase): 24 | """Test class for bunquantize()""" 25 | def setUp(self): 26 | self.x = np.linspace(-10, 10, 101) 27 | 28 | def test_bunquantize(self): 29 | """Test function for bunquantize() 1/3""" 30 | yr = ds.bquantize(self.x) 31 | yv = [] 32 | y = [] 33 | for yi in yr: 34 | y += [yi.csd] 35 | yv += [yi.val] 36 | yv = np.asarray(yv) 37 | xres = ds.bunquantize(y) 38 | self.assertTrue(np.allclose(xres, yv, atol=1e-8, rtol=1e-5)) 39 | 40 | -------------------------------------------------------------------------------- /deltasigma/tests/test_calculateSNR.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_calculateSNR.py 3 | # This module provides the tests for the calculateSNR() function. 4 | # Copyright 2014 Giuseppe Venturini & Shayne Hodge 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | import unittest 17 | import numpy as np 18 | import deltasigma as ds 19 | from numpy.fft import fft 20 | from deltasigma._ds_hann import ds_hann 21 | 22 | 23 | class TestCalculateSNR(unittest.TestCase): 24 | """Test function for calculateSNR()""" 25 | def setUp(self): 26 | N = 2**12 27 | t = np.arange(N) 28 | (f1, f2) = (1.0/8, 1.0/302) 29 | A = np.cos(2*np.pi*f1*t) 30 | B = 0.01*np.cos(2*np.pi*f2*t) 31 | y = A + B 32 | window = ds_hann(N) 33 | self.hwfft = fft(window*y) 34 | self.N = N 35 | self.f1 = f1 36 | 37 | def test_snr_is_40(self): 38 | """ Test that a particular SNR is within roundings errors of 39 | 40 (dB?) """ 40 | N = self.N 41 | snr = ds.calculateSNR(self.hwfft[:N//2], int(N*self.f1)) 42 | # Consider replacing with assertAlmostEqual 43 | self.assertTrue(np.allclose(snr, 40, atol=1e-8, rtol=1e-8)) 44 | 45 | def test_snr_is_inf(self): 46 | """ Test that a paricular SNR is infinite. """ 47 | N = self.N 48 | hwfft = np.zeros((N//2, )) 49 | hwfft[512] = 1.0 # specially crafted to have Inf snr 50 | snr = ds.calculateSNR(hwfft[:N//2], 512) 51 | self.assertEqual(snr, np.Inf) 52 | -------------------------------------------------------------------------------- /deltasigma/tests/test_circ_smooth.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_circ_smooth.py 3 | # This module provides the tests for the circ_smooth() function. 4 | # Copyright 2014 Giuseppe Venturini & Shayne Hodge 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | import unittest 17 | import numpy as np 18 | import deltasigma as ds 19 | import pkg_resources 20 | from scipy.io import loadmat 21 | from os.path import join 22 | 23 | 24 | class TestCircSmooth(unittest.TestCase): 25 | """Test function for circ_smooth()""" 26 | 27 | def setUp(self): 28 | file_path = join('test_data', 'test_circ_smooth.mat') 29 | fname = pkg_resources.resource_filename(__name__, file_path) 30 | self.bt = loadmat(fname)['b'] 31 | 32 | def test_circ_smooth(self): 33 | A = np.arange(1, 101) 34 | b = ds.circ_smooth(A, 16) 35 | self.assertTrue(np.allclose(self.bt, b, atol=1e-8, rtol=1e-5)) 36 | -------------------------------------------------------------------------------- /deltasigma/tests/test_clans.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_clans.py 3 | # This module provides the tests for the clans() function. 4 | # Copyright 2014 Giuseppe Venturini & Shayne Hodge 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | import unittest 17 | import numpy as np 18 | import deltasigma as ds 19 | 20 | 21 | class TestClans(unittest.TestCase): 22 | """Class doc string""" 23 | def setUp(self): 24 | self.ntf = ds.clans(5, 32, 5, .95, 1) 25 | self.poles = np.array((0.41835234+0.0j, 0.48922229+0.1709716j, 26 | 0.48922229-0.1709716j, 0.65244885+0.3817224j, 27 | 0.65244885-0.3817224j)) 28 | 29 | def test_clans(self): 30 | """Test function for clans()""" 31 | self.assertTrue( 32 | np.allclose(self.poles, self.ntf[1], atol=1e-8, rtol=1e-5)) 33 | -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_bplogsmooth.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_bplogsmooth.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_bquantize.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_bquantize.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_bquantize.txt: -------------------------------------------------------------------------------- 1 | % The mat file test_bquantize.mat contains the variable s, \ 2 | % computed with: 3 | 4 | b = linspace(-10,10,101); 5 | s = bquantize(b); 6 | -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_circ_smooth.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_circ_smooth.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_circ_smooth.txt: -------------------------------------------------------------------------------- 1 | The variable b was obtained running: 2 | 3 | A = 1:100; 4 | b = circ_smooth(A, 16); 5 | 6 | And exporting b in .mat format. 7 | -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_ds_optzeros.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_ds_optzeros.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_ds_optzeros.txt: -------------------------------------------------------------------------------- 1 | The file test_ds_optzeros.mat was generated with the following code: 2 | 3 | res = struct(); 4 | for j=1:14, 5 | field = strcat('n', int2str(j)); 6 | a = [] 7 | for opt=0:2, 8 | a = [a, ds_optzeros(j, opt)]; 9 | res.(field) = a; 10 | end 11 | end 12 | 13 | And then exporting the variable res. 14 | -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_dsdemo3.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_dsdemo3.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_logsmooth.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_logsmooth.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_peak_snr.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_peak_snr.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_pulse.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_pulse.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_pulse.txt: -------------------------------------------------------------------------------- 1 | % The mat file test_pulse.mat contains the variable pp, \ 2 | % computed with output of: 3 | 4 | H = tf([1], [1 2 10]) 5 | pp = pulse(ss(H), [0. 1], .1, 10) 6 | -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_simulateDSM.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_simulateDSM.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_simulateDSM.txt: -------------------------------------------------------------------------------- 1 | OSR = 32; 2 | H = synthesizeNTF(5, OSR, 10) 3 | N = 8192; 4 | f = 85; 5 | t = 0:N-1; 6 | u = 0.5*sin(2*pi*f/N*t); 7 | [a g b c] = realizeNTF(H, 'CRFB') 8 | ABCD = stuffABCD(a, g, b, c, 'CRFB') 9 | [v xn xmax y] = simulateDSM(u, ABCD, 10); 10 | poles = H.p{:} 11 | zeros = H.z{:} 12 | -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_simulateSNR.m: -------------------------------------------------------------------------------- 1 | % the file test_snr_data2.mat may be generated with the following: 2 | clear; clc; 3 | order = 3; 4 | osr = 256; 5 | nlev = 2; 6 | f0 = 0.; 7 | Hinf = 1.25; 8 | form = 'CIFB'; 9 | 10 | ntf = synthesizeNTF(order, osr, 2, Hinf, f0); 11 | [a1 g1 b1 c1] = realizeNTF(ntf, form); 12 | ABCD = stuffABCD(a1, g1, b1, c1, form); 13 | [snr amp] = simulateSNR(ABCD, osr, [], f0, nlev) 14 | % saving ABCD, snr, amp -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_snr_amp.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_snr_amp.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_snr_amp.txt: -------------------------------------------------------------------------------- 1 | % code to generate snr, amp, snr_user, amp_user 2 | clc 3 | clear * 4 | stf = [] 5 | % Design parameters 6 | order = 4; 7 | osr = 256; 8 | nlev = 2; 9 | f0 = 0.22; 10 | Hinf = 1.25; 11 | form = 'CRFB'; 12 | 13 | ntf = synthesizeNTF(order,osr,2,Hinf,f0); 14 | [a1,g1,b1,c1] = realizeNTF(ntf,form); 15 | ABCD = stuffABCD(a1, g1, b1, c1, form); 16 | [a2,g2,b2,c2] = mapABCD(ABCD, form); 17 | 18 | [snr, amp] = simulateSNR(ABCD, osr, [], f0, nlev); 19 | amp_user = linspace(-100, 0, 200); 20 | [snr_user, amp_user] = simulateSNR(ABCD, osr, amp_user, f0, nlev) 21 | %[snr2, amp2] = simulateSNR(ntf, osr, [], f0, nlev) 22 | -------------------------------------------------------------------------------- /deltasigma/tests/test_data/test_snr_amp2.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/deltasigma/tests/test_data/test_snr_amp2.mat -------------------------------------------------------------------------------- /deltasigma/tests/test_dbm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_dbm.py 3 | # This module provides the tests for the dbm function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the dbm() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | 22 | from deltasigma import dbm 23 | 24 | class TestDbm(unittest.TestCase): 25 | """Test class for dbm()""" 26 | def setUp(self): 27 | self.v1 = np.arange(10) * 1e-3 # test arrays 28 | self.r1 = [-np.inf, -46.98970004, -40.96910013, -37.44727495, -34.94850022, 29 | -33.01029996, -31.42667504, -30.08773924, -28.9279003, -27.90484985] 30 | self.v2 = 9e-3 # test scalars. 31 | self.r2 = -27.90484985 32 | 33 | def test_dbm_1(self): 34 | """Test function for dbm() 1/2""" 35 | self.assertTrue(np.allclose(dbm(self.v1), self.r1, atol=1e-8, rtol=1e-5)) 36 | 37 | def test_dbm_2(self): 38 | """Test function for dbm() 2/2""" 39 | self.assertTrue(np.allclose(dbm(self.v2), self.r2, atol=1e-8, rtol=1e-5)) 40 | self.assertTrue(np.isscalar(dbm(self.v2))) 41 | 42 | -------------------------------------------------------------------------------- /deltasigma/tests/test_dbp.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_dbp.py 3 | # This module provides the tests for the dbp function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the dbp() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | 22 | from deltasigma import dbp 23 | 24 | class TestDbp(unittest.TestCase): 25 | """Test class for dbp()""" 26 | def setUp(self): 27 | self.tv1 = np.array([2]) 28 | self.r1 = np.array([3.01029996]) 29 | self.tv2 = 2 30 | self.r2 = 3.01029996 31 | self.tv3 = 2, 2 32 | self.r3 = 3.01029996, 3.01029996 33 | 34 | def test_dbp_1(self): 35 | """Test function for dbp() 1/3""" 36 | res = dbp(self.tv1) 37 | self.assertTrue(np.allclose(self.r1, res, atol=1e-8, rtol=1e-5)) 38 | 39 | def test_dbp_2(self): 40 | """Test function for dbp() 2/3""" 41 | res = dbp(self.tv2) 42 | self.assertTrue(np.allclose(self.r2, res, atol=1e-8, rtol=1e-5)) 43 | self.assertTrue(np.isscalar(res)) # check for type coherence 44 | 45 | def test_dbp_3(self): 46 | """Test function for dbp() 3/3""" 47 | res = dbp(self.tv3) 48 | self.assertTrue(np.allclose(self.r3, res, atol=1e-8, rtol=1e-5)) 49 | 50 | -------------------------------------------------------------------------------- /deltasigma/tests/test_dbv.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_dbv.py 3 | # This module provides the tests for the dbv function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the dbv() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | 22 | from deltasigma import dbv, undbv 23 | 24 | class TestDbv(unittest.TestCase): 25 | """Test class for dbv()""" 26 | def setUp(self): 27 | self.t1 = np.array([3.0]) 28 | self.r1 = 9.5424250943932485 29 | 30 | def test_dbv(self): 31 | """Test function for dbv()""" 32 | res = dbv(self.t1) 33 | t2 = undbv(res) 34 | self.assertTrue(np.allclose(t2, self.t1, atol=1e-8, rtol=1e-5)) 35 | self.assertTrue(np.allclose(res, self.r1, atol=1e-8, rtol=1e-5)) 36 | 37 | -------------------------------------------------------------------------------- /deltasigma/tests/test_ds_f1f2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_ds_f1f2.py 3 | # This module provides the tests for the ds_f1f2 function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the ds_f1f2() function. 17 | """ 18 | 19 | import unittest 20 | import deltasigma as ds 21 | 22 | class TestDs_f1f2(unittest.TestCase): 23 | """Test class for ds_f1f2()""" 24 | def setUp(self): 25 | self.f0 = 1e3 26 | self.OSR = 128 27 | self.cf = False 28 | 29 | def test_ds_f1f2_1(self): 30 | """Test function for ds_f1f2() 1/3""" 31 | t1f1, t1f2 = ds.ds_f1f2(self.OSR, self.f0, self.cf) 32 | self.assertTrue((t1f1, t1f2) == (self.f0 - 0.25/self.OSR, self.f0 + 0.25/self.OSR)) 33 | 34 | def test_ds_f1f2_2(self): 35 | """Test function for ds_f1f2() 2/3""" 36 | t2f1, t2f2 = ds.ds_f1f2(self.OSR, self.f0, not self.cf) 37 | self.assertTrue((t2f1, t2f2) == (self.f0 - 0.5/self.OSR, self.f0 + 0.5/self.OSR)) 38 | 39 | def test_ds_f1f2_3(self): 40 | """Test function for ds_f1f2() 3/3""" 41 | t3f1, t3f2 = ds.ds_f1f2(self.OSR, .24/self.OSR, self.cf) 42 | self.assertTrue((t3f1, t3f2) == (0., 0.5/self.OSR)) 43 | -------------------------------------------------------------------------------- /deltasigma/tests/test_ds_hann.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_ds_hann.py 3 | # This module provides the tests for the ds_hann() function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the ds_hann() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | import deltasigma as ds 22 | 23 | class TestDs_Hann(unittest.TestCase): 24 | """Test class for ds_hann()""" 25 | def setUp(self): 26 | self.res = np.array([0. , 0.02148628, 0.06768441, 0.09549150, 27 | 0.06533781, -0.03015369, -0.1545085 , -0.24133259, 28 | -0.22851372, -0.0954915 ]) 29 | 30 | def test_ds_hann(self): 31 | """Test function for ds_hann()""" 32 | self.assertTrue(np.allclose(self.res, np.hanning(10) - ds.ds_hann(10), atol=1e-8, rtol=1e-5)) 33 | 34 | 35 | -------------------------------------------------------------------------------- /deltasigma/tests/test_ds_optzeros.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_ds_optzeros.py 3 | # This module provides the tests for the ds_freq() function. 4 | # Copyright 2014 Giuseppe Venturini & Shayne Hodge 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | import unittest 17 | import numpy as np 18 | import deltasigma as ds 19 | import pkg_resources 20 | import scipy.io 21 | from os.path import join 22 | 23 | 24 | class TestDSOptZeros(unittest.TestCase): 25 | """Test function for ds_optzeros()""" 26 | 27 | def setUp(self): 28 | file_path = join('test_data', 'test_ds_optzeros.mat') 29 | fname = pkg_resources.resource_filename(__name__, file_path) 30 | self.res = scipy.io.loadmat(fname)['res'] 31 | 32 | def test_opt_zeros(self): 33 | """ Test 14 different optzeros() calls. """ 34 | ns = ('n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9', 'n10', 35 | 'n11', 'n12', 'n13', 'n14') 36 | 37 | for i, n in enumerate(ns): 38 | for opt in (0, 1, 2): 39 | self.assertTrue( 40 | np.allclose( 41 | self.res[n][0][0][:, opt], ds.ds_optzeros(i+1, opt), 42 | atol=1e-10, rtol=1e-6)) 43 | -------------------------------------------------------------------------------- /deltasigma/tests/test_ds_synNTFobj1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_ds_synNTFobj1.py 3 | # This module provides the tests for the ds_synNTFobj1() function. 4 | # Copyright 2014 Giuseppe Venturini & Shayne Hodge 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | import unittest 17 | import numpy as np 18 | import deltasigma as ds 19 | 20 | 21 | class TestDSSynNTFObj1(unittest.TestCase): 22 | """Test functions for ds_synNTFobj1()""" 23 | 24 | def setUp(self): 25 | pass 26 | 27 | def test_ds_synNTFobj1_1(self): 28 | """Test function for ds_synNTFobj1() 1/2""" 29 | res = -27.167735573627283 30 | tv = ds.ds_synNTFobj1(.5, (.9, 2), 64, .1) 31 | self.assertTrue(np.allclose((res,), (tv, ), atol=1e-8, rtol=1e-5)) 32 | 33 | def test_ds_synNTFobj1_2(self): 34 | """Test function for ds_synNTFobj1() 2/2""" 35 | res = -43.0365 36 | tv = ds.ds_synNTFobj1(.5, (.9, 2), 64, 0.) 37 | self.assertTrue(np.allclose((res,), (tv, ), atol=1e-8, rtol=1e-5)) 38 | 39 | -------------------------------------------------------------------------------- /deltasigma/tests/test_evalF1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_evalF1.py 3 | # This module provides the tests for the evalF1 function. 4 | # Copyright 2014 Giuseppe Venturini and Shayne Hodge 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the evalF1() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | 22 | from deltasigma import evalF1 23 | 24 | class TestEvalF1(unittest.TestCase): 25 | """Test class for evalF1()""" 26 | 27 | def setUp(self): 28 | pass 29 | 30 | def test_evalF1_1(self): 31 | """Test function for evalF1() 1/2""" 32 | r = evalF1([0.5, 1, 1.5, 2, 5, 10, 20, 30, 40.7, 50], 2, 23) 33 | ref = 0.544143311383570 34 | self.assertTrue(np.allclose((r,), (ref,))) 35 | 36 | def test_evalF1_2(self): 37 | """Test function for evalF1() 2/2""" 38 | r = evalF1([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0.135) 39 | ref = 0.640058615996223 40 | self.assertTrue(np.allclose((r,), (ref,))) 41 | 42 | -------------------------------------------------------------------------------- /deltasigma/tests/test_evalRPoly.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_evalRPoly.py 3 | # This module provides the tests for the evalRPoly function. 4 | # Copyright 2014 Giuseppe Venturini & Shayne Hodge 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | import unittest 17 | import numpy as np 18 | import deltasigma as ds 19 | 20 | class TestEvalRPoly(unittest.TestCase): 21 | """Test function for evalRPoly()""" 22 | def setUp(self): 23 | pass 24 | 25 | def test_evalRPoly(self): 26 | """test_evalRPoly""" 27 | x = np.arange(1001) - 500 28 | a = [1, 0, 1, 2] 29 | r1 = np.polyval(a, x) 30 | rts = np.roots(a) 31 | r2 = ds.evalRPoly(rts, x) 32 | self.assertTrue(np.allclose(r1, r2, atol=1e-8, rtol=1e-5)) 33 | -------------------------------------------------------------------------------- /deltasigma/tests/test_figureMagic.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_figureMagic.py 3 | # This module provides the tests for the figureMagic function. 4 | # Copyright 2014 Giuseppe Venturini & Shayne Hodge 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | import unittest 17 | import numpy as np 18 | import deltasigma as ds 19 | import matplotlib.pyplot as plt 20 | 21 | 22 | class TestFigureMagic(unittest.TestCase): 23 | """Test functions for figureMagic()""" 24 | 25 | def setUp(self): 26 | pass 27 | 28 | def test_figureMagic(self): 29 | """test plotting - None should be returned.""" 30 | a = np.arange(10) 31 | plt.figure() 32 | plt.plot(a) 33 | self.assertIsNone( 34 | ds.figureMagic( 35 | xRange=[1, 10], dx=1, xLab=None, yRange=[2, 8], dy=.5, 36 | yLab=None, size=(10, 6), name="Test plot")) 37 | -------------------------------------------------------------------------------- /deltasigma/tests/test_infnorm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_infnorm.py 3 | # This module provides the tests for the infnorm function. 4 | # Copyright 2014 Giuseppe Venturini & Shayne Hodge 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | import unittest 17 | import numpy as np 18 | import deltasigma as ds 19 | 20 | 21 | class TestInfNorm(unittest.TestCase): 22 | """Test functions for figureMagic()""" 23 | def setUp(self): 24 | num, den = np.poly([3, 0.3, 1]), np.poly([2, 0.5, .25]) 25 | H = (num, den) 26 | self.Hinf, self.fmax = ds.infnorm(H) 27 | 28 | def test_infnorm_Hinf(self): 29 | """Test function for infnorm() checking Hinf""" 30 | self.assertTrue(np.allclose( 31 | self.Hinf, 1.84888889, atol=1e-8, rtol=1e-5)) 32 | 33 | def test_infnorm_fmax(self): 34 | """Test function for infnorm() checking fmax""" 35 | self.assertTrue(np.allclose( 36 | self.fmax, 3.141592653589793/2.0/np.pi, atol=1e-8, rtol=1e-5)) 37 | -------------------------------------------------------------------------------- /deltasigma/tests/test_lollipop.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_lollipop.py 3 | # This module provides the tests for the lollipop function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the lollipop() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | #import pylab as plt 22 | import matplotlib.pyplot as plt 23 | 24 | from warnings import catch_warnings 25 | 26 | from deltasigma import lollipop 27 | 28 | class TestLollipop(unittest.TestCase): 29 | """Test class for lollipop()""" 30 | 31 | def setUp(self): 32 | pass 33 | 34 | def test_lollipop(self): 35 | """Test function for lollipop()""" 36 | t = np.arange(1, 20)*1e-3 37 | f = 20. 38 | a = np.sin(2*np.pi*f*t) 39 | plt.figure() 40 | with catch_warnings(record=True) as w: 41 | lollipop(t, a, color=None, lw=1.5, ybot=0.1) 42 | self.assertTrue(len(w) > 0) 43 | 44 | -------------------------------------------------------------------------------- /deltasigma/tests/test_mapRtoQ.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_mapRtoQ.py 3 | # This module provides the tests for the mapRtoQ function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the mapRtoQ() function. 17 | """ 18 | 19 | from __future__ import division 20 | 21 | import unittest 22 | import numpy as np 23 | import deltasigma as ds 24 | 25 | class TestMapRtoQ(unittest.TestCase): 26 | """Test class for mapRtoQ()""" 27 | 28 | def setUp(self): 29 | self.test_matrix = np.arange(1, 25).reshape((4, 6)).T 30 | self.dq = np.array([[4.5 - 2.5j, 16.5 - 2.5j], 31 | [6.5 - 2.5j, 18.5 - 2.5j], 32 | [8.5 - 2.5j, 20.5 - 2.5j]]) 33 | self.dp = np.array([[-3.5 + 4.5j, -3.5 + 16.5j], 34 | [-3.5 + 6.5j, -3.5 + 18.5j], 35 | [-3.5 + 8.5j, -3.5 + 20.5j]]) 36 | 37 | def test_mapRtoQ(self): 38 | """Test function for mapRtoQ()""" 39 | resq, resp = ds.mapRtoQ(self.test_matrix) 40 | self.assertTrue(np.allclose(resq, self.dq, atol=1e-8, rtol=1e-5)) 41 | self.assertTrue(np.allclose(resp, self.dp, atol=1e-8, rtol=1e-5)) 42 | 43 | -------------------------------------------------------------------------------- /deltasigma/tests/test_mod1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_mod1.py 3 | # This module provides the tests for the mod1 function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the mod1() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | import deltasigma as ds 22 | 23 | class Testmod1(unittest.TestCase): 24 | """Test class for mod1()""" 25 | 26 | def setUp(self): 27 | self.ABCDmod1 = [[1., 1., -1.], [1., 0., 0.]] 28 | 29 | def test_mod1(self): 30 | """Test function for mod1()""" 31 | ABCD, ntf, stf = ds.mod1() 32 | self.assertTrue(np.allclose(ABCD, self.ABCDmod1, atol=1e-8, rtol=1e-5)) 33 | 34 | -------------------------------------------------------------------------------- /deltasigma/tests/test_mod2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_mod2.py 3 | # This module provides the tests for the mod2 function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the mod2() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | import deltasigma as ds 22 | 23 | class TestMod2(unittest.TestCase): 24 | """Test class for mod2()""" 25 | 26 | def setUp(self): 27 | self.ABCDmod2 = [[1., 0., 1., -1.], 28 | [1., 1., 1., -2.], 29 | [0., 1., 0., 0.]] 30 | 31 | def test_mod2(self): 32 | """Test function for mod2()""" 33 | ABCD, ntf, stf = ds.mod2() 34 | self.assertTrue(np.allclose(ABCD, self.ABCDmod2, atol=1e-8, 35 | rtol=1e-5)) 36 | 37 | -------------------------------------------------------------------------------- /deltasigma/tests/test_nabsH.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_nabsH.py 3 | # This module provides the tests for the nabsH function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the nabsH() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | import deltasigma as ds 22 | 23 | #from nose.tools import raises 24 | 25 | class TestNabsH(unittest.TestCase): 26 | """Test class for nabsH()""" 27 | 28 | def setUp(self): 29 | pass 30 | 31 | def test_nabsH(self): 32 | """Test function for nabsH()""" 33 | H = ([1, 2], [2, 0, .25], 1) 34 | N = 129 35 | w = np.linspace(0, 2*np.pi, num=N, endpoint=True) 36 | z = np.exp(1j*w) 37 | r1 = -np.abs(ds.evalTF(H, z)) 38 | r2 = ds.nabsH(w, H) 39 | self.assertTrue(np.allclose(r1, r2, atol=1e-8, rtol=1e-5)) 40 | 41 | -------------------------------------------------------------------------------- /deltasigma/tests/test_padb.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_padb.py 3 | # This module provides the tests for the padb function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the padb() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | from deltasigma import padb 22 | 23 | class TestPadb(unittest.TestCase): 24 | """Test class for padb()""" 25 | def setUp(self): 26 | self.tv1 = np.eye(15) 27 | self.tv2 = np.arange(10) 28 | self.tv3 = np.array([]) 29 | 30 | def test_padb_1(self): 31 | """Test function for padb() 1/3""" 32 | # regular matrix 33 | tr = padb(self.tv1, n=25, val=2) 34 | res = np.concatenate((self.tv1, 2.*np.ones((10, 15))), axis=0) 35 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 36 | 37 | def test_padb_2(self): 38 | """Test function for padb() 2/3""" 39 | # 1-d array 40 | tr = padb(self.tv2, n=25, val=1.5) 41 | res = np.vstack((self.tv2.reshape((-1, 1)), 1.5*np.ones((15, 1)))) 42 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 43 | 44 | def test_padb_3(self): 45 | """Test function for padb() 3/3""" 46 | # empty matrix array 47 | tr = padb(self.tv3, n=25, val=1.5) 48 | res = np.vstack((self.tv3.reshape((-1, 1)), 1.5*np.ones((25, 1)))) 49 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 50 | 51 | -------------------------------------------------------------------------------- /deltasigma/tests/test_padl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_padl.py 3 | # This module provides the tests for the padl function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the padl() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | from deltasigma import padl 22 | 23 | class TestPadl(unittest.TestCase): 24 | """Test class for padl()""" 25 | 26 | def setUp(self): 27 | self.tv1 = np.eye(15) 28 | self.tv2 = np.arange(10) 29 | self.tv3 = np.array([]) 30 | 31 | def test_padl_1(self): 32 | """Test function for padl() 1/3""" 33 | tr = padl(self.tv1, n=25, val=2) 34 | res = np.concatenate((2.*np.ones((15, 10)), self.tv1), axis=1) 35 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 36 | 37 | def test_padl_2(self): 38 | """Test function for padl() 2/3""" 39 | # 1-d array 40 | tr = padl(self.tv2, n=25, val=1.5) 41 | res = np.hstack((1.5*np.ones((1, 15)), self.tv2.reshape((1, -1)))) 42 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 43 | 44 | def test_padl_3(self): 45 | """Test function for padl() 3/3""" 46 | # empty matrix array 47 | tr = padl(self.tv3, n=25, val=1.5) 48 | res = np.hstack((1.5*np.ones((1, 25)), self.tv3.reshape((1, -1)))) 49 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 50 | 51 | -------------------------------------------------------------------------------- /deltasigma/tests/test_padr.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_padr.py 3 | # This module provides the tests for the padr function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the padr() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | from deltasigma import padr 22 | 23 | class TestPadr(unittest.TestCase): 24 | """Test class for padr()""" 25 | def setUp(self): 26 | self.tv1 = np.eye(15) 27 | self.tv2 = np.arange(10) 28 | self.tv3 = np.array([]) 29 | 30 | def test_padr_1(self): 31 | """Test function for padr() 1/3""" 32 | tr = padr(self.tv1, n=25, val=2) 33 | res = np.concatenate((self.tv1, 2.*np.ones((15, 10))), axis=1) 34 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 35 | 36 | def test_padr_2(self): 37 | """Test function for padr() 2/3""" 38 | # 1-d array 39 | tr = padr(self.tv2, n=25, val=1.5) 40 | res = np.hstack((self.tv2.reshape((1, -1)), 1.5*np.ones((1, 15)))) 41 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 42 | 43 | def test_padr_3(self): 44 | """Test function for padr() 3/3""" 45 | # empty matrix array 46 | tr = padr(self.tv3, n=25, val=1.5) 47 | res = np.hstack((self.tv3.reshape((1, -1)), 1.5*np.ones((1, 25)))) 48 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 49 | 50 | -------------------------------------------------------------------------------- /deltasigma/tests/test_padt.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_padt.py 3 | # This module provides the tests for the padt function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the padt() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | 22 | from deltasigma import padt 23 | 24 | class TestPadt(unittest.TestCase): 25 | """Test class for padt()""" 26 | def setUp(self): 27 | self.tv1 = np.eye(15) 28 | self.tv2 = np.arange(10) 29 | self.tv3 = np.array([]) 30 | 31 | def test_padt_1(self): 32 | """Test function for padt() 1/3""" 33 | tr = padt(self.tv1, n=25, val=2) 34 | res = np.concatenate((2.*np.ones((10, 15)), self.tv1), axis=0) 35 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 36 | 37 | def test_padt_2(self): 38 | """Test function for padt() 2/3""" 39 | # 1-d array 40 | tr = padt(self.tv2, n=25, val=1.5) 41 | res = np.vstack((1.5*np.ones((15, 1)), self.tv2.reshape((-1, 1)))) 42 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 43 | 44 | def test_padt_3(self): 45 | """Test function for padt() 3/3""" 46 | # empty matrix array 47 | tr = padt(self.tv3, n=25, val=1.5) 48 | res = np.vstack((1.5*np.ones((25, 1)), self.tv3.reshape((-1, 1)))) 49 | self.assertTrue(np.allclose(tr, res, atol=1e-8, rtol=1e-5)) 50 | 51 | -------------------------------------------------------------------------------- /deltasigma/tests/test_peakSNR.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_peakSNR.py 3 | # This module provides the tests for the peakSNR function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the peakSNR() function. 17 | """ 18 | 19 | import unittest 20 | import pkg_resources 21 | 22 | import numpy as np 23 | import scipy.io 24 | 25 | import deltasigma as ds 26 | 27 | class TestPeakSNR(unittest.TestCase): 28 | """Test class for peakSNR()""" 29 | 30 | def setUp(self): 31 | ds._peakSNR._debug = True 32 | fname = pkg_resources.resource_filename(__name__, "test_data/test_peak_snr.mat") 33 | self.snr = scipy.io.loadmat(fname)['snr'].reshape((-1,)) 34 | self.amp = scipy.io.loadmat(fname)['amp'].reshape((-1,)) 35 | self.peak_snr, self.peak_amp = 76.612340603949761, -3.220409771005124 36 | 37 | def test_peakSNR(self): 38 | """Test function for peakSNR()""" 39 | ps, pa = ds.peakSNR(self.snr, self.amp) 40 | self.assertTrue(np.allclose(ps, self.peak_snr, atol=1e-8, rtol=1e-5)) 41 | self.assertTrue(np.allclose(pa, self.peak_amp, atol=1e-8, rtol=1e-5)) 42 | 43 | -------------------------------------------------------------------------------- /deltasigma/tests/test_plotPZ.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_plotPZ.py 3 | # This module provides the tests for the plotPZ function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the plotPZ() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | import pylab as plt 22 | 23 | from deltasigma import plotPZ 24 | 25 | class TestPlotPZ(unittest.TestCase): 26 | """Test class for plotPZ()""" 27 | 28 | def setUp(self): 29 | pass 30 | 31 | def test_plotPZ_1(self): 32 | """Test function for plotPZ() 1/2""" 33 | plt.figure() 34 | self.assertIsNone(plotPZ(((1, .2), (1, 0, .10)), color=('r', 'b'), 35 | showlist=True)) 36 | 37 | def test_plotPZ_2(self): 38 | """Test function for plotPZ() 2/2""" 39 | plt.figure() 40 | self.assertIsNone(plotPZ(((1, 0, .10), (1, .2, .01)), showlist=False)) 41 | 42 | -------------------------------------------------------------------------------- /deltasigma/tests/test_rms.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | # test_rms.py 4 | # This module provides the tests for the rms function. 5 | # Copyright 2014 Giuseppe Venturini 6 | # This file is part of python-deltasigma. 7 | # 8 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 9 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 10 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 11 | # 12 | # python-deltasigma is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # LICENSE file for the licensing terms. 16 | 17 | """This module provides the test class for the rms() function. 18 | """ 19 | 20 | import unittest 21 | import numpy as np 22 | 23 | from deltasigma import rms 24 | 25 | class TestRms(unittest.TestCase): 26 | """Test class for rms()""" 27 | 28 | def setUp(self): 29 | self.tv = np.arange(100) 30 | self.res1 = np.sqrt(np.sum(self.tv**2.)/float(self.tv.shape[0])) 31 | self.res2 = np.sqrt((np.sum((self.tv - self.tv.mean())**2.)) \ 32 | /self.tv.shape[0]) 33 | 34 | def test_rms_1(self): 35 | """Test function for rms() 1/2""" 36 | self.assertTrue(np.allclose(rms(self.tv), self.res1, rtol=1e-05, 37 | atol=1e-08)) 38 | 39 | def test_rms_2(self): 40 | """Test function for rms() 2/2""" 41 | self.assertTrue(np.allclose(rms(self.tv, no_dc=True), self.res2, 42 | rtol=1e-05, atol=1e-08)) 43 | 44 | -------------------------------------------------------------------------------- /deltasigma/tests/test_rmsGain.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_rmsGain.py 3 | # This module provides the tests for the rmsGain function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the rmsGain() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | import deltasigma as ds 22 | 23 | class TestRmsGain(unittest.TestCase): 24 | """Test class for rmsGain()""" 25 | 26 | def setUp(self): 27 | num = (1,) 28 | den = (1, 2, 10) 29 | self.H = (num, den) 30 | self.f1 = 0.001 31 | self.f2 = 0.5 32 | self.res1 = 0.102245275091 33 | 34 | def test_rmsGain(self): 35 | """Test function for rmsGain()""" 36 | res = ds.rmsGain(self.H, self.f1, self.f2, N=1000) 37 | self.assertTrue(np.allclose((res,), (self.res1,), rtol=1e-05, 38 | atol=1e-08)) 39 | 40 | -------------------------------------------------------------------------------- /deltasigma/tests/test_thermometer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_thermometer.py 3 | # This module provides the tests for the thermometer function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the thermometer() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | 22 | from deltasigma import thermometer 23 | 24 | class TestThermometer(unittest.TestCase): 25 | """Test class for thermometer()""" 26 | 27 | def setUp(self): 28 | self.tv = np.arange(50) 29 | self.rm = np.zeros((70, 50)) 30 | for i in range(50): 31 | self.rm[:i, i] = np.ones(self.rm[:i, i].shape) 32 | 33 | def test_thermometer(self): 34 | """Test function for thermometer() 1/3""" 35 | self.assertTrue(np.allclose(thermometer(self.tv, 70), self.rm, 36 | rtol=1e-05, atol=1e-08)) 37 | 38 | -------------------------------------------------------------------------------- /deltasigma/tests/test_undbm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_undbm.py 3 | # This module provides the tests for the undbm function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the undbm() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | 22 | from deltasigma import undbm 23 | 24 | class TestUndbm(unittest.TestCase): 25 | """Test class for undbm()""" 26 | 27 | def setUp(self): 28 | pass 29 | 30 | def test_undbm_1(self): 31 | """Test function for undbm() 1/3""" 32 | self.assertTrue(np.allclose([undbm(53.015)], [100.054125892], rtol=1e-05, 33 | atol=1e-08)) 34 | 35 | def test_undbm_2(self): 36 | """Test function for undbm() 2/3""" 37 | self.assertTrue(np.allclose([undbm(3, 100)], [0.44668359215], rtol=1e-05, 38 | atol=1e-08)) 39 | 40 | def test_undbm_3(self): 41 | """Test function for undbm() 3/3""" 42 | self.assertTrue(np.isscalar(undbm(3, 100))) 43 | 44 | -------------------------------------------------------------------------------- /deltasigma/tests/test_undbp.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | # test_undbp.py 4 | # This module provides the tests for the undbp function. 5 | # Copyright 2014 Giuseppe Venturini 6 | # This file is part of python-deltasigma. 7 | # 8 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 9 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 10 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 11 | # 12 | # python-deltasigma is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # LICENSE file for the licensing terms. 16 | 17 | """This module provides the test class for the undbp() function. 18 | """ 19 | 20 | import unittest 21 | import numpy as np 22 | 23 | from deltasigma import undbp 24 | 25 | class TestUndbp(unittest.TestCase): 26 | """Test class for undbp()""" 27 | 28 | def setUp(self): 29 | pass 30 | 31 | def test_undbp_1(self): 32 | """Test function for undbp() 1/2""" 33 | self.assertTrue(np.allclose([undbp(53.05)], [201836.636368], rtol=1e-05, 34 | atol=1e-08)) 35 | 36 | def test_undbp_2(self): 37 | """Test function for undbp() 2/2""" 38 | self.assertTrue(np.allclose([undbp(3)], [1.99526231497], rtol=1e-05, 39 | atol=1e-08)) 40 | 41 | -------------------------------------------------------------------------------- /deltasigma/tests/test_undbv.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_undbv.py 3 | # This module provides the tests for the undbv function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the undbv() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | 22 | from deltasigma import undbv 23 | 24 | class TestUndbv(unittest.TestCase): 25 | """Test class for undbv()""" 26 | 27 | def setUp(self): 28 | pass 29 | 30 | def test_undbv_1(self): 31 | """Test function for undbv() 1/2""" 32 | self.assertTrue(np.allclose([undbv(53.05)], [449.26232467], rtol=1e-05, 33 | atol=1e-08)) 34 | 35 | def test_undbv_2(self): 36 | """Test function for undbv() 2/2""" 37 | self.assertTrue(np.allclose([undbv(3)], [1.41253754462], rtol=1e-05, 38 | atol=1e-08)) 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /deltasigma/tests/test_zinc.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_zinc.py 3 | # This module provides the tests for the zinc function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the zinc() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | import deltasigma as ds 22 | 23 | class TestZinc(unittest.TestCase): 24 | """Test class for zinc()""" 25 | 26 | def setUp(self): 27 | self.ref = [1.0000, 0.9985, 0.9941, 0.9867, 0.9765, 0.9635, 28 | 0.9478, 0.9295, 0.9087, 0.8855, 0.8602, 0.8329, 29 | 0.8038, 0.7730, 0.7408, 0.7074, 0.6729, 0.6377, 30 | 0.6019, 0.5658, 0.5295, 0.4933, 0.4574, 0.4221, 31 | 0.3874, 0.3536, 0.3208, 0.2892, 0.2590, 0.2302, 32 | 0.2031, 0.1776, 0.1538, 0.1319, 0.1118, 0.0936, 33 | 0.0772, 0.0626, 0.0499, 0.0389, 0.0295, 0.0217, 34 | 0.0154, 0.0104, 0.0066, 0.0038, 0.0020, 0.0008, 35 | 0.0002, 0.0000, 0.0000] 36 | self.f = np.arange(0, 0.51, 0.01) 37 | 38 | def test_zinc(self): 39 | """Test function for zinc()""" 40 | test = ds.zinc(self.f, 2, 3) 41 | self.assertTrue(np.allclose(test, self.ref, atol=1e-4, 42 | rtol=1e-4)) 43 | 44 | -------------------------------------------------------------------------------- /doc/_static/CIFB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/CIFB.png -------------------------------------------------------------------------------- /doc/_static/CIFF.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/CIFF.png -------------------------------------------------------------------------------- /doc/_static/CRFB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/CRFB.png -------------------------------------------------------------------------------- /doc/_static/CRFBD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/CRFBD.png -------------------------------------------------------------------------------- /doc/_static/CRFF.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/CRFF.png -------------------------------------------------------------------------------- /doc/_static/CRFFD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/CRFFD.png -------------------------------------------------------------------------------- /doc/_static/DS_equivalence_DT_CT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/DS_equivalence_DT_CT.png -------------------------------------------------------------------------------- /doc/_static/functionality.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/functionality.png -------------------------------------------------------------------------------- /doc/_static/mapCtoD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/mapCtoD.png -------------------------------------------------------------------------------- /doc/_static/modulator_model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/modulator_model.png -------------------------------------------------------------------------------- /doc/_static/predictSNR.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/predictSNR.png -------------------------------------------------------------------------------- /doc/_static/quantizer_model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/quantizer_model.png -------------------------------------------------------------------------------- /doc/_static/synthesizeQNTF.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hpretl/python-deltasigma/9b1b21ea805513851b907701e9bed3fbba582a99/doc/_static/synthesizeQNTF.png -------------------------------------------------------------------------------- /doc/deltasigma_theme/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | deltasigma_theme_path = os.path.split(os.path.split(__file__)[0])[0] 3 | -------------------------------------------------------------------------------- /doc/deltasigma_theme/relbar.html: -------------------------------------------------------------------------------- 1 | {%- macro rellink_markup() %} 2 | 18 | {%- endmacro %} 19 | 20 | {%- macro breadcrumbs_markup() %} 21 | 34 | {%- endmacro %} 35 | 36 | {%- macro relbar_top() %} 37 | {%- if theme_showrelbartop|tobool %} 38 | 42 | {%- endif %} 43 | {%- endmacro %} 44 | 45 | {%- macro relbar_bottom() %} 46 | {%- if theme_showrelbarbottom|tobool %} 47 | 51 | {%- endif %} 52 | {%- endmacro %} 53 | -------------------------------------------------------------------------------- /doc/deltasigma_theme/sourcelink.html: -------------------------------------------------------------------------------- 1 | {%- if show_source and has_source and sourcename %} 2 | 7 | 8 | {%- endif %} 9 | -------------------------------------------------------------------------------- /doc/deltasigma_theme/theme.conf: -------------------------------------------------------------------------------- 1 | [theme] 2 | inherit = basic 3 | stylesheet = deltasigma_theme.css 4 | pygments_style = sphinx 5 | 6 | [options] 7 | rightsidebar = false 8 | inlinecss = 9 | cssfiles = 10 | scriptfiles = 11 | ga_ua = UA-46404189-1 12 | ga_domain = deltasigma.io 13 | 14 | showrelbartop = false 15 | showrelbarbottom = true 16 | showheader = true 17 | enablesidebarsearch = false 18 | linktotheme = true 19 | 20 | # css shortcuts that should decrease as the markup improves 21 | 22 | ## page width is determined by CSS 23 | sidebarwidth = 15rem 24 | 25 | ## headtextcolor (color of h* tags) and footertextcolor default to the value 26 | ## of textcolor 27 | textcolor = #666 28 | headtextcolor = #000000 29 | footertextcolor = #000000 30 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | .. raw:: latex 2 | 3 | \renewcommand{\headrulewidth}{0.5pt} 4 | \renewcommand{\footrulewidth}{0pt} 5 | \fancyhf{} 6 | \fancyfoot[C]{\thepage} 7 | \fancyhead[RO]{} 8 | \fancyhead[LE]{} 9 | 10 | .. toctree:: 11 | :maxdepth: 3 12 | 13 | .. automodule:: deltasigma.__init__ 14 | :members: DocumentNTF, PlotExampleSpectrum, SIunits, axisLabels, bilogplot, bplogsmooth, bquantize, bunquantize, calculateSNR, calculateTF, calculateQTF, cancelPZ, changeFig, circ_smooth, circshift, clans, eps, db, dbm, dbp, dbv, delay, ds_f1f2, ds_freq, ds_hann, ds_optzeros, ds_quantize, ds_synNTFobj1, dsclansNTF, evalMixedTF, evalRPoly, evalTF, evalTFP, figureMagic, frespF1, impL1, infnorm, l1norm, logsmooth, lollipop, mapABCD, mapCtoD, mapQtoR, mapRtoQ, mod1, mod2, nabsH, padb, padl, padr, padt, partitionABCD, peakSNR, plotPZ, plotSpectrum, predictSNR, pulse, realizeNTF, realizeNTF_ct, realizeQNTF, rms, rmsGain, scaleABCD, simulateDSM, simulateQDSM, simulateQSNR, simulateSNR, sinc_decimate, stuffABCD, synthesizeChebyshevNTF, synthesizeNTF, synthesizeQNTF, undbm, undbp, undbv, cplxpair, mfloor, mround, pretty_lti, rat, gcd, lcm, zinc 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /doc/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx 2 | numpy 3 | scipy 4 | matplotlib 5 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: base 2 | channels: 3 | - defaults 4 | dependencies: 5 | - numpy < 1.21.2 6 | - scipy 7 | - matplotlib 8 | # - nose 9 | - setuptools 10 | - coverage 11 | - cython 12 | -------------------------------------------------------------------------------- /misc/test_template.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # test_CHANGEME.py 3 | # This module provides the tests for the CHANGEME function. 4 | # Copyright 2014 Giuseppe Venturini 5 | # This file is part of python-deltasigma. 6 | # 7 | # python-deltasigma is a 1:1 Python replacement of Richard Schreier's 8 | # MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based. 9 | # The delta sigma toolbox is (c) 2009, Richard Schreier. 10 | # 11 | # python-deltasigma is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # LICENSE file for the licensing terms. 15 | 16 | """This module provides the test class for the CHANGEME() function. 17 | """ 18 | 19 | import unittest 20 | import numpy as np 21 | import deltasigma as ds 22 | 23 | class TestCHANGEME(unittest.TestCase): 24 | """Test class for CHANGEME()""" 25 | 26 | def setUp(self): 27 | pass 28 | 29 | def test_CHANGEME(self): 30 | """Test function for CHANGEME() 1/3""" 31 | self.assertTrue(True) 32 | 33 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # python >= 3.7 2 | numpy < 1.21.2 3 | scipy 4 | #intel-scipy 5 | matplotlib 6 | cython 7 | #nose 8 | setuptools 9 | coverage 10 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | from setuptools import setup, find_packages 5 | __version__ = "0.2.6" 6 | 7 | def read(fname): 8 | try: 9 | with open(os.path.join(os.path.dirname(__file__), fname)) as fp: 10 | return fp.read() 11 | except IOError: 12 | return "" 13 | 14 | setup( 15 | name='deltasigma', 16 | version=__version__, 17 | packages=find_packages(exclude=['beta']), 18 | package_data={ 19 | 'deltasigma': ['tests/test_data/*.mat', 'tests/test_data/*.txt'] 20 | }, 21 | install_requires=['numpy', 'scipy', 'matplotlib>=3.0.0'], 22 | zip_safe=False, 23 | include_package_data=True, 24 | author="Giuseppe Venturini and others", 25 | author_email="giuseppe.g.venturini@ieee.org", 26 | description="a Python package to synthesize, simulate, scale and map " + \ 27 | "to implementable topologies delta sigma modulators.", 28 | long_description=''.join([read('pypi_description.rst'), '\n\n', 29 | read('CHANGES.rst')]), 30 | license="BSD", 31 | keywords="delta sigma modulator simulator", 32 | url="http://github.com/ggventurini/python-deltasigma", 33 | test_suite = "deltasigma.tests", 34 | classifiers=[ 35 | "Development Status :: 5 - Production/Stable", 36 | "Intended Audience :: Education", 37 | "Intended Audience :: Science/Research", 38 | "License :: OSI Approved :: BSD License", 39 | "Operating System :: POSIX", 40 | "Operating System :: POSIX :: Linux", 41 | "Operating System :: Microsoft :: Windows", 42 | "Operating System :: MacOS", 43 | "Natural Language :: English", 44 | "Programming Language :: Python :: 3 :: Only", 45 | "Programming Language :: Python :: 3.7", 46 | "Programming Language :: Python :: 3.8", 47 | "Programming Language :: Python :: 3.9", 48 | ] 49 | ) 50 | 51 | --------------------------------------------------------------------------------