# Public GEMS API

The module `gems` is organised in several submodules.

- `gems.libio` contains input/output routines. You want to start with this one
    in order to load the data and pass it to the fitting routines.
- `gems.fit` contains the optimisation routines for fitting the data.
- `gems.libuk` contains all the tools you need to handle the microspeciation
    information.
- `gems.plotter` contains routines for plotting the results obtained
- `gems.report` contains reporting routines

## variable definition

### Free Energy

`dict` where the keys are the microstate codified as a tuple of ones and zeros and the value is a float representing the value of the energy that correspond to that microstate.

    free_energy = {(0, 0, 0): 0.0, (0, 0, 1): -12.41, (0, 1, 0): -13.01,
        (0, 1, 1): -22.14, (1, 0, 0): -10.43, (1, 0, 1): -29.13,
        (1, 1, 0): -27.34, (1, 1, 1): -41.42}

### Microstate

The microstate can be codified either with numbers or letters. A tuple of zeros and ones of the lenght of the number of protonation centres can define each one of the microstates. When the centre s:sub:j is protonated, a 1 occupies that place in the tuple, zero otherwise. A given microstate is generally noted as {sj} which means the collection of 0s and 1s that represent it, e.g. {0, 1, 0, 1} meaning that s1 = 0, s2 = 1, s3 = 0, s4 = 1.

### Microstate Probability

Each microstate has a probability that can be calculated from the free energy.

\[p(\{s_j\}) = \frac{a_{\mathrm{H}}^n e^{-\beta F(\{s_j\})}}{\sum_{\{s_j\}} a_{\mathrm{H}}^n e^{-\beta F(\{s_j\})}}\]

Internally, this variable is stored as a `dict` where the key is a microstate binary tuple and the value is an iterable (like a 1D array) containing the values of the microstate probability for each titration point.

### Macrostate Probability

Each macrostate has a probability that can be calculated according to

\[P_n(a_H) = \frac{\bar{K_n} a_{\rm H}^n}{\sum_{n=0}^N \bar{K_n} a_{\mathrm{H}}^n}\]

### Conditional Probability

\[\pi_n(\{s_j\}) = \frac{e^{-\beta F(\{s_j\})}}{\sum_{\{s_j\}} e^{-\beta F(\{s_j\})}}\]
\[\pi_n(\{s_j\}) = \pi_n({s_j}) P_n(a_H)\]

### Molecule Symmetry

The symmetry of a molecule can be expressed as a string of letters with a multiplier for the sites that are equivalent. For example `A2B` if the molecule has three centres, two of which are equivalent; or `ABC` if the molecule has three different centres.

### A Matrix

The A matrix represents the variation in population (rows) when the

### B Matrix

The B matrix represents the variation of the chemical shift (rows) when the macroscopic protonation degree changes in one unit.

\[\delta_l - \delta^{(0)}_l = \sum_{n=1}^N B_{ln} P_n(a_H)\]

### Delta Matrix

The matrix Δ represents the variation of the chemical shift (rows) when the protonation degree of a particular site (columns) goes from protonated to unprotonated.

\[\delta_l - \delta^{(0)}_l = \sum_{m=1} \Delta_{lm} \theta_m\]

## libuk.py

This module contains the basic tools for microconstants. These functions are loaded by GEMS or they can be used in a standalone python script.

### Microstates Nomenclature

- `name_microstate()`
- `name_terms()`
- `expand_name()`
- `compact_name()`
- `molecule_info()`

### Functions for Multiplicity and Combinatory

- `order_terms()`
- `kdeflation()`
- `comb()`
- `remainder()`
- `generate_microstep()`
- `state_microsteps()`
- `total_microconsts()`
- `total_microstates()`
- `generate_microstate()`
- `generate_all_microstates()`
- `count_microstate()`
- `remove_equivalent_states()`

### Terms calculations

- `fit_free_energy()`
- `microstate_probability()`
- `macrostate_probability()`
- `matrix_a()`
- `matrix_b()`
- `conditional_probability2()`
- `conditional_probability1()`
- `avg_prtdeg()`
- `microstate_multiplicity()`
- `micro_constants2()`
- `micro_constants()`
- `error_macro_constants()`
- `macro_constants()`
- `num_prot_centres()`

`gems.libuk.``avg_prtdeg`(msprob)

  Calculate the average protonation degree.

  This routine uses eq (6) from Borkovec et al. [Borkovec2000]

  \[\theta_m = \frac1N \sum_{\{s_j\}} s_m p(\{s_j\})\]

  Parameters: | msprob (dict) – the microstate probability.
  Returns: | average protonation degree of each centre.
  Return type: | numpy.ndarray

`gems.libuk.``comb`(n, k)

  Combinatorial for n elements and k.

  Parameters: | n (int) – the number of elements k (int) – the k combination, where \(n >= k\)
  Returns: | the combinatorial of n and k
  Return type: | int

`gems.libuk.``compact_name`(input_name)

  Compact a name.

  Parameters: | input_name (str) – an expanded molecule name
  Returns: | the compact name with multipliers
  Return type: | str

  Example

      >>> compact_name('AAABCC')
      A3BC2

  See also

  `expand_name()`

`gems.libuk.``conditional_probability1`(micro_prob, macro_prob)

  Calculate the Conditional Probability.

  This routine uses eq (7) from Borkovec et al. [Borkovec2000]

  \[\pi_n(\{s_j\}) = \pi_n({s_j}) P_n(a_H)\]

  Parameters: | micro_prob (dict) – The Microstate Probability. macro_prob (`numpy.ndarray`) – The Macrostate Probability.

`gems.libuk.``conditional_probability2`(free_enrg)

  Calculate the Conditional Probability of each Microstate.

  \[\pi_n(\{s_j\}) = \frac{e^{-\beta F(\{s_j\})}} {\sum_{\{s_j\}}e^{-\beta F(\{s_j\})} \delta_{n,\sum_js_j}}\]

`gems.libuk.``error_macro_constants`(free_enrg, error_freenrgy)

  Calculate error in macroconstants.

  Parameters: | free_enrg (dict) – dict containing the Free Energy for each microstate. error_free_enrgy (dict) – dict containing the free energy for each microstate.

`gems.libuk.``expand_name`(input_name)

  Expand names with multipliers.

  When a site has high multiplicity it is more convenient to express it with a number rather than with repetition (eg. `A3B2` instead of `AAABB`. This routine converts the former in the latter.

  Parameters: | input_name (str) – a compact name
  Returns: | an expanded name
  Return type: | str

  See also

  `compact_name()`

      >>> expand_name('A3B3C')
      AAABBBC
      >>> expand_name('ABC')
      ABC

`gems.libuk.``fit_free_energy`(microk, lvl1=None, lvl2=None, error=False)

  Calculate the free energy of a system based on parameters.

  The free energy of the system is decomposed in first, second and third order parameters and calculated according to the following equation.

  \[\frac{\beta F(\{s_j\})}{\ln 10} = -\sum_j{p\hat{K}_js_j} + \frac1{2!}\sum_{ij}\varepsilon_{ij}s_is_j + \frac1{3!}\sum_{ijk}\lambda_{ijk}s_is_js_k\]

`gems.libuk.``kdeflation`(n)

  Statistical distribution of equilibrium constants.

  Parameters: | n (int) – the number of protonations
  Yields: | float – the deflation of the constants

`gems.libuk.``macro_constants`(free_enrg: dict)

  Calculate the macro constants from the energy data.

  Applies equation below to calculate the macro constants.

  \[\bar{K_n} = \sum_{\{s_j\}} e^{-\beta F(\{s_j\})} \delta_{n,\sum_js_j}\]

  Parameters: | free_enrg (dict) – dict containing the free energy for each microstate. n_protcentr (int) – The number of protonation centres

`gems.libuk.``macrostate_probability`(macro_consts, ah)

  Calculate probability of a macrostate.

  Apply the equations (8) and (10) from [Borkovec2000] in order to calculate the probability of the macrostates.

  \[P_n(a_H) = \frac{\bar{K_n} a_{\rm H}^n}{\sum_{n=0}^N \bar{K_n} a_{\mathrm{H}}^n}\]

  Parameters: | macro_consts (`numpy.ndarray`) – An array containing the values if the macroconstants. ah (`numpy.ndarray`) – The activity of protons.
  Returns: | The probability of the macrostate.
  Return type: | `numpy.ndarray`

`gems.libuk.``matrix_a`(cond_prob, n_centres)

  Compute matrix A.

  Compute A Matrix using the equation

  \[A_{mn} = \sum_{\{s_j\}} s_m \pi_n(\{s_j\}) \delta_{n,\sum_js_j}\]

  Parameters: | cond_prob (dict) – The Conditional Probability for each microstate as output by `conditional_probability1()` or `conditional_probability2()`. n_centres (int) – The number of protonation centres n_indepctres (int) – The number of independent protonation centres.
  Returns: | The A matrix as defined above.
  Return type: | `numpy.ndarray`

`gems.libuk.``matrix_b`(macro_prob, shifts)

  Least square solving for the equation below.

  Parameters: | macro_prob (`numpy.ndarray`) – shifts (`numpy.ndarray`) – The experimental chemical shifts.

  \[\delta_i = \delta_i^{(0)} + \sum_{m=1}^N B_{ln} P_n(a_{\mathrm{H}})\]

  Warning

  As of now, NumPy does not support linear algebra for masked arrays. Therefore, if a masked array is passed, the linear algebra routines are not used. Instead, a least square minimisation is done. The result should be approximately the same and, for most cases the used will not perceive the difference.

  New in version 0.5.

`gems.libuk.``micro_constants`(molecule, free_enrg)

  Calculate the micro constants from the energy data.

  Parameters: | molecule (str) – The molecule symmetry free_enrg (dict) – dict containing the Free Energy for each microstate.
  Returns: | the values of the microconstants for each microstate and microstep.
  Return type: | dict

`gems.libuk.``micro_constants2`(molecule, lvl1, lvl2, lvl3, elvl1=None, elvl2=None, elvl3=None)

  Calculate the micro constants from parameters.

  \[{\rm p}\bar{K}_{A\{s_j\}} = {\rm p}\bar{K}_i -\sum_j{\varepsilon_{ij}s_j} -frac12 \sum_{jk}{\lambda_{ijk}s_js_k}\]

  Parameters: | molecule (str) – the molecule symmetry lvl1 (`numpy.ndarray`) – a 1D array with first order parameters. lvl2 (`numpy.ndarray`) – a 2D array with second order parameters. lvl3 (`numpy.ndarray`) – a 3D array with third order parameters. elvl1 (`numpy.ndarray`, optional) – a 1D array with first order parameter errors. elvl2 (`numpy.ndarray`, optional) – a 2D array with second order parameter errors. elvl3 (`numpy.ndarray`, optional) – a 3D array with third order parameter errors.

`gems.libuk.``microstate_multiplicity`(molecule, microstate)

  Calculate the multiplicity of a microstate.

  Parameters: | molecule (str) – The molecule symmetry microstate (str) – The string representation of a microstate
  Returns: | the multiplicity of the microstate
  Return type: | int

  Note

  The molecule and microstate strings must be expanded.

      >>> microstate_multiplicity('AABC', 'BC')
      1
      >>> microstate_multiplicity('AABC', 'ABC')
      2

`gems.libuk.``microstate_population`(conditional_probability, molecule)

  Calculate the population for each microstate.

  The population for each microstate is basically computed in the Conditional Probability variable. However, some microstates are equivalent. This routine sums all equivalent microstates together and returns a more sensible result.

  Parameters: | conditional_probability (dict) – the Conditional Probability. molecule (str) – A string representing the Molecule Symmetry.
  Returns: | the microstate population.
  Return type: | dict

`gems.libuk.``microstate_probability`(free_energy, ah)

  Calculate microstate probability from the energy data.

  The probability of a given microstate is calculates from the free energy terms according to:

  \[p(\{s_j\}) = \Xi^{-1} a_H^n e^{-\beta F(\{s_j\})}\]

  Where \(\Xi = \sum_{\{s_j\}} a_H^n e^{-\beta F(\{s_j\})}\) and \(n=\sum_js_j\)

  Parameters: | free_energy (dict) – A dict containing the free energy for each microstate. ah (`numpy.ndarray`) – The activity of protons.
  Returns: | The microstate probability for each microstate
  Return type: | `dict`

`gems.libuk.``mlstsq`(A, B)

  Linear least squares for masked arrays.

  Compute the array x so that \(||Ax - B||\) is mimized.

  Parameters: | A (`numpy.ndarray`) – B (`numpy.ma.MaskedArray`) –
  Returns: | The result
  Return type: | `numpy.ndarray`

  See also

  `scipy.linalg.lstsq()`

  Warning

  This function will be removed when NumPy finally supports masked matrix inversion.

`gems.libuk.``molecule_info`(molecule)

  Info given a molecule symmetry.

  Parameters: | molecule (str) – A string representing the Molecule Symmetry.
  Returns: | info about the molecule symmetry expanded the molecule with multipliers expanded n_params_1 the number of first-order parameters n_params_2 the number of second-order parameters n_params_3 the number of third-order parameters n_protctrs the number of protonation centres
  Return type: | dict

`gems.libuk.``name_microstate`(molecule: str, ms: tuple) → str

  Given a numeric microstate, compute the text version of it.

  Parameters: | molecule (str) – A string representing the Molecule Symmetry. ms (tuple) – a 0/1 tuple representing the microstate.
  Returns: | the name of the microstate.
  Return type: | str

      >>> name_microstate('AABC', (1, 0, 0, 1))
      'AC'
      >>> name_microstate('AAB', (1, 0, 0))
      'A'

`gems.libuk.``name_terms`(molecule, level)

  Name the terms of the molecule at a given level.

  Parameters: | molecule (str) – A string representing the Molecule Symmetry. level (int) – the level (1, 2, or 3) of the parameters
  Returns: | the sorted names of the terms
  Return type: | list

  Example

      >>> name_terms('AABC', 1)
      ['A', 'B', 'C']
      >>> name_terms('AABC', 2)
      ['AA', 'AB', 'AC', 'BC']
      >>> name_terms('AABC', 3)
      ['AAB', 'AAC', 'ABC']

`gems.libuk.``num_prot_centres`(data) → int

  Compute the number of protonation centres based on dict of data.

  Parameters: | data (`dict`) – any type of data where the keys are a tuple of zeros and nones indicating the microstate.
  Returns: | the number of protonation centres.
  Return type: | int

`gems.libuk.``order_terms`(molecule, n)

  Return valid combinations of sites of order n.

  Given a molecule, n-th order combinations of the sites defined by the symmetry. Results are sorted.

  Parameters: | molecule (str) – a string defining the summetry of the molecule. n (int) – the order of interactions, usually n=2 or n=3.
  Returns: | valid n-th order combinations
  Return type: | list

`gems.libuk.``remove_equivalent_states`(molecule, data)

  Remove microstates that are equivalent based on molecule symmetry.

  Parameters: | molecule (str) – a string representing the molecule symmetry data (dict) – any data where the keys are the microsite numerical representation.
  Returns: | The same data but with the entries that are symmetrically equivalente removed.
  Return type: | dict

`gems.libuk.``total_microstates`(microstates)

  Calculate total number of microstates.

## report.py

Routines for printing information from the data fitting.

Public API

- `gems.report.report_molecule()` for printing a report based on the molecule symmetry.
- `gems.report.minimal_report()` for a small report
- `gems.report.print_report()` for a full report. It includes the minimal report.
- `gems.report.generate_scheme()`

Auxiliary functions

- `gems.report.section()`
- `gems.report.print_residuals()`
- `gems.report.print_nuclei_influence()`
- `gems.report.print_microstates()`
- `gems.report.print_deltamatrix()`
- `gems.report.print_correlation()`
- `gems.report.print_bmatrix()`
- `gems.report.print_amatrix()`
- `gems.report.print_array_half()`
- `gems.report.print_array_full()`
- `gems.report.print_array_sorted()`
- `gems.report.print_parameters()`
- `gems.report.print_populations()`
- `gems.report.prefit()`

`gems.report.``generate_scheme`(molecule)

  Generate the possible protonation pathways for a given molecule.

  Parameters: | molecule (str) – A string representing the expanded molecule symmetry.
  Returns: | each element is a `dict` whose keys are the possible microstates and the values are sets which contain the possible protonation sites available.
  Return type: | list

      >>> gems.report.generate_scheme('AAB')
      [{'': {'A', 'B'}},
       {'B': {'A'}, 'A': {'A', 'B'}},
       {'AB': {'A'}, 'AA': {'B'}},
       {'AAB': set()}]

`gems.report.``minimal_report`(infodict)

  Print minimal report.

`gems.report.``prefit`(title, n_points, n_data)

  Print initial message.

`gems.report.``print_amatrix`(amatrix, molecule, **kwargs)

  Print report on A Matrix.

  Parameters: | amatrix (`numpy.ndarray`) – the A matrix. molecule (str) – A string representing the expanded molecule symmetry. kwargs (dict) – this is ignored

`gems.report.``print_array_full`(array, labels)

  Print a full array with labels.

  Parameters: | array (`numpy.ndarray`) – The array to print labels (sequence) – the labels for each row/column of the array

`gems.report.``print_array_half`(array, labels)

  Print a triangular array with labels.

  Parameters: | array (`numpy.ndarray`) – The array to print labels (sequence) – the labels for each row/column of the array

`gems.report.``print_array_sorted`(array, labels, n=10)

  Print the n highest values of the array.

  Parameters: | array (`numpy.ndarray`) – The array to print labels (sequence) – the labels for each row/column of the array n (int, optional) – the number of entries to print

`gems.report.``print_bmatrix`(bmatrix, labels, **kwargs)

  Print report on B Matrix.

  Parameters: | bmatrix – labels – kwargs (dict) – this is ignored

`gems.report.``print_correlation`(corr, molecule)

  Print information on the correlation matrix.

`gems.report.``print_deltamatrix`(dmatrix, delta_span, labels, molecule, **kwargs)

  Print report on Delta Matrix.

  Parameters: | dmatrix – delta_span – labels – molecule – kwargs (dict) – this is ignored

`gems.report.``print_macroconstants`(log_macroconstants, error_log_macroconstants, **kwargs)

  Print the macroconstant report.

  Parameters: | log_macroconstants (`numpy.ndarray`) – error_log_macroconstants (`numpy.ndarray`) – kwargs (dict) – this is ignored

`gems.report.``print_microstates`(molecule, free_energy, error_free_energy, microconstants, microstate_population, **kwargs)

  Print the microstates.

  Parameters: | molecule (str) – A string representing the expanded molecule symmetry. free_energy (dict) – the free energy error_free_energy (dict) – the error of the free energy conditional_probability (dict) – the conditional microstate probability microconstants (iterable) – kwargs (dict) – this is ignored

`gems.report.``print_nuclei_influence`(xsmooth, ysmooth, labels, centres_unique, centres_occupation, **kwargs)

  Print the influence of each nucleus in each protonation step.

  Parameters: | xsmooth (`numpy.ndarray`) – ysmooth (`numpy.ndarray`) – labels (sequence) – centres_unique (`numpy.ndarray`) – centers_occupation (`numpy.ndarray`) – kwargs (dict) – this is ignored

`gems.report.``print_parameters`(fit1, err1, fit2, err2, fit3, err3, molecule)

  Print report about the parameters.

`gems.report.``print_populations`(n_microcts, n_protctrs, centres_unique, idx_unique, theta, xvalues, macrostate_probability, **kwargs)

  Print information of population analysis.

  Parameters: | n_microcts (int) – the number of microconstants in the system n_protctrs (int) – the number of protonation centres centres_unique – idx_unique – theta – xvalues – macrostate_probability – kwargs (dict) – this is ignored

`gems.report.``print_report`(infodict)

  Print report.

  Parameters: | infodict (dict) – a `dict` containing all the infomation.

`gems.report.``print_residuals`(residuals, pD, shifts, labels, num=20)

  Print the part of the report dealing with residuals.

  Given a list of residuals produced by the fitting, print the larges n values.

  Parameters: | residuals (`numpy.ndarray`) – pD (`numpy.ndarray`) – the x-values shifts (`numpy.ndarray`) – the y-values labels (iterable) – the labels associated with y-values num (int, default=20) – the number of residuals to print

`gems.report.``print_residuals_uv`(residuals, pH, absorbance, wavelength, num=20)

  Print the part of the report dealing with residuals.

  Given a list of residuals produced by the fitting, print the larges n values.

  Parameters: | residuals (`numpy.ndarray`) – pD (`numpy.ndarray`) – the x-values shifts (`numpy.ndarray`) – the y-values labels (iterable) – the labels associated with y-values num (int, default=20) – the number of residuals to print

`gems.report.``report_molecule`(molecule)

  Print report of a given molecule.

  Parameters: | molecule (str) – A string representing the expanded molecule symmetry.

`gems.report.``section`(text)

  Separate sections.

## fit.py

All the routines related to fitting.

Public Functions: * `do_fit()` * `calc_error_free_energy()` * `fit_shifts2()` * `calc_residuals2()` * `fit_shifts()` * `calc_residuals()` * `rearrange_parameters()` * `arrange_parameters()`

Auxiliary Functions: * `postfit()` * `fobj()` * `first_term()` * `build_terms()`

`gems.fit.``arrange_parameters`(expmolec, initvals, order=3)

  Build the initial parameter array from initial guess.

  Construct an initial array filled with zeros and then insert the given parameters in its proper places, leaving the not given parameters as zeros. Additional initial values given are ignored.

  Parameters: | expmolec (str) – a string defining the expanded symmetry of the molecule. initvals (iterable) – list of initial values order (int) – the order of interactions (1, 2 or 3)
  Returns: | A 1D array with the parameters arranged in the proper order.
  Return type: | `numpy.ndarray`
  Raises: | `ValueError` – if the order parameter is not within 1–3.

`gems.fit.``aux_fitting1`(title, pH, yvalues, molecule, ini_vals, order, flag_uv)

  Auxiliary function for fitting routines.

`gems.fit.``build_terms`(molecule, args=None)

  Construct epsilon and lambda matrices from parameters.

  Parameters: | molecule (str) – a string defining the summetry of the molecule. args (sequence) – a sequence containing the parameters
  Returns: | the first element is a 2D array containing the binary terms; the second is a 3D array containing the tertiary terms.
  Return type: | tuple

`gems.fit.``calc_error_free_energy`(molecule, variance, n_microcts)

  Calculate the error in free energy.

  Parameters: | molecule (str) – the symmetry of the molecule variance (sequence) – the variance in the free energy n_microcts (int) – the number of microconstants

`gems.fit.``calc_residuals`(free_energy, shifts, proton_activity)

  Calculate the residuals.

  The fitting is done by equation \(\delta_l = \delta_l^{(0)} + \sum_{n=1}^N B_{ln} P_n (a_H)\) by fitting the experimental chemical shifts to the calculated \(P_n(a_H)\)

  Parameters: | free_energy (`dict`) – the free energy shifts (`numpy.ndarray`) – the chemical shifts proton_activity (`numpy.ndarray`) – the proton activity
  Returns: | the residuals
  Return type: | `numpy.ndarray`

`gems.fit.``calc_residuals2`(free_energy, shifts, proton_activity)

  Calculate the residuals.

  The fitting is done by equation \(\delta_l = \delta_l^{(0)} + \sum_{m=1}^N \Delta_{lm} P_n (a_H)\) by fitting the experimental chemical shifts to the calculated \(P_n(a_H)\)

  Parameters: | free_energy (`dict`) – the free energy shifts (`numpy.ndarray`) – the chemical shifts proton_activity (`numpy.ndarray`) – the proton activity
  Returns: | the residuals
  Return type: | `numpy.ndarray`

`gems.fit.``do_fit`(init_vars, order, expmolec, ah, shifts, weights=1.0)

  Fit data.

  Calls `scipy.optimization.minimize()` in order to minimize `fobj()`.

  Parameters: | init_vars (`numpy.ndarray`) – order (int) –

  Changed in version 0.5: Added option weights

`gems.fit.``first_term`(molecule, terms)

  Return first term.

`gems.fit.``fit_shifts`(macro_prob, shifts)

  Return calculated chemical shifts.

  The calculated chemical shifts are computed according to the equation below. The parameter shifts can be a `numpy.ma.ndarray`; in this case, the missing values are zeroed.

  \[\delta^{\rm calc} = P^{+}_n(a_{\mathrm{H}}) \cdot \delta^{\rm exp} \cdot P_n(a_{\mathrm{H}})\]

  Parameters: | macro_prob (`numpy.ndarray`) – The macrostate probability. shifts (`numpy.ndarray`) – The experimental chemical shifts.
  Returns: | the calculated chemical shifts.
  Return type: | `numpy.ndarray`

`gems.fit.``fit_shifts2`(theta, shifts)

  Return calculated chemical shifts.

  The calculated chemical shifts are computed according to the equation below. The parameter shifts can be a `numpy.ma.ndarray`; in this case, the missing values are zeroed.

  \[\delta^{\rm calc} = \theta \cdot \left(\delta^{\rm exp} \cdot \theta^+\right)\]

  Parameters: | macro_prob (`numpy.ndarray`) – The macrostate probability. shifts (`numpy.ndarray`) – The experimental chemical shifts.
  Returns: | the calculated chemical shifts.
  Return type: | `numpy.ndarray`

`gems.fit.``fobj`(x, *args)

  Objective function to be used with `minimize()`.

  Parameters: | x (`numpy.ndarray`) – A 1D array with the fitting parameters args[0] (int) – the parameter range to fit (1, 2 or 3). args[1] (str) – the molecule symmetry. args[2] (`numpy.ndarray`) – the activity of protons args[3] (`numpy.ndarray`) – the experimental data where the titration points are arranged in rows and nuclei are arranged in columns. args[4] (float or `numpy.ndarray`) – the weights to be used for minimization.
  Returns: | the sum of the residuals squared.
  Return type: | float

`gems.fit.``postfit`(retval, smooth_points=100)

  Complete calculations after the fitting has been done.

  The input is a `dict` with some data (see below). This function updates the dict with a lot of additional data.

  - n_nuclei (`int`): the number of nuclei
  - molecule (str): the symmetry of the molecule
  - n_microcts (int): the number of microconstants in the system
  - n_protctrs (int): the number of protonation centres
  - ah (`numpy.ndarray`):
  - iterations (int): the number of iterations
  - function_evaluations (int): the number of times the `fobj()` has
      been evaluated.
  - success
  - message
  - chisq (float): the final sum of squared residuals
  - covariance
  - fit_params1 (`numpy.ndarray`):
  - fit_params2 (`numpy.ndarray`):
  - fit_params3 (`numpy.ndarray`):
  - err_params1 (`numpy.ndarray`):
  - err_params2 (`numpy.ndarray`):
  - err_params3 (`numpy.ndarray`):
  - correlation
  - free_energy (dict):
  - error_free_energy
  - residuals
  - microstate_probability
  - theta
  - conditional_probability
  - macroconstants
  - error_macroconstants
  - macrostate_probability
  - microstate_population (dict):
  - bmatrix (`numpy.ndarray`):
  - microconstants
  - centres_unique
  - idx_unique
  - amatrix
  - dmatrix
  - delta_span
  - smooth_ah
  - xsmooth
  - ysmooth
  - distribution
  - centres_occupation

  Parameters: | retval (dict) – a `dict` that must contain the following fields xvalues (`numpy.ndarray`), yvalues (`numpy.ndarray`), result (`scipy.optimize.OptimizationResult`), labels (sequence), molecule (str). This variable is modified during the call. smooth_points (int) – the number of points that will be used in the smooth fitting result. n_nuclei (*) – The number of nuclei

`gems.fit.``rearrange_parameters`(param, param_errors, molecule, order)

  Rearrange a flattened array of parameters into order-sorted arrays.

  Parameters: | param (iterable) – a 1D array containing ordered parameters param_errors (iterable) – a 1D array containing ordered parameter errors molecule (str) – A string representing the molecule symmetry order (int) – A number indicating the interaction order level (1..3)
  Returns: | fit_params1, err_params1, fit_params2, err_params2, fit_params3, err_params3
  Return type: | tuple

`gems.fit.``spectra_weighting`(data, weight_param=0.01)

  Calculate automatic spectra weighting.

  Parameters: | data (`numpy.ndarray`) – w0 (float) –
  Returns: |
  Return type: | `numpy.ndarray`

## plotter.py

Collection of routines for plotting data.

### Plotting functions with pyplot

- `do_plot()`
- `plot_fitting()`

### Plotting functions in Axes

- `plot_distribution()`
- `plot_dshifts()`
- `plot_microconstants()`
- `plot_energies()`
- `plot_shifts()`
- :func`plot_uvbmatrix`
- :func`plot_uv_residuals`

### Auxiliary plotting functions

- `point_microconstants()`
- `annotate_microconstants()`
- `make_lines()`

class `gems.plotter.``Plotter`(master)

  Bases: `matplotlib.backends.backend_tkagg.FigureCanvasTkAgg`

  Override FigureCanvas.

  `clear`()

`gems.plotter.``annotate_microconstants`(xvalues, yvalues, labels, axes)

  Insert microconstants annotation into graph.

  Parameters: | xvalues (iterable) – the x values of the label position. yvalues (iterable) – the y values of the label position. labels (iterable) – the labels axes (`matplotlib.axes.Axes`) – the axes to plot into.

`gems.plotter.``do_plot`(infodict)

  Plot everything for NMR data.

  Pops new windows with the plots for all the information contained in the dict.

`gems.plotter.``do_plot_spectra`(infodict)

  Plot everything for spectra.

  Pops new windows with the plots for all the information contained in the dict.

`gems.plotter.``make_lines`(micro_constants)

  Calculate where to draw the energy levels.

  Parameters: | micro_constants (dict) – the microconstants
  Returns: | the coordinates of the lines to be drawn in the format ((x1, y1), (x2, y2))
  Return type: | list

`gems.plotter.``plot_distribution`(axes, xsmooth, distribution, centres_occupation, centres_unique, n_protctrs, **kwargs)

  Plot the macrospecies and microspecies distribution.

  Parameters: | axes (`matplotlib.Axes.axes`) – the axes to plot into. xsmooth – distribution – centres_occupation – centres_unique – n_protctrs – kwargs (dict) – Ignored

  See also

  `gems.fit.postfit()`

`gems.plotter.``plot_dshifts`(axes, lst, llabels, xsmooth, ysmooth, centres_occupation, centres_unique, **kwargs)

`gems.plotter.``plot_energies`(axes, molecule, free_energy, **kwargs)

  Plot energies.

`gems.plotter.``plot_fitting`(xvalues, yvalues, xsmooth, ysmooth, distribution, centres_occupation, labels, centres_unique, **kwargs)

  Plot fitting.

`gems.plotter.``plot_microconstants`(axes, stepwise_macroconstants, molecule, microconstants, n_protctrs, **kwargs)

  Plot microconstants.

`gems.plotter.``plot_shifts`(axes, lst, llabels, xvalues, yvalues, xsmooth, ysmooth, distribution, centres_occupation, **kwargs)

  Plot chemical shifts and distribution in background.

`gems.plotter.``plot_uv_residuals`(axes, xdim, residuals)

  Plot residuals.

  Parameters: | axes (`matplotlib.Axes.axes`) – the axes to plot into.

`gems.plotter.``plot_uvbmatrix`(axes, wavelength, bmatrix, **kwargs)

`gems.plotter.``point_microconstants`(molecule, micro_constants)

  Calculate positions for microconstant labels.

  Parameters: | molecule (str) – micro_constants (iterable) –
  Returns: | where [0] and [1] are the x and y coordinates of the label, and [2] are the labels.
  Return type: | tuple

## libio.py

This module contains the reading/writing and import/export routines.

Import/export fitting data to/from NumPy array * `import_numpy()` * `export_numpy()`

Load data from file * `load_stream()` * `load_spectra_stream()` * `load_file_spectra()` * `load_file()`

Auxiliary/Internal functions * `test_modules()` * `print_welcome()` * `prune_data()`

`gems.libio.``export_numpy`(filename: str, infodict: dict)

  Write all information into NumPy format file.

  Parameters: | filename (`str`) – the file name. infodict (`dict`) – all the information (see `gems.fit.postfit()`)

`gems.libio.``import_numpy`(filename: str)

  Read information from NumPy format file.

  Uses `numpy.load()` and then applies some type conversions.

  Parameters: | filename (str) – the file to read from.
  Returns: | the data read
  Return type: | dict

  New in version 0.6.

`gems.libio.``load_file`(filename: str)

  Open file and load its contents.

  A text file containing the data to be fit. See Data File Format.

  Parameters: | filename (`str`) – The file to read from
  Returns: | title (str), molecule (str), initial values (list of floats), labels (list of strings), pH (`numpy.ndarray`), shifts (`numpy.ndarray`).
  Return type: | tuple

  See also

  `gems.libio.loadstream()`

`gems.libio.``load_file_spectra`(filename: str)

  Open file containing spectral data and load its contents.

  Parameters: | filename (str) – The file to read from
  Returns: | title (str), molecule (str), initial values (list of floats), pH (`numpy.ndarray`), wavelength (`numpy.ndarray`), absorbances (`numpy.ndarray`).
  Return type: | tuple

  See also

  `load_file()`

`gems.libio.``load_spectra_stream`(streamio)

  Read datastream containing spectral data.

  Parameters: | streamio (StreamIOr) – The data stream
  Returns: | title (str), molecule (str), initial values (list of floats), pH (`numpy.ndarray`), wavelength (`numpy.ndarray`), absorbances (`numpy.ndarray`).
  Return type: | tuple

  See also

  `load_file_spectra()`

`gems.libio.``load_stream`(streamio)

  Load data from data stream.

  For details on the file data format, see Data File Format.

  Parameters: | streamio (file) – The strem to read data from.
  Returns: | title (str), molecule (str), initial values (list of floats), labels (list of strings), pH (`numpy.ndarray`), shifts (`numpy.ndarray`).
  Return type: | tuple

`gems.libio.``print_welcome`()

  Print welcome message.

`gems.libio.``prune_data`(array, rows_ignored, cols_ignored, row_labels, col_labels)

  Remove unused data from the bulk of data.

  Parameters: | array (`numpy.ndarray`) – the initial data. rows_ignored (sequence) – cols_ignored (sequence) – row_labels (sequence) – col_labels (sequence) –
  Returns: | item[0] is `numpy.ndarray` the pruned data, item[1] and item[2] are the respective row_labels and col_labels pruned.
  Return type: | tuple

`gems.libio.``test_modules`()

  Test the modules.