Skip to content

polykin.distributions¤

Flory ¤

Flory-Schulz (aka most-probable) chain-length distribution.

This distribution is based on the following number probability density function:

\[ p(k) = (1-a)a^{k-1} \]

where \(a=1-1/DP_n\). Mathematically speaking, this is a geometric distribution.

PARAMETER DESCRIPTION
DPn

Number-average degree of polymerization, \(DP_n\).

TYPE: float

M0

Molar mass of the repeating unit, \(M_0\). Unit = kg/mol.

TYPE: float DEFAULT: 0.1

name

Name

TYPE: str DEFAULT: ''

Examples:

Define a Flory distribution and evaluate the corresponding probability density function and cumulative distribution function for representative chain lengths.

>>> from polykin.distributions import Flory
>>> a = Flory(100, M0=0.050, name='A')
>>> a
type: Flory
name: A
DPn:  100.0
DPw:  199.0
DPz:  298.5
PDI:  1.99
M0:   0.050 kg/mol
Mn:   5.000 kg/mol
Mw:   9.950 kg/mol
Mz:   14.925 kg/mol
>>> a.pdf(a.DPn)
0.003697296376497271
>>> a.cdf([a.DPn, a.DPw, a.DPz])
array([0.26793532, 0.59535432, 0.80159978])
Source code in src/polykin/distributions/analyticaldistributions.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class Flory(AnalyticalDistributionP1):
    r"""Flory-Schulz (aka most-probable) chain-length distribution.

    This distribution is based on the following number probability density
    function:

    $$ p(k) = (1-a)a^{k-1} $$

    where $a=1-1/DP_n$. Mathematically speaking, this is a [geometric
    distribution](https://en.wikipedia.org/wiki/Geometric_distribution).

    Parameters
    ----------
    DPn : float
        Number-average degree of polymerization, $DP_n$.
    M0 : float
        Molar mass of the repeating unit, $M_0$. Unit = kg/mol.
    name : str
        Name


    Examples
    --------
    Define a Flory distribution and evaluate the corresponding probability
    density function and cumulative distribution function for representative
    chain lengths.

    >>> from polykin.distributions import Flory
    >>> a = Flory(100, M0=0.050, name='A')
    >>> a
    type: Flory
    name: A
    DPn:  100.0
    DPw:  199.0
    DPz:  298.5
    PDI:  1.99
    M0:   0.050 kg/mol
    Mn:   5.000 kg/mol
    Mw:   9.950 kg/mol
    Mz:   14.925 kg/mol

    >>> a.pdf(a.DPn)
    0.003697296376497271

    >>> a.cdf([a.DPn, a.DPw, a.DPz])
    array([0.26793532, 0.59535432, 0.80159978])

    """
    _continuous = False

    def __init__(self,
                 DPn: float,
                 M0: float = 0.1,
                 name: str = ''
                 ) -> None:

        super().__init__(DPn, M0, name)

    def _update_internal_parameters(self):
        super()._update_internal_parameters()
        self._a = 1 - 1/self.DPn

    def _pdf0_length(self, k):
        a = self._a
        return (1 - a) * a ** (k - 1)

    @functools.cache
    def _moment_length(self, order):
        a = self._a
        if order == 0:
            result = 1.0
        elif order == 1:
            result = 1/(1 - a)
        elif order == 2:
            result = 2/(1 - a)**2 - 1/(1 - a)
        elif order == 3:
            result = 6/(1 - a)**3 - 6/(1 - a)**2 + 1/(1 - a)
        else:
            raise ValueError("Not defined for order>3.")
        return result

    def _cdf_length(self, k, order):
        a = self._a
        if order == 0:
            result = 1 - a**k
        elif order == 1:
            result = (a**k*(-a*k + k + 1) - 1)/(a - 1)
        else:
            raise ValueError
        return result / self._moment_length(order)

    def _random_length(self, size):
        return self._rng.geometric((1-self._a), size)  # type: ignore

    @functools.cached_property
    def _range_length_default(self):
        return st.geom.ppf(self._ppf_bounds, p=(1-self._a))

DPn property writable ¤

DPn: float

Number-average degree of polymerization, \(DP_n\).

DPw property ¤

DPw: float

Mass-average degree of polymerization, \(DP_w\).

DPz property ¤

DPz: float

z-average degree of polymerization, \(DP_z\).

M0 instance-attribute ¤

M0 = M0

Number-average molar mass of the repeating units, \(M_0=M_n/DP_n\).

Mn property ¤

Mn: float

Number-average molar mass, \(M_n\).

Mw property ¤

Mw: float

Weight-average molar mass, \(M_w\).

Mz property ¤

Mz: float

z-average molar mass, \(M_z\).

PDI property ¤

PDI: float

Polydispersity index, \(M_w/M_n\).

cdf ¤

cdf(
    size: Union[float, FloatArrayLike],
    kind: Literal["number", "mass"] = "mass",
    sizeasmass: bool = False,
) -> Union[float, FloatArray]

Evaluate the cumulative distribution function:

\[ F(s) = \frac{\sum_{k=1}^{s}k^m\,p(k)}{\sum_{k=1}^{\infty}k^m\,p(k)} \]

or

\[ F(s) = \frac{\int_{0}^{s}x^m\,p(x)\mathrm{d}x} {\int_{0}^{\infty}x^m\,p(x)\mathrm{d}x} \]

where \(m\) is the order (0: number, 1: mass).

PARAMETER DESCRIPTION
size

Chain length or molar mass.

TYPE: float | FloatArrayLike

kind

Kind of distribution.

TYPE: Literal['number', 'mass'] DEFAULT: 'mass'

sizeasmass

Switch size input between chain-length (if False) or molar mass (if True).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
float | FloatArray

Cumulative probability.

Source code in src/polykin/distributions/base.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def cdf(self,
        size: Union[float, FloatArrayLike],
        kind: Literal['number', 'mass'] = 'mass',
        sizeasmass: bool = False,
        ) -> Union[float, FloatArray]:
    r"""Evaluate the cumulative distribution function:

    $$
    F(s) = \frac{\sum_{k=1}^{s}k^m\,p(k)}{\sum_{k=1}^{\infty}k^m\,p(k)}
    $$

    or

    $$
    F(s) = \frac{\int_{0}^{s}x^m\,p(x)\mathrm{d}x}
           {\int_{0}^{\infty}x^m\,p(x)\mathrm{d}x}
    $$

    where $m$ is the order (0: number, 1: mass).

    Parameters
    ----------
    size : float | FloatArrayLike
        Chain length or molar mass.
    kind : Literal['number', 'mass']
        Kind of distribution.
    sizeasmass : bool
        Switch size input between chain-length (if `False`) or molar
        mass (if `True`).

    Returns
    -------
    float | FloatArray
        Cumulative probability.
    """
    # Check inputs
    kind = self._verify_kind(kind)
    if kind == 'gpc':
        custom_error('kind', kind, ValueError,
                     "Please use `mass` instead.")
    order = self.kind_order[kind]
    self._verify_sizeasmass(sizeasmass)
    # Convert list to ndarray
    if isinstance(size, (list, tuple)):
        size = np.array(size)
    # Math is done by the corresponding subclass method
    return self._cdf(size, order, sizeasmass)

pdf ¤

pdf(
    size: Union[float, FloatArrayLike],
    kind: Literal["number", "mass", "gpc"] = "mass",
    sizeasmass: bool = False,
) -> Union[float, FloatArray]

Evaluate the probability density function, \(p(k)\).

PARAMETER DESCRIPTION
size

Chain length or molar mass.

TYPE: float | FloatArrayLike

kind

Kind of distribution.

TYPE: Literal['number', 'mass', 'gpc'] DEFAULT: 'mass'

sizeasmass

Switch size input between chain-length (if False) or molar mass (if True).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
float | FloatArray

Probability density.

Source code in src/polykin/distributions/base.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def pdf(self,
        size: Union[float, FloatArrayLike],
        kind: Literal['number', 'mass', 'gpc'] = 'mass',
        sizeasmass: bool = False,
        ) -> Union[float, FloatArray]:
    r"""Evaluate the probability density function, $p(k)$.

    Parameters
    ----------
    size : float | FloatArrayLike
        Chain length or molar mass.
    kind : Literal['number', 'mass', 'gpc']
        Kind of distribution.
    sizeasmass : bool
        Switch size input between chain-length (if `False`) or molar
        mass (if `True`).

    Returns
    -------
    float | FloatArray
        Probability density.
    """
    # Check inputs
    self._verify_sizeasmass(sizeasmass)
    order = self.kind_order[self._verify_kind(kind)]
    # Convert list to ndarray
    if isinstance(size, (list, tuple)):
        size = np.array(size)
    # Math is done by the corresponding subclass method
    return self._pdf(size, order, sizeasmass)

plot ¤

plot(
    kind: Union[
        Literal["number", "mass", "gpc"],
        list[Literal["number", "mass", "gpc"]],
    ] = "mass",
    sizeasmass: bool = False,
    xscale: Literal["auto", "linear", "log"] = "auto",
    xrange: Union[tuple[float, float], None] = None,
    cdf: Literal[0, 1, 2] = 0,
    title: Optional[str] = None,
    axes: Optional[list[Axes]] = None,
    return_objects: bool = False,
) -> Optional[tuple[Optional[Figure], list[Axes]]]

Plot the chain-length distribution.

PARAMETER DESCRIPTION
kind

Kind(s) of distribution.

TYPE: Literal['number', 'mass', 'gpc'] DEFAULT: 'mass'

sizeasmass

Switch size input between chain-length (if False) or molar mass (if True).

TYPE: bool DEFAULT: False

xscale

x-axis scale.

TYPE: Literal['auto', 'linear', 'log'] DEFAULT: 'auto'

xrange

x-axis range.

TYPE: tuple[float, float] | None DEFAULT: None

cdf

y-axis where cdf is displayed. If 0 the cdf is not displayed; if 1 the cdf is displayed on the primary y-axis; if 2 the cdf is displayed on the secondary axis.

TYPE: Literal[0, 1, 2] DEFAULT: 0

title

Title of plot. If None, the object name will be used.

TYPE: str | None DEFAULT: None

axes

Matplotlib Axes object.

TYPE: list[Axes] | None DEFAULT: None

return_objects

If True, the Figure and Axes objects are returned (for saving or further manipulations).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple[Figure | None, list[Axes]] | None

Figure and Axes objects if return_objects is True.

Source code in src/polykin/distributions/base.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def plot(self,
         kind: Union[Literal['number', 'mass', 'gpc'],
                     list[Literal['number', 'mass', 'gpc']]] = 'mass',
         sizeasmass: bool = False,
         xscale: Literal['auto', 'linear', 'log'] = 'auto',
         xrange: Union[tuple[float, float], None] = None,
         cdf: Literal[0, 1, 2] = 0,
         title: Optional[str] = None,
         axes: Optional[list[Axes]] = None,
         return_objects: bool = False
         ) -> Optional[tuple[Optional[Figure], list[Axes]]]:
    """Plot the chain-length distribution.

    Parameters
    ----------
    kind : Literal['number', 'mass', 'gpc']
        Kind(s) of distribution.
    sizeasmass : bool
        Switch size input between chain-length (if `False`) or molar
        mass (if `True`).
    xscale : Literal['auto', 'linear', 'log']
        x-axis scale.
    xrange : tuple[float, float] | None
        x-axis range.
    cdf : Literal[0, 1, 2]
        y-axis where cdf is displayed. If `0` the cdf is not displayed; if
        `1` the cdf is displayed on the primary y-axis; if `2` the cdf is
        displayed on the secondary axis.
    title : str | None
        Title of plot. If `None`, the object name will be used.
    axes : list[Axes] | None
        Matplotlib Axes object.
    return_objects : bool
        If `True`, the Figure and Axes objects are returned (for saving or
        further manipulations).

    Returns
    -------
    tuple[Figure | None, list[Axes]] | None
        Figure and Axes objects if return_objects is `True`.
    """
    # Check inputs
    kind = self._verify_kind(kind, accept_list=True)
    self._verify_sizeasmass(sizeasmass)
    check_in_set(xscale, {'linear', 'log', 'auto'}, 'xscale')
    check_in_set(cdf, {0, 1, 2}, 'cdf')
    if isinstance(kind, str):
        kind = [kind]

    # x-axis scale
    if xscale == 'auto' and set(kind) == {'gpc'}:
        xscale = 'log'
    elif xscale == 'log':
        pass
    else:
        xscale = 'linear'

    # x-axis range
    if xrange is not None:
        check_valid_range(xrange, 0., np.inf, 'xrange')
    else:
        vrange = self._xrange_plot(sizeasmass)  # type : ignore
        if xscale == 'log' and log10(vrange[1]/vrange[0]) > 3 and \
                isinstance(self, (AnalyticalDistribution,
                                  MixtureDistribution)):
            vrange[1] *= 10
        xrange = tuple(vrange)  # type: ignore

    # x-axis vector
    npoints = 200
    if isinstance(self, MixtureDistribution):
        npoints += 100*(len(self.components)-1)
    if xscale == 'log':
        x = np.geomspace(*xrange, npoints)  # type: ignore
    else:
        x = np.linspace(*xrange, npoints)  # type: ignore

    # x-axis label
    if sizeasmass:
        label_x = f"Molar mass [{self.units['molar_mass']}]"
    else:
        label_x = "Chain length"

    # Create axis if none is provided
    ax2 = None
    if axes is None:
        ext_mode = False
        fig, ax = plt.subplots(1, 1)
        if title is None:
            title = f"Distribution: {self.name}"
        fig.suptitle(title)
        if cdf == 2:
            ax2 = ax.twinx()
    else:
        ext_mode = True
        fig = None
        ax = axes[0]
        if cdf == 2:
            ax2 = axes[1]

    # y-values
    for mykind in kind:
        if cdf != 1:
            y1 = self.pdf(x, kind=mykind, sizeasmass=sizeasmass)
        if cdf > 0:
            if mykind == 'gpc':
                _mykind = 'mass'
            else:
                _mykind = mykind
            y2 = self.cdf(x, kind=_mykind, sizeasmass=sizeasmass)
        if cdf == 1:
            y1 = y2
        if ext_mode:
            label = self.name
            if label == '':
                label = '?'
        else:
            label = mykind
        ax.plot(x, y1, label=label)
        if cdf == 2:
            ax2.plot(x, y2, linestyle='--')

    # y-axis and labels
    label_y_pdf = 'Relative abundance'
    label_y_cdf = 'Cumulative probability'
    bbox_to_anchor = (1.05, 1.0)
    if cdf == 0:
        label_y1 = label_y_pdf
    elif cdf == 1:
        label_y1 = label_y_cdf
    elif cdf == 2:
        label_y1 = label_y_pdf
        label_y2 = label_y_cdf
        ax.set_ylabel(label_y1)
        ax2.set_ylabel(label_y2)
        bbox_to_anchor = (1.1, 1.0)
    else:
        raise ValueError
    ax.set_xlabel(label_x)
    ax.set_ylabel(label_y1)
    ax.set_xscale(xscale)
    ax.grid(True)
    ax.legend(bbox_to_anchor=bbox_to_anchor, loc="upper left")

    if return_objects:
        return (fig, [ax, ax2])

random ¤

random(
    shape: Optional[Union[int, tuple[int, ...]]] = None
) -> Union[int, IntArray]

Generate random sample of chain lengths according to the corresponding number probability density/mass function.

PARAMETER DESCRIPTION
shape

Sample shape.

TYPE: int | tuple[int, ...] | None DEFAULT: None

RETURNS DESCRIPTION
int | IntArray

Random sample of chain lengths.

Source code in src/polykin/distributions/base.py
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
def random(self,
           shape: Optional[Union[int, tuple[int, ...]]] = None
           ) -> Union[int, IntArray]:
    r"""Generate random sample of chain lengths according to the
    corresponding number probability density/mass function.

    Parameters
    ----------
    shape : int | tuple[int, ...] | None
        Sample shape.

    Returns
    -------
    int | IntArray
        Random sample of chain lengths.
    """
    if self._rng is None:
        self._rng = np.random.default_rng()
    return self._random_length(shape)