Skip to content

Commit bdac7c1

Browse files
committed
Add utilities mag2db and db2mag
These convert magnitudes to decibels and back
1 parent 710b6ce commit bdac7c1

3 files changed

Lines changed: 59 additions & 1 deletion

File tree

control/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@
7575
from .timeresp import forced_response, initial_response, step_response, \
7676
impulse_response
7777
from .xferfcn import TransferFunction
78-
from .ctrlutil import unwrap, issys
78+
from .ctrlutil import *
7979
from .frdata import FRD
8080
from .canonical import canonical_form, reachable_form
8181

control/ctrlutil.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@
4545
import numpy as np
4646
from numpy import pi
4747

48+
__all__ = ['unwrap', 'issys', 'db2mag', 'mag2db']
49+
4850
# Utility function to unwrap an angle measurement
4951
def unwrap(angle, period=2*pi):
5052
"""Unwrap a phase angle to give a continuous curve
@@ -78,3 +80,43 @@ def unwrap(angle, period=2*pi):
7880
def issys(obj):
7981
"""Return True if an object is a system, otherwise False"""
8082
return isinstance(obj, lti.Lti)
83+
84+
def db2mag(db):
85+
"""Convert a gain in decibels (dB) to a magnitude
86+
87+
If A is magnitude,
88+
89+
db = 20 * log10(A)
90+
91+
Parameters
92+
----------
93+
db : float or ndarray
94+
input value or array of values, given in decibels
95+
96+
Returns
97+
-------
98+
mag : float or ndarray
99+
corresponding magnitudes
100+
101+
"""
102+
return 10. ** (db / 20.)
103+
104+
def mag2db(mag):
105+
"""Convert a magnitude to decibels (dB)
106+
107+
If A is magnitude,
108+
109+
db = 20 * log10(A)
110+
111+
Parameters
112+
----------
113+
mag : float or ndarray
114+
input magnitude or array of magnitudes
115+
116+
Returns
117+
-------
118+
db : float or ndarray
119+
corresponding values in decibels
120+
121+
"""
122+
return 20. * np.log10(mag)

control/tests/ctrlutil_test.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,22 @@ def test_unwrap_list(self):
4141
angle_unwrapped = [0, 0.2, 0.4, 0.6]
4242
np.testing.assert_array_almost_equal(unwrap(angle, 1.0), angle_unwrapped)
4343

44+
def test_db2mag(self):
45+
for mag, db in zip(self.mag, self.db):
46+
np.testing.assert_almost_equal(mag, db2mag(db))
47+
48+
def test_db2mag_array(self):
49+
mag_array = db2mag(self.db)
50+
np.testing.assert_array_almost_equal(mag_array, self.mag)
51+
52+
def test_mag2db(self):
53+
for db, mag in zip(self.db, self.mag):
54+
np.testing.assert_almost_equal(db, mag2db(mag))
55+
56+
def test_mag2db_array(self):
57+
db_array = mag2db(self.mag)
58+
np.testing.assert_array_almost_equal(db_array, self.db)
59+
4460

4561
def test_suite():
4662
return unittest.TestLoader().loadTestsFromTestCase(TestUtils)

0 commit comments

Comments
 (0)