Fitting allosteric parameters

Fitting allosteric parameters#

%%capture
%run receptor_tools.ipynb
import numpy as np
import random
from matplotlib import pyplot as plt
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
AttributeError: _ARRAY_API not found
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
/tmp/ipykernel_11641/2555012149.py in <module>
      2 import numpy as np
      3 import random
----> 4 from matplotlib import pyplot as plt

/usr/lib/python3/dist-packages/matplotlib/__init__.py in <module>
    107 # cbook must import matplotlib only within function
    108 # definitions, so it is safe to import from it here.
--> 109 from . import _api, _version, cbook, docstring, rcsetup
    110 from matplotlib.cbook import MatplotlibDeprecationWarning, sanitize_sequence
    111 from matplotlib.cbook import mplDeprecation  # deprecated

/usr/lib/python3/dist-packages/matplotlib/rcsetup.py in <module>
     25 from matplotlib import _api, cbook
     26 from matplotlib.cbook import ls_mapper
---> 27 from matplotlib.colors import Colormap, is_color_like
     28 from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
     29 from matplotlib._enums import JoinStyle, CapStyle

/usr/lib/python3/dist-packages/matplotlib/colors.py in <module>
     54 import matplotlib as mpl
     55 import numpy as np
---> 56 from matplotlib import _api, cbook, scale
     57 from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
     58 

/usr/lib/python3/dist-packages/matplotlib/scale.py in <module>
     21 import matplotlib as mpl
     22 from matplotlib import _api, docstring
---> 23 from matplotlib.ticker import (
     24     NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
     25     NullLocator, LogLocator, AutoLocator, AutoMinorLocator,

/usr/lib/python3/dist-packages/matplotlib/ticker.py in <module>
    134 import matplotlib as mpl
    135 from matplotlib import _api, cbook
--> 136 from matplotlib import transforms as mtransforms
    137 
    138 _log = logging.getLogger(__name__)

/usr/lib/python3/dist-packages/matplotlib/transforms.py in <module>
     44 
     45 from matplotlib import _api
---> 46 from matplotlib._path import (
     47     affine_transform, count_bboxes_overlapping_bbox, update_path_extents)
     48 from .path import Path

ImportError: numpy.core.multiarray failed to import
#G = graphs.HouseGraph()
G = graphs.PathGraph(4)

(G, T, KappaEta, A) = enumerate_allosteric_parameters(G,method='alpha',show=True)
A module that was compiled using NumPy 1.x cannot be run in
NumPy 2.2.6 as it may crash. To support both 1.x and 2.x
versions of NumPy, modules must be compiled with NumPy 2.0.
Some module may need to rebuild instead e.g. with 'pybind11>=2.12'.

If you are a user of the module, the easiest solution will be to
downgrade to 'numpy<2' or try to upgrade the affected module.
We expect that some modules will need time to support NumPy 2.

Traceback (most recent call last):  File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.10/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/usr/lib/python3/dist-packages/sage/repl/ipython_kernel/__main__.py", line 3, in <module>
    IPKernelApp.launch_instance(kernel_class=SageKernel)
  File "/usr/lib/python3/dist-packages/traitlets/config/application.py", line 846, in launch_instance
    app.start()
  File "/usr/lib/python3/dist-packages/ipykernel/kernelapp.py", line 677, in start
    self.io_loop.start()
  File "/usr/lib/python3/dist-packages/tornado/platform/asyncio.py", line 199, in start
    self.asyncio_loop.run_forever()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 603, in run_forever
    self._run_once()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 1909, in _run_once
    handle._run()
  File "/usr/lib/python3.10/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/lib/python3/dist-packages/ipykernel/kernelbase.py", line 461, in dispatch_queue
    await self.process_one()
  File "/usr/lib/python3/dist-packages/ipykernel/kernelbase.py", line 450, in process_one
    await dispatch(*args)
  File "/usr/lib/python3/dist-packages/ipykernel/kernelbase.py", line 357, in dispatch_shell
    await result
  File "/usr/lib/python3/dist-packages/ipykernel/kernelbase.py", line 652, in execute_request
    reply_content = await reply_content
  File "/usr/lib/python3/dist-packages/ipykernel/ipkernel.py", line 353, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/lib/python3/dist-packages/ipykernel/zmqshell.py", line 532, in run_cell
    return super().run_cell(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 2914, in run_cell
    result = self._run_cell(
  File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 2960, in _run_cell
    return runner(coro)
  File "/usr/lib/python3/dist-packages/IPython/core/async_helpers.py", line 78, in _pseudo_sync_runner
    coro.send(None)
  File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 3185, in run_cell_async
    has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
  File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 3377, in run_ast_nodes
    if (await self.run_code(code, result,  async_=asy)):
  File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 3457, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "/tmp/ipykernel_11641/3500602749.py", line 4, in <module>
    (G, T, KappaEta, A) = enumerate_allosteric_parameters(G,method='alpha',show=True)
  File "/tmp/ipykernel_11641/347421326.py", line 36, in enumerate_allosteric_parameters
    G.show(graph_border=True,edge_labels=False)
  File "/usr/lib/python3/dist-packages/sage/graphs/generic_graph.py", line 20195, in show
    return self.graphplot(**plot_kwds).show(**kwds)
  File "/usr/lib/python3/dist-packages/sage/graphs/graph_plot.py", line 1026, in show
    self.plot().show(**kwds)
  File "/usr/lib/python3/dist-packages/sage/misc/decorators.py", line 410, in wrapper
    return func(*args, **kwds)
  File "/usr/lib/python3/dist-packages/sage/plot/graphics.py", line 2133, in show
    dm.display_immediately(self, **kwds)
  File "/usr/lib/python3/dist-packages/sage/repl/rich_output/display_manager.py", line 851, in display_immediately
    plain_text, rich_output = self._rich_output_formatter(obj, rich_repr_kwds)
  File "/usr/lib/python3/dist-packages/sage/repl/rich_output/display_manager.py", line 643, in _rich_output_formatter
    rich_output = self._call_rich_repr(obj, rich_repr_kwds)
  File "/usr/lib/python3/dist-packages/sage/repl/rich_output/display_manager.py", line 601, in _call_rich_repr
    return obj._rich_repr_(self, **rich_repr_kwds)
  File "/usr/lib/python3/dist-packages/sage/plot/graphics.py", line 1000, in _rich_repr_
    return display_manager.graphics_from_save(
  File "/usr/lib/python3/dist-packages/sage/repl/rich_output/display_manager.py", line 731, in graphics_from_save
    save_function(filename, **kwds)
  File "/usr/lib/python3/dist-packages/sage/misc/decorators.py", line 410, in wrapper
    return func(*args, **kwds)
  File "/usr/lib/python3/dist-packages/sage/plot/graphics.py", line 3296, in save
    from matplotlib import rcParams
  File "/usr/lib/python3/dist-packages/matplotlib/__init__.py", line 109, in <module>
    from . import _api, _version, cbook, docstring, rcsetup
  File "/usr/lib/python3/dist-packages/matplotlib/rcsetup.py", line 27, in <module>
    from matplotlib.colors import Colormap, is_color_like
  File "/usr/lib/python3/dist-packages/matplotlib/colors.py", line 56, in <module>
    from matplotlib import _api, cbook, scale
  File "/usr/lib/python3/dist-packages/matplotlib/scale.py", line 23, in <module>
    from matplotlib.ticker import (
  File "/usr/lib/python3/dist-packages/matplotlib/ticker.py", line 136, in <module>
    from matplotlib import transforms as mtransforms
  File "/usr/lib/python3/dist-packages/matplotlib/transforms.py", line 46, in <module>
    from matplotlib._path import (
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
AttributeError: _ARRAY_API not found
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
/tmp/ipykernel_11641/3500602749.py in <module>
      2 G = graphs.PathGraph(Integer(4))
      3 
----> 4 (G, T, KappaEta, A) = enumerate_allosteric_parameters(G,method='alpha',show=True)

/tmp/ipykernel_11641/347421326.py in enumerate_allosteric_parameters(G, **kwargs)
     34 
     35     if verbose or myshow:
---> 36         G.show(graph_border=True,edge_labels=False)
     37 
     38     (BFSVertexList,BFSTree) = G.lex_BFS(tree=True,initial_vertex=Groot)

/usr/lib/python3/dist-packages/sage/graphs/generic_graph.py in show(self, method, **kwds)
  20193         plot_kwds = {k: kwds.pop(k) for k in graphplot_options if k in kwds}
  20194 
> 20195         return self.graphplot(**plot_kwds).show(**kwds)
  20196 
  20197     def plot3d(self, bgcolor=(1,1,1),

/usr/lib/python3/dist-packages/sage/graphs/graph_plot.py in show(self, **kwds)
   1024                 kwds[k] = value
   1025 
-> 1026         self.plot().show(**kwds)
   1027 
   1028     def plot(self, **kwds):

/usr/lib/python3/dist-packages/sage/misc/decorators.py in wrapper(*args, **kwds)
    408             kwds[self.name + "options"] = suboptions
    409 
--> 410             return func(*args, **kwds)
    411 
    412         # Add the options specified by @options to the signature of the wrapped

/usr/lib/python3/dist-packages/sage/plot/graphics.py in show(self, **kwds)
   2131         from sage.repl.rich_output import get_display_manager
   2132         dm = get_display_manager()
-> 2133         dm.display_immediately(self, **kwds)
   2134 
   2135     def xmin(self, xmin=None):

/usr/lib/python3/dist-packages/sage/repl/rich_output/display_manager.py in display_immediately(self, obj, **rich_repr_kwds)
    849             1/2
    850         """
--> 851         plain_text, rich_output = self._rich_output_formatter(obj, rich_repr_kwds)
    852         self._backend.display_immediately(plain_text, rich_output)
    853 

/usr/lib/python3/dist-packages/sage/repl/rich_output/display_manager.py in _rich_output_formatter(self, obj, rich_repr_kwds)
    641         has_rich_repr = isinstance(obj, SageObject) and hasattr(obj, '_rich_repr_')
    642         if has_rich_repr:
--> 643             rich_output = self._call_rich_repr(obj, rich_repr_kwds)
    644         if isinstance(rich_output, OutputPlainText):
    645             plain_text = rich_output

/usr/lib/python3/dist-packages/sage/repl/rich_output/display_manager.py in _call_rich_repr(self, obj, rich_repr_kwds)
    599         if rich_repr_kwds:
    600             # do not ignore errors from invalid options
--> 601             return obj._rich_repr_(self, **rich_repr_kwds)
    602         try:
    603             return obj._rich_repr_(self)

/usr/lib/python3/dist-packages/sage/plot/graphics.py in _rich_repr_(self, display_manager, **kwds)
    998         for file_ext, output_container in preferred:
    999             if output_container in display_manager.supported_output():
-> 1000                 return display_manager.graphics_from_save(
   1001                     self.save, kwds, file_ext, output_container)
   1002 

/usr/lib/python3/dist-packages/sage/repl/rich_output/display_manager.py in graphics_from_save(self, save_function, save_kwds, file_extension, output_container, figsize, dpi)
    729         if dpi is not None:
    730             kwds['dpi'] = dpi
--> 731         save_function(filename, **kwds)
    732         from sage.repl.rich_output.buffer import OutputBuffer
    733         buf = OutputBuffer.from_file(filename)

/usr/lib/python3/dist-packages/sage/misc/decorators.py in wrapper(*args, **kwds)
    408             kwds[self.name + "options"] = suboptions
    409 
--> 410             return func(*args, **kwds)
    411 
    412         # Add the options specified by @options to the signature of the wrapped

/usr/lib/python3/dist-packages/sage/plot/graphics.py in save(self, filename, **kwds)
   3294                              "', '".join(ALLOWED_EXTENSIONS) + "'!")
   3295         else:
-> 3296             from matplotlib import rcParams
   3297             rc_backup = (rcParams['ps.useafm'], rcParams['pdf.use14corefonts'],
   3298                          rcParams['text.usetex'])  # save the rcParams

/usr/lib/python3/dist-packages/matplotlib/__init__.py in <module>
    107 # cbook must import matplotlib only within function
    108 # definitions, so it is safe to import from it here.
--> 109 from . import _api, _version, cbook, docstring, rcsetup
    110 from matplotlib.cbook import MatplotlibDeprecationWarning, sanitize_sequence
    111 from matplotlib.cbook import mplDeprecation  # deprecated

/usr/lib/python3/dist-packages/matplotlib/rcsetup.py in <module>
     25 from matplotlib import _api, cbook
     26 from matplotlib.cbook import ls_mapper
---> 27 from matplotlib.colors import Colormap, is_color_like
     28 from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
     29 from matplotlib._enums import JoinStyle, CapStyle

/usr/lib/python3/dist-packages/matplotlib/colors.py in <module>
     54 import matplotlib as mpl
     55 import numpy as np
---> 56 from matplotlib import _api, cbook, scale
     57 from ._color_data import BASE_COLORS, TABLEAU_COLORS, CSS4_COLORS, XKCD_COLORS
     58 

/usr/lib/python3/dist-packages/matplotlib/scale.py in <module>
     21 import matplotlib as mpl
     22 from matplotlib import _api, docstring
---> 23 from matplotlib.ticker import (
     24     NullFormatter, ScalarFormatter, LogFormatterSciNotation, LogitFormatter,
     25     NullLocator, LogLocator, AutoLocator, AutoMinorLocator,

/usr/lib/python3/dist-packages/matplotlib/ticker.py in <module>
    134 import matplotlib as mpl
    135 from matplotlib import _api, cbook
--> 136 from matplotlib import transforms as mtransforms
    137 
    138 _log = logging.getLogger(__name__)

/usr/lib/python3/dist-packages/matplotlib/transforms.py in <module>
     44 
     45 from matplotlib import _api
---> 46 from matplotlib._path import (
     47     affine_transform, count_bboxes_overlapping_bbox, update_path_extents)
     48 from .path import Path

ImportError: numpy.core.multiarray failed to import
n_states=G.order()
n_kappa=n_states-1
n_kappa_plus_eta = A.ngens()
n_eta=n_kappa_plus_eta-n_kappa
kappa_list = [A.gen(k) for k in range(n_kappa)]
print(f'kappa_list = {kappa_list}\n')

eta_list = [A.gen(k) for k in range(n_kappa,n_kappa_plus_eta)]
print(f'eta_list = {eta_list}\n')

phi=normalize(random_binary_array(n_states))
#print(f'phi = {phi}\n')
print('phi = [' + ', '.join([f'{x:.2f}' for x in phi]) + ']')

Phi = dimerize(phi)
#print(f'Phi = {Phi}')
print('\nPhi = ')
for P in Phi:
    print('      [' + ', '.join([f'{x:.2f}' for x in P]) + ']')
kappa_list = [kappa_b, kappa_c, kappa_d]

eta_list = [eta_bb, eta_bc, eta_cc, eta_bd, eta_cd, eta_dd]

phi = [0.00, 0.50, 0.50, 0.00]

Phi = 
      [0.00, 0.00, 0.00, 0.00]
      [0.00, 0.50, 0.25, 0.00]
      [0.00, 0.00, 0.50, 0.00]
      [0.00, 0.00, 0.00, 0.00]
# create the symbolic binding curve 
FBindingKappaEta=make_symbolic_dimer_binding_curve(Phi,KappaEta)
show(FBindingKappaEta)
print(f'binding = {FBindingKappaEta}\n')
\(\displaystyle \frac{0.5 \kappa_{b}^{2} \kappa_{c}^{2} \eta_{\mathit{bb}} \eta_{\mathit{bc}}^{2} \eta_{\mathit{cc}} + 0.5 \kappa_{b}^{2} \kappa_{c} \eta_{\mathit{bb}} \eta_{\mathit{bc}} + 0.5 \kappa_{b}^{2} \eta_{\mathit{bb}}}{\kappa_{b}^{2} \kappa_{c}^{2} \kappa_{d}^{2} \eta_{\mathit{bb}} \eta_{\mathit{bc}}^{2} \eta_{\mathit{cc}} \eta_{\mathit{bd}}^{2} \eta_{\mathit{cd}}^{2} \eta_{\mathit{dd}} + 2.0 \kappa_{b}^{2} \kappa_{c}^{2} \kappa_{d} \eta_{\mathit{bb}} \eta_{\mathit{bc}}^{2} \eta_{\mathit{cc}} \eta_{\mathit{bd}} \eta_{\mathit{cd}} + \kappa_{b}^{2} \kappa_{c}^{2} \eta_{\mathit{bb}} \eta_{\mathit{bc}}^{2} \eta_{\mathit{cc}} + 2.0 \kappa_{b}^{2} \kappa_{c} \kappa_{d} \eta_{\mathit{bb}} \eta_{\mathit{bc}} \eta_{\mathit{bd}} + 2.0 \kappa_{b}^{2} \kappa_{c} \eta_{\mathit{bb}} \eta_{\mathit{bc}} + 2.0 \kappa_{b} \kappa_{c} \kappa_{d} + \kappa_{b}^{2} \eta_{\mathit{bb}} + 2.0 \kappa_{b} \kappa_{c} + 2.0 \kappa_{b} + 1.0}\)
binding = (0.5*kappa_b^2*kappa_c^2*eta_bb*eta_bc^2*eta_cc + 0.5*kappa_b^2*kappa_c*eta_bb*eta_bc + 0.5*kappa_b^2*eta_bb)/(kappa_b^2*kappa_c^2*kappa_d^2*eta_bb*eta_bc^2*eta_cc*eta_bd^2*eta_cd^2*eta_dd + 2.0*kappa_b^2*kappa_c^2*kappa_d*eta_bb*eta_bc^2*eta_cc*eta_bd*eta_cd + kappa_b^2*kappa_c^2*eta_bb*eta_bc^2*eta_cc + 2.0*kappa_b^2*kappa_c*kappa_d*eta_bb*eta_bc*eta_bd + 2.0*kappa_b^2*kappa_c*eta_bb*eta_bc + 2.0*kappa_b*kappa_c*kappa_d + kappa_b^2*eta_bb + 2.0*kappa_b*kappa_c + 2.0*kappa_b + 1.0)
# add ligand dependencies randomly or manually
manual = False
var('X')
if manual:
    d_kappa_X = dict({kappa_b: kappa_b*X, kappa_c: kappa_c*X})
else:
    def Round_To_n(x, n):
        return round(x, -int(np.floor(np.sign(x) * np.log10(abs(x)))) + n)
    d_kappa_X=dict()
    num_X = 0
    while num_X == 0: # make sure there is at least one ligand binding edge (kappa*X)
        for kappa in kappa_list:
            k=Round_To_n(np.random.exponential(scale=1.0),2)
            ligand_prob = 0.4
            if np.random.random() <= ligand_prob:
                d_kappa_X[kappa]=k*X
                num_X += 1
            else:
                d_kappa_X[kappa]=k
print(d_kappa_X)
FBindingEtaX=FBindingKappaEta.subs(d_kappa_X)
show(FBindingEtaX)
print(f'binding_x = {FBindingEtaX}\n')
{kappa_b: 2.39*X, kappa_c: 1.61, kappa_d: 0.926*X}
\(\displaystyle \frac{7.403167205000002 \, X^{2} \eta_{\mathit{bb}} \eta_{\mathit{bc}}^{2} \eta_{\mathit{cc}} + 4.5982405 \, X^{2} \eta_{\mathit{bb}} \eta_{\mathit{bc}} + 2.85605 \, X^{2} \eta_{\mathit{bb}}}{12.696076404549165 \, X^{4} \eta_{\mathit{bb}} \eta_{\mathit{bc}}^{2} \eta_{\mathit{bd}}^{2} \eta_{\mathit{cc}} \eta_{\mathit{cd}}^{2} \eta_{\mathit{dd}} + 27.421331327320008 \, X^{3} \eta_{\mathit{bb}} \eta_{\mathit{bc}}^{2} \eta_{\mathit{bd}} \eta_{\mathit{cc}} \eta_{\mathit{cd}} + 17.031882812000003 \, X^{3} \eta_{\mathit{bb}} \eta_{\mathit{bc}} \eta_{\mathit{bd}} + 14.806334410000003 \, X^{2} \eta_{\mathit{bb}} \eta_{\mathit{bc}}^{2} \eta_{\mathit{cc}} + 18.392962 \, X^{2} \eta_{\mathit{bb}} \eta_{\mathit{bc}} + 5.7121 \, X^{2} \eta_{\mathit{bb}} + 7.1263108000000015 \, X^{2} + 12.475800000000001 \, X + 1.0}\)
binding_x = (7.403167205000002*X^2*eta_bb*eta_bc^2*eta_cc + 4.5982405*X^2*eta_bb*eta_bc + 2.85605*X^2*eta_bb)/(12.696076404549165*X^4*eta_bb*eta_bc^2*eta_bd^2*eta_cc*eta_cd^2*eta_dd + 27.421331327320008*X^3*eta_bb*eta_bc^2*eta_bd*eta_cc*eta_cd + 17.031882812000003*X^3*eta_bb*eta_bc*eta_bd + 14.806334410000003*X^2*eta_bb*eta_bc^2*eta_cc + 18.392962*X^2*eta_bb*eta_bc + 5.7121*X^2*eta_bb + 7.1263108000000015*X^2 + 12.475800000000001*X + 1.0)
FastCallableFBindingEtaX = fast_callable(FBindingEtaX, vars=['X']+eta_list)
from scipy.optimize import minimize
import random
from matplotlib import pyplot as plt

# construct target function
# xrange and values x for data, x0 for smooth plots
xlogmin=-3
xlogmax=3
x = np.logspace(xlogmin,xlogmax,20)
x0 = np.logspace(xlogmin,xlogmax,1000)


# choose random eta's with 50% chance of being 1 (1 means that this eta is unused)
eta_prob_one = 0.5
eta = np.random.exponential(scale=1.0,size=n_eta)
for i in range(n_eta):
    if np.random.random() <= eta_prob_one:
        eta[i]=1.0
y = FastCallableFBindingEtaX(x,*eta) + np.random.normal(size=x.size, scale=0.005) # w/ noise
y0 = FastCallableFBindingEtaX(x0,*eta) # y, y0 are large arrays 
# create hypercube and flip left/right
Q = graphs.CubeGraph(n_eta, embedding=2)
pos = Q.get_pos()
for v in Q.vertices(sort=False):
    xpos,ypos = pos[v] # do not use x,y here! These are needed below
    pos[v]=(n_eta-xpos,ypos)
    # pos[v]=(ypos,xpos) this didn't look good 
Q.show(figsize=6,edge_labels=False,vertex_labels=True, vertex_size=100,edge_thickness=0.5,vertex_colors='white')
_images/dc01717e79cacc98280c9b6042830e762ffae206ea194732741614f90aef9705.png
root = "1" * n_eta
d_level = dict()
for level in range(n_eta+1):
    for v in Q.vertices(sort=True):
        if level == Q.distance(v,root):
            d_level[v]=level
print(d_level)
{'111111': 0, '011111': 1, '101111': 1, '110111': 1, '111011': 1, '111101': 1, '111110': 1, '001111': 2, '010111': 2, '011011': 2, '011101': 2, '011110': 2, '100111': 2, '101011': 2, '101101': 2, '101110': 2, '110011': 2, '110101': 2, '110110': 2, '111001': 2, '111010': 2, '111100': 2, '000111': 3, '001011': 3, '001101': 3, '001110': 3, '010011': 3, '010101': 3, '010110': 3, '011001': 3, '011010': 3, '011100': 3, '100011': 3, '100101': 3, '100110': 3, '101001': 3, '101010': 3, '101100': 3, '110001': 3, '110010': 3, '110100': 3, '111000': 3, '000011': 4, '000101': 4, '000110': 4, '001001': 4, '001010': 4, '001100': 4, '010001': 4, '010010': 4, '010100': 4, '011000': 4, '100001': 4, '100010': 4, '100100': 4, '101000': 4, '110000': 4, '000001': 5, '000010': 5, '000100': 5, '001000': 5, '010000': 5, '100000': 5, '000000': 6}
def do_eta_fit(eta_list):

    # Define the objective function
    def objective_function(params):
        eta = params
        residuals = y - FastCallableFBindingEtaX(x,*eta)
        return np.sum(residuals ** 2)

    # Initial guess for parameters
    initial_guess = np.ones(n_eta)
    # this loop makes elements of the tuple bnds
    bnds = ()
    k = 0 # nparams
    for i in range(n_eta):
        if eta_list[i]==1.0:
            bnds += ((1, 1),) # eta = 1, not used
        else:
            bnds += ((0, None),) # eta non-negative
            k += 1

    # Perform optimization
    result = minimize(objective_function, initial_guess, bounds=bnds)

    # Extract and print optimized eta's
    optimal_eta = result.x
    np.set_printoptions(precision=2)
    print( optimal_eta )
    #print(f'{optimal_eta=}')

    # Evaluate result
    y0_result = FastCallableFBindingEtaX(x0,*optimal_eta)

    res = y - FastCallableFBindingEtaX(x,*optimal_eta)
    ssr = np.sum(res ** 2)
    n = len(y)
    aic = 2*(k+2)+n*np.log(ssr/(n-k))

    # Plot result
    plot_results = True
    if plot_results:
        plt.semilogx(x0,y0,linewidth=4,color='yellow',label='exact')
        plt.semilogx(x,y,'+',color='black',label='sim data')
        plt.semilogx(x0,y0_result,color='red',linestyle='dashed',label='fit')
        np.set_printoptions(precision=2)
        plt.title(f'aic={aic=},\ntarget eta={eta},\noptimal eta={optimal_eta}')
        plt.xlabel('x')
        plt.ylabel('phi',rotation = 0)
        plt.legend()
        plt.grid()
        plt.show()

    return aic
# make arcs point rightward to "lower" levels only (fewer parameters used, more 1's)
Q_directed = Q.to_directed()
for e in Q_directed.edges(sort=False):
    if d_level[e[0]]<d_level[e[1]]:
        Q_directed.delete_edge(e)
Q_directed.show(figsize=14,graph_border=True)
_images/8262238bfa412db5addbcc1b4efd4b00e89ad88de8701f29f9e1302d1c83c3b9.png
max_depth = 4
d_aic = dict();
Q_aic = copy(Q_directed)
for level in range(max_depth+1,n_eta+1): # delete levels not used
    #print(f'{max_depth=} so deleting {level=}')
    for vert, lev in d_level.items():
        if lev == level:
            Q_aic.delete_vertex(vert)
for level in range(0,max_depth+1):
    for vert, lev in d_level.items():
        if lev == level:
            if Q_aic.has_vertex(vert):
                #print(type(vert))
                aic = do_eta_fit([int(char) for char in vert])
                d_aic[vert]=str(f'{aic:.3f}')
                Q_aic.set_vertex(vert,aic)
                #print(f"level {lev} : eta_mask={vert} {aic=:.2f}")
                hang = 0
                for nv in Q_aic.neighbors_out(vert):
                    #print(f'looking at vert {vert} --> {nv}')
                    if float(d_aic[vert])>=float(d_aic[nv]): # float from str
                        #print(f'deleted edge {vert=} {d_aic[vert]=} -> {nv=} {d_aic[nv]=}')
                        Q_aic.delete_edge(vert,nv)
                    else:
                        hang+=1
                if hang==0 and vert != root:
                    Q_aic.delete_vertex(vert)
[1. 1. 1. 1. 1. 1.]
_images/d0cd74991d2e5f2f68d90b07ceeb63516abdb696e719258b4bf28c6f10071c62.png
[2.02 1.   1.   1.   1.   1.  ]
_images/29592bd442f7d72d5f679a99cff539b8db7b233fc90eac1f7930b8abf6bcc44e.png
[1.   1.12 1.   1.   1.   1.  ]
_images/b9bd6d5c0ce041b0bf22b0076422ab9206d913e6b32b63af63de953c933072f9.png
[1. 1. 0. 1. 1. 1.]
_images/75efdae154c8fa3efb11fcd439a12c2f56eda9a9f7d59e6327bf08c3cbc8cc28.png
[1.   1.   1.   0.02 1.   1.  ]
_images/3a01b5e5cf52c2a111c0304d90801cd5448c882f57082be0cc4a397aa579a59e.png
[1.00e+00 1.00e+00 1.00e+00 1.00e+00 1.11e-16 1.00e+00]
_images/97862aee103862991cacd6099982d33ad2ed3e69a7ea42fa818fa5d7ccf26485.png
[1. 1. 1. 1. 1. 0.]
_images/81e0306ef4a3d1689d9dee1b9f6536fa72f8ebcc2c0bd9acb6007de2b02ecbc0.png
[4.23 0.01 1.   1.   1.   1.  ]
_images/5ca87820ebd4e430ca31b758811e5e9beea86a2443129cb6017166477ea8d5e4.png
[4.74 1.   0.   1.   1.   1.  ]
_images/d4ed536bffd447b6d02b57a78dcd157a31d03fd8e8601ccf39cd28235ec16201.png
[1.26 1.   1.   0.02 1.   1.  ]
_images/0688e77aa40feec1a7d0e4ede6ce8b91b69e53fb2c7616bad89f39550a4b2924.png
[1.89 1.   1.   1.   0.   1.  ]
_images/55a9b67ad4ab91f56c235f7b1959ba347747c0b097acfbae7dc5171494e1086a.png
[2.08 1.   1.   1.   1.   0.  ]
_images/a115e53f131584074b1f934ba7dfc02e95b9b936f0b88739e33d5e7ca234d4ec.png
[1.00e+00 2.49e-04 1.40e+03 1.00e+00 1.00e+00 1.00e+00]
_images/74c068a79258782fa5061cbbbc065c0581394f552ff22eb0fd7106094a487b9e.png
[1.   1.16 1.   0.02 1.   1.  ]
_images/99f14c7de3b7bedbe541f68f3a4285ce5d076360b1e64556f929e5188402b8af.png
[1.   2.08 1.   1.   0.   1.  ]
_images/d2bc0ff54592d04216b4ecc4b9ecd2863f9ed248bcaaba0ae94500154829c4e7.png
[1.   1.37 1.   1.   1.   0.  ]
_images/cd4a2fcff3d84f538af99f0b4ca6699a1ce9daf18537d5303f9f40a7e7f96651.png
[1.   1.   1.3  0.02 1.   1.  ]
_images/502f586a0f143ed293fbcab663a060877ad24db5e7e6dc097c3033eedad0f465.png
[1.   1.   4.85 1.   0.   1.  ]
_images/90bfb06bf3952360e9c700649455d2dda446fd8209a09ea6f70e55f2796d3276.png
[1.   1.   2.29 1.   1.   0.  ]
_images/dcca036ac7e5e67f45461900005f6b6d1809b2a8e5beffdd25927a6130596b9f.png
[1.   1.   1.   0.02 0.55 1.  ]
_images/4faa9a34741b2c5d04f279a9c349d4ebfdd7afd4f3f11a5715ab432628cb6cf0.png
[1.   1.   1.   0.02 1.   0.75]
_images/1a0fde8be0f6b6b29cb664c8b264376aa7c72488789034f0b311af8f8bf0a0ba.png
[1.   1.   1.   1.   0.   0.69]
_images/cc49ea6714072da178fc4445a4f389db1128186b56af620ea128020286580032.png
[4.56 0.01 0.   1.   1.   1.  ]
_images/067781c0c6ea9bacfc77c636ceea259bd31219e10b3bb411a0f1fdbb2e9eb971.png
[2.26 0.62 1.   0.02 1.   1.  ]
_images/acb656e93751419536055fc1225a3fd2d7eabd2200058b69de36de1d263d88db.png
[2.40e-03 2.71e+01 1.00e+00 1.00e+00 0.00e+00 1.00e+00]
_images/0b0ed5ab0cd96a33a17224debc9a9784f5c9a294aa8f79b87a905d80dfdde6f4.png
[4.56 0.01 1.   1.   1.   0.  ]
_images/6655e8c04d7b7f89ce8fe7fbbfbcf51a815d27e4421fd4b56ef79e6564e6bbad.png
[1.75 1.   0.6  0.02 1.   1.  ]
_images/89f08c56cbb73a0362f37a757ea4251841260ca55dfb54da0cd462720497008a.png
[ 0.06  1.   26.72  1.    0.    1.  ]
_images/22d4960a679a1772c59283ff2edee4c0beb9eb3e7e9c1761c84ba29de505beea.png
[4.74 1.   0.   1.   1.   0.  ]
_images/e64cc88d67dfbef983b16815117d9a606b8814a815f9cbb051d3fe6caa3531fa.png
[1.29 1.   1.   0.04 0.28 1.  ]
_images/01163888fac2fbe12920132b1fdfda66789881c5550694ecf348219f814b420f.png
[1.29 1.   1.   0.02 1.   0.26]
_images/438aeeef851ca0959531b0c7ca9ef5c276fca4a1f9aedb5b16ac11dff0cb25aa.png
[1.89 1.   1.   1.   0.   0.69]
_images/c576cc950486cf2bbf8cba4670c2a418c81744d58bbb7cc36a53d9b079e1a2e7.png
[1.   1.74 0.45 0.01 1.   1.  ]
_images/762a043f839ceba99205d4ea0b5f78987de30c3de7a69e12df5d7c2f73589cfa.png
[1.00e+00 6.50e-02 3.26e+02 1.00e+00 0.00e+00 1.00e+00]
_images/eb27bc6a14fa097b2e4d11df4cf081138a6064cab1d578110ed4aee042738ace.png
[1.00e+00 1.23e-02 1.32e+04 1.00e+00 1.00e+00 0.00e+00]
_images/77bac1e3db97342357748c3d49ff2687600254fc4d2ac981c985fcef03bb17b5.png
[1.   1.18 1.   0.04 0.24 1.  ]
_images/3f40f49609e9f44e31a66c0151ffc789d61d66b56b82220135b0c3392e1ebf07.png
[1.   1.18 1.   0.02 1.   0.22]
_images/d3a9ad3fc21a95f5c0e5f95d08e2036ac4f722f96e7bae5a5ec282d0371d8e64.png
[1.   2.08 1.   1.   0.   0.69]
_images/b73bc66d5bf11a44489d9b364cd5cdf27daef0b3784bb311fc9f41db017510a2.png
[1.   1.   1.39 0.05 0.17 1.  ]
_images/ec2c3ae5880c456a4cca51b8f17ea4cbfc614a40d6974f406aab1c8da19218d1.png
[1.   1.   1.39 0.02 1.   0.17]
_images/8144f83c1c31f2b1573776167cde644f54f7e3dfed68ec553cf22938dc76ce90.png
[1.   1.   4.85 1.   0.   0.69]
_images/d985411e50c09faab90083ffb3c577475375268127b0f18535c4101fca0f5b6c.png
[1.   1.   1.   0.02 0.66 0.83]
_images/112978286c18ac91d5741abd71e8ec984586441b3b38f583de86e71ead74cedb.png
[1.51 1.15 0.57 0.02 1.   1.  ]
_images/be81900cc954c3966186522ef111864c4fb4c2a9d7e86332cbb50c2b07af9dfb.png
[ 0.04  1.52 17.62  1.    0.    1.  ]
_images/502d8d98291b63cbecb97937ff96094aa2cb052e09437142f503ebaaef4b0907.png
[4.56 0.01 0.3  1.   1.   0.  ]
_images/81a064bfba94d8920dab6c0a0c4a133862268339efff540138351b01ef92fa2b.png
[2.3  0.62 1.   0.03 0.4  1.  ]
_images/ccf0124eb68f20ed69a2cd925e0076fbd1ceb8988b1f3b3dc3b49bad0a0fe1d4.png
[2.31 0.62 1.   0.02 1.   0.32]
_images/3815e25cd168a3c70b417567344bbbbbc89d564a3572da39430a0ab0d9f91753.png
[2.40e-03 2.71e+01 1.00e+00 1.00e+00 0.00e+00 6.86e-01]
_images/72ecb388cb4fbf8a83059be81757db588f5a024990e6092f381d27e55fdcd129.png
[1.54 1.   0.77 0.03 0.43 1.  ]
_images/d0e045a2ed556caa554fd5a30a09723bb27c9f4b86d390cbb325a1e6a00d8885.png
[1.54 1.   0.77 0.02 1.   0.39]
_images/efe3db2b84f3ea41af67dc084c278d47855feb479a62ae7f0d5519d84099148f.png
[ 0.06  1.   26.72  1.    0.    0.69]
_images/f70a01afb873e35589e8c56822140b00eb4a744c5c35b838452680be583404aa.png
[1.29 1.   1.   0.03 0.34 0.78]
_images/102a51f65f482a839f792499c15592909b636ff6e1cb71cdb17aca12f367bd16.png
[1.   1.54 0.59 0.03 0.42 1.  ]
_images/0f013112442ab4ec3cb4d85682ab8e0a0d2847ca423e03a1c96b31ee741605b1.png
[1.   1.45 0.66 0.02 1.   0.32]
_images/c2b104c4ccd7ab53d483fb5a1437b9569f3b250692ad6eb73a2228c4baefc3a5.png
[1.00e+00 6.50e-02 3.26e+02 1.00e+00 0.00e+00 6.85e-01]
_images/0765acf126d6d36b5f62ba63d470ba13a37cc2c4d504c8e4ef99edecff3ebc40.png
[1.   1.18 1.   0.04 0.28 0.78]
_images/30d4a0c427cf9693815b662a9ac0158b14c5e57a87f63274c95d7a98b4a600b8.png
[1.   1.   1.39 0.04 0.21 0.77]
_images/663db7a672c44435af7160cdf4e55198c1d41c147064bd3d5f3eba59cbb00f38.png
print(d_aic)
{'111111': '-78.608', '011111': '-76.126', '101111': '-75.589', '110111': '-78.343', '111011': '-171.310', '111101': '-87.627', '111110': '-79.216', '001111': '-149.271', '010111': '-78.260', '011011': '-190.806', '011101': '-85.763', '011110': '-76.905', '100111': '-94.583', '101011': '-187.974', '101101': '-89.420', '101110': '-76.269', '110011': '-182.511', '110101': '-98.654', '110110': '-76.431', '111001': '-168.702', '111010': '-168.605', '111100': '-84.545', '000111': '-157.253', '001011': '-191.479', '001101': '-157.253', '001110': '-157.203', '010011': '-196.606', '010101': '-157.253', '010110': '-75.117', '011001': '-198.341', '011010': '-198.341', '011100': '-82.620', '100011': '-196.704', '100101': '-157.253', '100110': '-73.764', '101001': '-196.027', '101010': '-196.027', '101100': '-86.277', '110001': '-190.732', '110010': '-190.732', '110100': '-95.511', '111000': '-165.559', '000011': '-193.399', '000101': '-154.040', '000110': '-154.025', '001001': '-197.085', '001010': '-197.085', '001100': '-154.040', '010001': '-197.528', '010010': '-197.528', '010100': '-154.040', '011000': '-195.129', '100001': '-197.528', '100010': '-197.164', '100100': '-154.040', '101000': '-192.815', '110000': '-187.520'}
Q_aic_undirected = Q_aic.to_undirected()
Q_aic_undirected.show(figsize=6,edge_labels=False,vertex_labels=d_aic, vertex_size=0,edge_thickness=0.3,vertex_colors='white',title='AIC pruned')
Q_aic_undirected.show(figsize=6,edge_labels=False, vertex_size=0,edge_thickness=0.3,vertex_colors='white',title='eta\'s not used')
_images/37cffa63d7acabf98da6984f54542aeed134cc6c69450558912bf2a47694b331.png _images/b72424e7bee5af2b918dc88c62fbddf8ebca7fdb53ed088c8861a757492205c0.png