Menu

Global variables, functions, libraries not accessible inside function in python.NET

2023-05-23
2023-06-09
  • Pravin Dalve

    Pravin Dalve - 2023-05-23

    I was testing following code in python script user model

    import numpy as np
    from scipy.optimize import curve_fit
    
    # Define the function to fit
    def func(x, a, b, c):
        #import numpy as np
        return a * np.exp(-b * x) + c
    
    # Generate sample data
    x_data = np.linspace(0, 4, 50)
    y_data = func(x_data, 2.5, 1.3, 0.5) + 0.2 * np.random.normal(size=len(x_data))
    
    # Fit the data
    initial_guess = [1, 1, 1]  # Initial parameter guess
    params, _ = curve_fit(func, x_data, y_data, initial_guess)
    
    # Print the estimated parameters
    Flowsheet.WriteMessage(str(params[0]))
    Flowsheet.WriteMessage(str(params[1]))
    Flowsheet.WriteMessage(str(params[2]))
    

    In function definition func is not able to access numpy library which is imported at top. If I am explicitly importing library inside the function the code works. I have faced similar issue when I was trying to use a function inside another function.

    Overall it seems that in python.Net we are not able to access global functions, variables and libraries inside functions. Any thoughts on this???

     
    • Daniel Medeiros

      Daniel Medeiros - 2023-06-09

      try this:

      def func(x, a, b, c):
          global np
          return a * np.exp(-b * x) + c
      
       
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.