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')
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)
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.]
[2.02 1. 1. 1. 1. 1. ]
[1. 1.12 1. 1. 1. 1. ]
[1. 1. 0. 1. 1. 1.]
[1. 1. 1. 0.02 1. 1. ]
[1.00e+00 1.00e+00 1.00e+00 1.00e+00 1.11e-16 1.00e+00]
[1. 1. 1. 1. 1. 0.]
[4.23 0.01 1. 1. 1. 1. ]
[4.74 1. 0. 1. 1. 1. ]
[1.26 1. 1. 0.02 1. 1. ]
[1.89 1. 1. 1. 0. 1. ]
[2.08 1. 1. 1. 1. 0. ]
[1.00e+00 2.49e-04 1.40e+03 1.00e+00 1.00e+00 1.00e+00]
[1. 1.16 1. 0.02 1. 1. ]
[1. 2.08 1. 1. 0. 1. ]
[1. 1.37 1. 1. 1. 0. ]
[1. 1. 1.3 0.02 1. 1. ]
[1. 1. 4.85 1. 0. 1. ]
[1. 1. 2.29 1. 1. 0. ]
[1. 1. 1. 0.02 0.55 1. ]
[1. 1. 1. 0.02 1. 0.75]
[1. 1. 1. 1. 0. 0.69]
[4.56 0.01 0. 1. 1. 1. ]
[2.26 0.62 1. 0.02 1. 1. ]
[2.40e-03 2.71e+01 1.00e+00 1.00e+00 0.00e+00 1.00e+00]
[4.56 0.01 1. 1. 1. 0. ]
[1.75 1. 0.6 0.02 1. 1. ]
[ 0.06 1. 26.72 1. 0. 1. ]
[4.74 1. 0. 1. 1. 0. ]
[1.29 1. 1. 0.04 0.28 1. ]
[1.29 1. 1. 0.02 1. 0.26]
[1.89 1. 1. 1. 0. 0.69]
[1. 1.74 0.45 0.01 1. 1. ]
[1.00e+00 6.50e-02 3.26e+02 1.00e+00 0.00e+00 1.00e+00]
[1.00e+00 1.23e-02 1.32e+04 1.00e+00 1.00e+00 0.00e+00]
[1. 1.18 1. 0.04 0.24 1. ]
[1. 1.18 1. 0.02 1. 0.22]
[1. 2.08 1. 1. 0. 0.69]
[1. 1. 1.39 0.05 0.17 1. ]
[1. 1. 1.39 0.02 1. 0.17]
[1. 1. 4.85 1. 0. 0.69]
[1. 1. 1. 0.02 0.66 0.83]
[1.51 1.15 0.57 0.02 1. 1. ]
[ 0.04 1.52 17.62 1. 0. 1. ]
[4.56 0.01 0.3 1. 1. 0. ]
[2.3 0.62 1. 0.03 0.4 1. ]
[2.31 0.62 1. 0.02 1. 0.32]
[2.40e-03 2.71e+01 1.00e+00 1.00e+00 0.00e+00 6.86e-01]
[1.54 1. 0.77 0.03 0.43 1. ]
[1.54 1. 0.77 0.02 1. 0.39]
[ 0.06 1. 26.72 1. 0. 0.69]
[1.29 1. 1. 0.03 0.34 0.78]
[1. 1.54 0.59 0.03 0.42 1. ]
[1. 1.45 0.66 0.02 1. 0.32]
[1.00e+00 6.50e-02 3.26e+02 1.00e+00 0.00e+00 6.85e-01]
[1. 1.18 1. 0.04 0.28 0.78]
[1. 1. 1.39 0.04 0.21 0.77]
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')