Libraries

pyfda.pyfda_fix_lib

Fixpoint library for converting numpy scalars and arrays to quantized numpy values and formatting reals in various formats

class pyfda.pyfda_fix_lib.Fixed(q_obj)[source]

Implement binary quantization of signed scalar or array-like objects in the form Q = WI.WF where WI and WF are the wordlength of integer resp. fractional part; total wordlength is W = WI + WF + 1 due to the sign bit.

Examples

Define a dictionary with the format options and pass it to the constructor:

>>> q_obj = {'WI':1, 'WF':14, 'ovfl':'sat', 'quant':'round'} # or
>>> q_obj = {'Q':'1.14', 'ovfl':'none', 'quant':'round'}
>>> myQ = Fixed(q_obj)
Parameters:
  • q_obj (dict) – define quantization options with the following keys
  • 'WI' (*) –
  • 'WF' (*) –
  • 'W' (*) – W are missing, WI = W - 1 and WF = 0.
  • 'Q' (*) – to`WI` and WF. When both Q and WI / WF are given, Q is ignored
  • 'quant' (*) –
    • ‘floor’: (default) largest integer I such that \(I \le x\) (= binary truncation)
    • ’round’: (binary) rounding
    • ’fix’: round to nearest integer towards zero (‘Betragsschneiden’)
    • ’ceil’: smallest integer I, such that \(I \ge x\)
    • ’rint’: round towards nearest int
    • ’none’: no quantization
  • 'ovfl' (*) –
    • ‘wrap’: do a two’s complement wrap-around
    • ’sat’ : saturate at minimum / maximum value
    • ’none’: no overflow; the integer word length is ignored
  • the following keys define the base / display format for the (Additionally,) –
  • number (fixpoint) –
  • 'frmt' (*) –
    • ‘float’ : (default)
    • ’dec’ : decimal integer, scaled by \(2^{WF}\)
    • ’bin’ : binary string, scaled by \(2^{WF}\)
    • ’hex’ : hex string, scaled by \(2^{WF}\)
    • ’csd’ : canonically signed digit string, scaled by \(2^{WF}\)
  • 'scale' (*) –

    representation and its floating point value. If scale is a float, this value is used. Alternatively, if:

    • q_obj['scale'] == 'int': scale = 1 << self.WF
    • q_obj['scale'] == 'norm': scale = 2.**(-self.WI)
q_obj

A copy of the quantization dictionary (see above)

Type:dict
WI

number of integer bits

Type:integer
WF

number of fractional bits

Type:integer
W

total wordlength

Type:integer
Q

quantization format, e.g. ‘2.13’

Type:string
quant

Quantization behaviour (‘floor’, ‘round’, …)

Type:string
ovfl

Overflow behaviour (‘wrap’, ‘sat’, …)

Type:string
frmt

target output format (‘float’, ‘dec’, ‘bin’, ‘hex’, ‘csd’)

Type:string
scale

The factor between integer fixpoint representation and the floating point value, RWV = FXP / scale. By default, scale = 1 << WI.

Examples:
WI.WF = 3.0, FXP = “b0110.” = 6, scale = 8 -> RWV = 6 / 8 = 0.75 WI.WF = 1.2, FXP = “b01.10” = 1.5, scale = 2 -> RWV = 1.5 / 2 = 0.75
Type:float
LSB

value of LSB (smallest quantization step)

Type:float
MSB

value of most significant bit (MSB)

Type:float
digits

number of digits required for selected number format and wordlength

Type:integer
ovr_flag

overflow flag, meaning:

0 : no overflow

+1: positive overflow

-1: negative overflow

has occured during last fixpoint conversion

Type:integer or integer array (same shape as input argument)
N_over

total number of overflows

Type:integer
N_over_neg

number of negative overflows

Type:integer
N_over_pos

number of positive overflows

Type:integer

Example

class Fixed() can be used like Matlabs quantizer object / function from the fixpoint toolbox, see (Matlab) ‘help round’ and ‘help quantizer/round’ e.g.

>>> q_dsp = quantizer('fixed', 'round', [16 15], 'wrap'); % Matlab
>>> yq = quantize(q_dsp, y)
>>> q_dsp = {'Q':'0.15', 'quant':'round', 'ovfl':'wrap'} # Python
>>> my_q = Fixed(q_dsp)
>>> yq = my_q.fixp(y)
fixp(y, scaling='mult')[source]

Return fixed-point integer or fractional representation for y (scalar or array-like) with the same shape as y.

Saturation / two’s complement wrapping happens outside the range +/- MSB, requantization (round, floor, fix, …) is applied on the ratio y / LSB.

Parameters:
  • y (scalar or array-like object) – input value (floating point format) to be quantized
  • scaling (String) –

    Determine the scaling before and after quantizing / saturation

    ’mult’ float in, int out:
    y is multiplied by self.scale before quantizing / saturating
    ’div’: int in, float out:
    y is divided by self.scale after quantizing / saturating.
    ’multdiv’: float in, float out (default):
    both of the above

    For all other settings, y is transformed unscaled.

Returns:

with the same shape as y, in the range -2*self.MSB2*self.MSB-self.LSB

Return type:

float scalar or ndarray

Examples

>>> q_obj_a = {'WI':1, 'WF':6, 'ovfl':'sat', 'quant':'round'}
>>> myQa = Fixed(q_obj_a) # instantiate fixed-point object myQa
>>> myQa.resetN()  # reset overflow counter
>>> a = np.arange(0,5, 0.05) # create input signal
>>> aq = myQa.fixed(a) # quantize input signal
>>> plt.plot(a, aq) # plot quantized vs. original signal
>>> print(myQa.N_over, "overflows!") # print number of overflows
>>> # Convert output to same format as input:
>>> b = np.arange(200, dtype = np.int16)
>>> btype = np.result_type(b)
>>> # MSB = 2**7, LSB = 2**(-2):
>>> q_obj_b = {'WI':7, 'WF':2, 'ovfl':'wrap', 'quant':'round'}
>>> myQb = Fixed(q_obj_b) # instantiate fixed-point object myQb
>>> bq = myQb.fixed(b)
>>> bq = bq.astype(btype) # restore original variable type
float2frmt(y)[source]

Called a.o. by itemDelegate.displayText() for on-the-fly number conversion. Returns fixpoint representation for y (scalar or array-like) with numeric format self.frmt and self.W bits. The result has the same shape as y.

The float is multiplied by self.scale and quantized / saturated using fixp() for all formats before it is converted to different number formats.

Parameters:y (scalar or array-like) – y has to be an integer or float decimal number either numeric or in string format.
Returns:
  • A string, a float or an ndarray of float or string is returned in the
  • numeric format set in self.frmt. It has the same shape as y. For all
  • formats except float a fixpoint representation with self.W binary
  • digits is returned.
frmt2float(y, frmt=None)[source]

Return floating point representation for fixpoint scalar y given in format frmt.

When input format is float, return unchanged.

Else:

  • Remove illegal characters and leading ‘0’s
  • Count number of fractional places frc_places and remove radix point
  • Calculate decimal, fractional representation y_dec of string, using the base and the number of fractional places
  • Calculate two’s complement for W bits (only for negative bin and hex numbers)
  • Calculate fixpoint float representation y_float = fixp(y_dec, scaling=’div’), dividing the result by scale.
Parameters:
  • y (scalar or string) – to be quantized with the numeric base specified by frmt.
  • frmt (string (optional)) – any of the formats float, dec, bin, hex, csd) When frmt is unspecified, the instance parameter self.frmt is used
Returns:

Return type:

quantized floating point (dtype=np.float64) representation of input string

resetN()[source]

Reset counter and overflow-counters of Fixed object

setQobj(q_obj)[source]

Analyze quantization dict, complete and transform it if needed and store it as instance attribute.

Check the docstring of class Fixed() for details.

pyfda.pyfda_fix_lib.bin2hex(bin_str, WI=0)[source]

Convert number bin_str in binary format to hex formatted string. bin_str is prepended / appended with zeros until the number of bits before and after the radix point (position given by WI) is a multiple of 4.

pyfda.pyfda_fix_lib.csd2dec(csd_str)[source]

Convert the CSD string csd_str to a decimal, csd_str may contain ‘+’ or ‘-‘, indicating whether the current bit is meant to positive or negative. All other characters are simply ignored (= replaced by zero).

csd_str has to be an integer CSD number.

Parameters:csd_str (string) – A string with the CSD value to be converted, consisting of ‘+’, ‘-‘, ‘.’ and ‘0’ characters.
Returns:
Return type:decimal (integer) value of the CSD string

Examples

+00- = +2³ - 2⁰ = +7

-0+0 = -2³ + 2¹ = -6

pyfda.pyfda_fix_lib.dec2csd(dec_val, WF=0)[source]

Convert the argument dec_val to a string in CSD Format.

Parameters:
  • dec_val (scalar (integer or real)) – decimal value to be converted to CSD format
  • WF (integer) – number of fractional places. Default is WF = 0 (integer number)
Returns:

  • string – containing the CSD value
  • Original author (Harnesser)
  • https (//sourceforge.net/projects/pycsd/)
  • License (GPL2)

pyfda.pyfda_fix_lib.dec2hex(val, nbits, WF=0)[source]

— currently not used, no unit test —

Return val in hex format with a wordlength of nbits in two’s complement format. The built-in hex function returns args < 0 as negative values. When val >= 2**nbits, it is “wrapped” around to the range 0 … 2**nbits-1

Parameters:
  • val (integer) – The value to be converted in decimal integer format.
  • nbits (integer) – The wordlength
Returns:

Return type:

A string in two’s complement hex format

pyfda.pyfda_fix_lib.qstr(text)[source]

carefully replace qstr() function - only needed for Py2 compatibility

pyfda.pyfda_fix_lib.Fixed

class pyfda.pyfda_fix_lib.Fixed(q_obj)[source]

Implement binary quantization of signed scalar or array-like objects in the form Q = WI.WF where WI and WF are the wordlength of integer resp. fractional part; total wordlength is W = WI + WF + 1 due to the sign bit.

Examples

Define a dictionary with the format options and pass it to the constructor:

>>> q_obj = {'WI':1, 'WF':14, 'ovfl':'sat', 'quant':'round'} # or
>>> q_obj = {'Q':'1.14', 'ovfl':'none', 'quant':'round'}
>>> myQ = Fixed(q_obj)
Parameters:
  • q_obj (dict) – define quantization options with the following keys
  • 'WI' (*) –
  • 'WF' (*) –
  • 'W' (*) – W are missing, WI = W - 1 and WF = 0.
  • 'Q' (*) – to`WI` and WF. When both Q and WI / WF are given, Q is ignored
  • 'quant' (*) –
    • ‘floor’: (default) largest integer I such that \(I \le x\) (= binary truncation)
    • ’round’: (binary) rounding
    • ’fix’: round to nearest integer towards zero (‘Betragsschneiden’)
    • ’ceil’: smallest integer I, such that \(I \ge x\)
    • ’rint’: round towards nearest int
    • ’none’: no quantization
  • 'ovfl' (*) –
    • ‘wrap’: do a two’s complement wrap-around
    • ’sat’ : saturate at minimum / maximum value
    • ’none’: no overflow; the integer word length is ignored
  • the following keys define the base / display format for the (Additionally,) –
  • number (fixpoint) –
  • 'frmt' (*) –
    • ‘float’ : (default)
    • ’dec’ : decimal integer, scaled by \(2^{WF}\)
    • ’bin’ : binary string, scaled by \(2^{WF}\)
    • ’hex’ : hex string, scaled by \(2^{WF}\)
    • ’csd’ : canonically signed digit string, scaled by \(2^{WF}\)
  • 'scale' (*) –

    representation and its floating point value. If scale is a float, this value is used. Alternatively, if:

    • q_obj['scale'] == 'int': scale = 1 << self.WF
    • q_obj['scale'] == 'norm': scale = 2.**(-self.WI)
q_obj

A copy of the quantization dictionary (see above)

Type:dict
WI

number of integer bits

Type:integer
WF

number of fractional bits

Type:integer
W

total wordlength

Type:integer
Q

quantization format, e.g. ‘2.13’

Type:string
quant

Quantization behaviour (‘floor’, ‘round’, …)

Type:string
ovfl

Overflow behaviour (‘wrap’, ‘sat’, …)

Type:string
frmt

target output format (‘float’, ‘dec’, ‘bin’, ‘hex’, ‘csd’)

Type:string
scale

The factor between integer fixpoint representation and the floating point value, RWV = FXP / scale. By default, scale = 1 << WI.

Examples:
WI.WF = 3.0, FXP = “b0110.” = 6, scale = 8 -> RWV = 6 / 8 = 0.75 WI.WF = 1.2, FXP = “b01.10” = 1.5, scale = 2 -> RWV = 1.5 / 2 = 0.75
Type:float
LSB

value of LSB (smallest quantization step)

Type:float
MSB

value of most significant bit (MSB)

Type:float
digits

number of digits required for selected number format and wordlength

Type:integer
ovr_flag

overflow flag, meaning:

0 : no overflow

+1: positive overflow

-1: negative overflow

has occured during last fixpoint conversion

Type:integer or integer array (same shape as input argument)
N_over

total number of overflows

Type:integer
N_over_neg

number of negative overflows

Type:integer
N_over_pos

number of positive overflows

Type:integer

Example

class Fixed() can be used like Matlabs quantizer object / function from the fixpoint toolbox, see (Matlab) ‘help round’ and ‘help quantizer/round’ e.g.

>>> q_dsp = quantizer('fixed', 'round', [16 15], 'wrap'); % Matlab
>>> yq = quantize(q_dsp, y)
>>> q_dsp = {'Q':'0.15', 'quant':'round', 'ovfl':'wrap'} # Python
>>> my_q = Fixed(q_dsp)
>>> yq = my_q.fixp(y)
fixp(y, scaling='mult')[source]

Return fixed-point integer or fractional representation for y (scalar or array-like) with the same shape as y.

Saturation / two’s complement wrapping happens outside the range +/- MSB, requantization (round, floor, fix, …) is applied on the ratio y / LSB.

Parameters:
  • y (scalar or array-like object) – input value (floating point format) to be quantized
  • scaling (String) –

    Determine the scaling before and after quantizing / saturation

    ’mult’ float in, int out:
    y is multiplied by self.scale before quantizing / saturating
    ’div’: int in, float out:
    y is divided by self.scale after quantizing / saturating.
    ’multdiv’: float in, float out (default):
    both of the above

    For all other settings, y is transformed unscaled.

Returns:

with the same shape as y, in the range -2*self.MSB2*self.MSB-self.LSB

Return type:

float scalar or ndarray

Examples

>>> q_obj_a = {'WI':1, 'WF':6, 'ovfl':'sat', 'quant':'round'}
>>> myQa = Fixed(q_obj_a) # instantiate fixed-point object myQa
>>> myQa.resetN()  # reset overflow counter
>>> a = np.arange(0,5, 0.05) # create input signal
>>> aq = myQa.fixed(a) # quantize input signal
>>> plt.plot(a, aq) # plot quantized vs. original signal
>>> print(myQa.N_over, "overflows!") # print number of overflows
>>> # Convert output to same format as input:
>>> b = np.arange(200, dtype = np.int16)
>>> btype = np.result_type(b)
>>> # MSB = 2**7, LSB = 2**(-2):
>>> q_obj_b = {'WI':7, 'WF':2, 'ovfl':'wrap', 'quant':'round'}
>>> myQb = Fixed(q_obj_b) # instantiate fixed-point object myQb
>>> bq = myQb.fixed(b)
>>> bq = bq.astype(btype) # restore original variable type
float2frmt(y)[source]

Called a.o. by itemDelegate.displayText() for on-the-fly number conversion. Returns fixpoint representation for y (scalar or array-like) with numeric format self.frmt and self.W bits. The result has the same shape as y.

The float is multiplied by self.scale and quantized / saturated using fixp() for all formats before it is converted to different number formats.

Parameters:y (scalar or array-like) – y has to be an integer or float decimal number either numeric or in string format.
Returns:
  • A string, a float or an ndarray of float or string is returned in the
  • numeric format set in self.frmt. It has the same shape as y. For all
  • formats except float a fixpoint representation with self.W binary
  • digits is returned.
frmt2float(y, frmt=None)[source]

Return floating point representation for fixpoint scalar y given in format frmt.

When input format is float, return unchanged.

Else:

  • Remove illegal characters and leading ‘0’s
  • Count number of fractional places frc_places and remove radix point
  • Calculate decimal, fractional representation y_dec of string, using the base and the number of fractional places
  • Calculate two’s complement for W bits (only for negative bin and hex numbers)
  • Calculate fixpoint float representation y_float = fixp(y_dec, scaling=’div’), dividing the result by scale.
Parameters:
  • y (scalar or string) – to be quantized with the numeric base specified by frmt.
  • frmt (string (optional)) – any of the formats float, dec, bin, hex, csd) When frmt is unspecified, the instance parameter self.frmt is used
Returns:

Return type:

quantized floating point (dtype=np.float64) representation of input string

resetN()[source]

Reset counter and overflow-counters of Fixed object

setQobj(q_obj)[source]

Analyze quantization dict, complete and transform it if needed and store it as instance attribute.

Check the docstring of class Fixed() for details.