Can the function variables be dynamically updated with each call?

I am currently tackling an Ordinary Differential Equation (ODE) system using the solve_ivp function and I aim to modify the local variables within the function each time it is called by the solver. Specifically, I wish to update the Lagrange multipliers (lambdas_i) so that the subsequent step in solve_ivp utilizes the values from the previous one. (The ''reconstruct'' function comes from a Python module that employs a method for reconstructing a size distribution based on given moments). Is there a way to achieve this? Below is the code snippet:

import time 
import numpy as np
import scipy.integrate as integrate
from numpy import sqrt, sin, cos, pi
import math 
import pylab as pp
from pymaxent import reconstruct

start = time.time()

'''Initializing variables'''

t=np.linspace(0, 60,31)
tspan=(0,60)

initial_m=[]
for i in range(4):
    def distr(L,i=i):
        return (L**i)*0.0399*np.exp(-((L-50)**2)/200)
   
    m, err=integrate.quad(distr, 0, np.inf)
    print('m(',i,')=',m)
    initial_m.append(m)

'''Solving the ODE system using Maximum Entropy with G(L)=1+0.002*L'''

def moments(t,y):
    m0 = y[0]
    m1 = y[1]
    m2 = y[2]
    m3 = y[3]
    Lmean=m1
    σ=(m2-Lmean**2)**(1/2)
    Lmin=Lmean-3*σ
    Lmax=Lmean+4*σ
    bnds=[Lmin,Lmax]
    L=np.linspace(Lmin,Lmax)
    
    sol, lambdas_i= reconstruct(mu=y ,bnds=bnds)
    print(lambdas_i)
    
    dm0dt=0
        
    def moment1(L):
        return(sol(L)+0.002*sol(L)*L)                
    dm1dt, err1=integrate.quad(moment1,Lmin,Lmax)
    
    def moment2(L):
        return(2*L*(sol(L)+0.002*sol(L)*L))
    
    dm2dt, err2=integrate.quad(moment2,Lmin,Lmax)
    
    def moment3(L):
        return(3*L**2*(sol(L)+0.002*sol(L)*L))
    
    dm3dt, err3=integrate.quad(moment3,Lmin,Lmax)
    
    return(dm0dt,dm1dt,dm2dt,dm3dt)

'''Using the Backward Differentiation Formula (BDF) algorithm step by step'''

r=integrate.solve_ivp(moments,tspan,initial_m,method='BDF',jac=None,t_eval=t,rtol=10**(-3))

end = time.time()

print('Total time taken:', {end-start})

Answer №1

If you're looking for a solution, here is one approach you could take. I'll provide a simplified example problem to demonstrate the strategy that can be applied to your specific case.

def sequence():
  list = [1, 0]
  while True:
    previous = list[1]
    current = list[0] + previous
    list = [previous, current]
    print(current)
    input()

The function above showcases how you can generate the next term of the fibonacci sequence, where each term is the sum of the two preceding terms. The input command serves to create breaks between iterations, given the infinite nature of this sequence. To enhance flexibility and utility, consider transforming the function into a generator like so:

def sequence():
  list = [1, 0]
  while True:
    previous = list[1]
    current = list[0] + previous
    list = [previous, current]
    yield current

To achieve similar results, you can iterate over the generator as follows:

for item in sequence():
  print(item)
  input()

This method may seem redundant at first glance. However, utilizing a generator becomes advantageous when you require access to the next number of the sequence at any point within your code, rather than being confined to a loop structure. For instance:

gen = sequence()
next(gen) # returns 1
next(gen) # returns 1
next(gen) # returns 2
next(gen) # returns 3
next(gen) # returns 5

Following this pattern...


An alternative approach involves using a global variable instead of a local variable:

list = [1, 0]

def sequence():
  previous = list[1]
  current = list[0] + previous
  list[0] = previous
  list[1] = current
  return current

By defining the variable list outside the function scope, it maintains its state beyond individual function calls. Thus, running the updated code remains consistent with the previous implementation:

while True:
  print(sequence())
  input()

Both methods discussed can be integrated into your own code base effectively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing partial duplicates in pandas

Two dataframes are available: Dataframe 1 (df1): x y z 0 1 2 r 1 a c 2 2 22 g d Dataframe 2 (df2): x y z 0 1 2 r 1 a b 2 2 3 g d The goal is to remove rows where columns y and z have duplicate values. Desired output ...

Configuring Proxies in Scrapy

I'm having trouble configuring the proxy in my Scrapy project. Every time I try to run it, I encounter the following error: Error 2019-05-09 19:36:50 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023 2019-05-09 19:36:50 [sc ...

Eliminate duplicate elements in various lists (compress multiple lists) based on their values

If I have a collection of lists: [[0,0,0,1,2,3],[0,0,0,4,5,6],[0,0,0,0,7,8],[0,0,0,0,0,9]] I am looking to create a new list where common null, zero, or specific values are removed from each inner list to achieve the desired output: [[1,2,3],[4,5,6],[0, ...

Converting Nested JSON into a Pandas Data Frame

How can we efficiently convert the following JSON dataset snapshot into a Pandas Data Frame? Importing the file directly results in a format that is not easily manageable. Presently, I am utilizing json_normalize to separate location and sensor into diff ...

What can you find in the PyString variable while debugging in Qt Creator?

I have a PyString* object and I'm interested in viewing its contents. Is it possible to access the text of the PyString using the debugger in Qt Creator? PyObject *import_str = PyString_InternFromString("__import__"); Just for clarification, Qt Crea ...

Breaking down a pandas data frame based on dates

I am looking to generate a pandas datasheet that takes the dictionary a provided below and extends the dates by days_split, resulting in two tables. For instance, adding 10 days to the initial date value of 2/4/2022 1:33:40 PM would create a range for Tabl ...

Is there a way to halt the rendering of variables in Django?

Is there a way to prevent Django from rendering specific template variables? The scenario is that I wanted to experiment with implementing Vue.js in a Django application, which was somewhat successful. The issue arises because both Vue.js and Django use ...

Acquiring the Rock Paper Scissors game

Having an issue trying to extract the image of rock, paper, scissors and ensure the output matches the picture. I attempted to obtain a matrix representation, such as [1,0,0] for paper, [0,1,0] for rock, and [0,0,1] for scissors. However, upon reaching the ...

Encountered an issue while parsing JSON data: Error message indicates that string indices must be integers

Would appreciate some assistance with parsing the Json. The image displaying the json structure is attached below for reference. The error message I keep encountering is: print("title: "+json_data["title"]) TypeError: string indices must be integers Her ...

Using Django with Google App Engine's Adsense Integration

Facing an issue with Django on Google App Engine. Successfully designed HTML templates for my web application and imported them into Django using its template system. However, encountering a problem with Google AdSense. The AdSense banner shows up on the ...

Error! The function worker.recognize(...).progress is throwing an error. Any ideas on how to resolve this

Here is the code snippet: //Imports const express = require('express'); const app = express(); const fs = require("fs"); const multer = require('multer'); const { createWorker } = require("tesseract.js"); co ...

TCP allows files to be transferred without needing to close the socket

I developed a basic TCP server - client file sharing system, but I've encountered an issue where it only works when the socket is closed in the client script. I attempted to eliminate the 's.close' command from the client python script, whi ...

Python ModuleNotFound error when invoking Python code from system() function in R

I have a scenario where I have an R script running on my Raspberry Pi that calls a Python script using the system() function. Let's call this R script tweetsomething.R # first some data cleaning etc. system("python3 tweetImage.py var1 var2" ...

What could be causing the NameError error to occur when I've already included self in my code

Although I'm well-versed in C++, this time around I need to work with Python. I grasp most of what's going on, but this error has got me stumped. I know it has to do with the "self" in the functions, yet even after using it, the error still pers ...

Methods for calculating vast amounts of data

Imagine I am faced with the task of counting collisions for different hash schemes. The input sequence consists of 1e10^8 elements or even more. Since I am unable to calculate this analytically, I resort to using brute force. It is clear that storing this ...

Retrieving the most recent data in a Dask dataframe with duplicate dates in the index column

Although I'm quite familiar with pandas dataframes, Dask is new to me and I'm still trying to grasp the concept of parallelizing my code effectively. I've managed to achieve my desired outcomes using pandas and pandarallel, but now I'm ...

What are some ways to optimize the efficiency of this function to save time?

I have a DataFrame series that contains sentences, some of which are quite lengthy. Additionally, I possess two dictionaries with words as keys and integers as counts. It's worth noting that not all words from the strings appear in both dictionaries ...

Error encountered: PYODBC InterfaceError - Cannot locate specified data source name

I am attempting to establish a connection between Python and an MS Access Database using pyodbc. However, every time I try, I encounter the following error message: pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] ...

Using Python to locate an element based on a specific type value in the preceding element's xpath

I've been struggling to figure out a way to select an element if there is a preceding element that contains a specific name. For example, consider the following HTML: <div> <input type="text" name="name"> </div> <div> ...

Utilizing Selenium to add a JavaScript event listener will automatically activate it

After conducting thorough research, I've discovered that there is no direct way to capture user input using Selenium. In an attempt to work around this limitation, I have implemented a JavaScript event listener. Unfortunately, upon executing the code ...