Minimize receptor model pade

Minimize receptor model pade#

import numpy as np
from scipy.optimize import minimize

import random
from matplotlib import pyplot as plt
np.set_printoptions(precision=2)

# construct target rational function
n=5 # order
xlogmin=-3
xlogmax=3
phi = np.random.uniform(low=0,high=1,size=n+1)
sum_phi = sum(phi); phi = np.array([float(p)/sum_phi for p in phi])
q = np.random.uniform(low=0,high=10,size=n+1); q[0]=1

# q_list is length n+1 (same as phi_list)
def pade(phi_list,q_list,x_list):
    num = np.zeros(x_list.size)
    den = np.zeros(x_list.size)
    for i, (phi, q) in enumerate(zip(phi_list,q_list)):
        num = np.add(num,[phi*q*x**i for x in x_list])
        den = np.add(den,[q*x**i for x in x_list])
    return np.divide(num,den)

x = np.logspace(xlogmin,xlogmax,20)
y = pade(phi,q,x) + np.random.normal(size=x.size, scale=0.005) # w/ noise

x0 = np.logspace(xlogmin,xlogmax,1000)
y0 = pade(phi,q,x0)

# Define the objective function
def objective_function(params):
    q = params
    q_with_one = np.append(1, q)
    #print(type(y))
    residuals = y - pade(phi,q_with_one,x)
    return np.sum(residuals ** 2)

# Initial guess for parameters
initial_guess = np.ones(n) # n is order, which is the number of q's

# q's must be positive
# this loop makes bnds = ((0, None), (0, None), ... ) n times
bnds = ((0, None),)
for _ in range(n-1):
    bnds += ((0, None),)

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

# Extract and print optimized q's
optimal_q = np.append(1, result.x)
for i, qq in enumerate(optimal_q):
    print(f'Optimal q{i}: {qq}')

# Evaluate result 
y0_result = pade(phi,optimal_q,x0)

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')
plt.title(f'phi={phi}, q={q}, optimal q={optimal_q}')
plt.xlabel('x')
plt.ylabel('phi',rotation = 0)
plt.legend()
plt.grid()
plt.show()
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_11904/638181480.py", line 5, in <module>
    from matplotlib import pyplot as plt
  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_11904/638181480.py in <module>
      3 
      4 import random
----> 5 from matplotlib import pyplot as plt
      6 np.set_printoptions(precision=Integer(2))
      7 

/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