How to plot a function in Python when both variables cannot be isolated to one side - function

I am trying to graph variable "u" versus variable "T" for 1<T<1000 (integers). However, the function I have includes both of the variables within an integral so I cannot create an isolated u=f(T) function. My thought process is to manipulate the function so that it is 0=f(T,u) and output a "u" value that minimizes f(T,u) for each T. However, I seem to be struggling a lot with how these variables and functions should be defined. All constants are defined and "E" should be defined through the integration step. The overall function I start with is:
5x10^28=integrate((pi/2)(8m/h^2)(E^0.5)(exp((E-u)/k*T)+1)^-1) from 0 to infinity and with respect to "E"
I am very new to python but the following code is how far I've been able to develop it based on previous forums and video tutorials. Any help is much appreciated!
from scipy.integrate import quad
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as spo
m=9.11e-31
h=6.63e-34
k=1.38e-23
T=list(range(1,1001))
def f(E,u):
return (np.pi/2)*(8*m/(h**2))*(E**0.5)*(1/((np.exp((E-u)/k*T)+1)))
Func_Equal_Zero=quad(f,0,np.inf,args=(u,))[0]-5e-28
Start_Guess_T_u=[500,1e-5]
result=spo.minimize(Func_Equal_Zero,Start_Guess_T_u)
plt.plot(T,u)
plt.figure(figsize=(6,6))
plt.xlabel('Temperature (k)')
plt.ylabel('Chemical Potential (J)')
I expected that I could just define the functions including "u" but python does not seem to like what I have tried. I am not sure if any of my other syntax is not correct because I cannot get past its issue with defining "u".

Related

Add a TensorBoard metric from my PettingZoo environment

I'm using Tensorboard to see the progress of the PettingZoo environment that my agents are playing. I can see the reward go up with time, which is good, but I'd like to add other metrics that are specific to my environment. i.e. I'd like TensorBoard to show me more charts with my metrics and how they improve over time.
The only way I could figure out how to do that was by inserting a few lines into the learn method of OnPolicyAlgorithm that's part of SB3. This works and I got the charts I wanted:
(The two bottom charts are the ones I added.)
But obviously editing library code isn't a good practice. I should make the modifications in my own code, not in the libraries. Is there currently a more elegant way to add a metric from my PettingZoo environment into TensorBoard?
You can add a callback to add your own logs. See the below example. In this case the call back is called every step. There are other callbacks that you case use depending on your use case.
import numpy as np
from stable_baselines3 import SAC
from stable_baselines3.common.callbacks import BaseCallback
model = SAC("MlpPolicy", "Pendulum-v1", tensorboard_log="/tmp/sac/", verbose=1)
class TensorboardCallback(BaseCallback):
"""
Custom callback for plotting additional values in tensorboard.
"""
def __init__(self, verbose=0):
super(TensorboardCallback, self).__init__(verbose)
def _on_step(self) -> bool:
# Log scalar value (here a random variable)
value = np.random.random()
self.logger.record('random_value', value)
return True
model.learn(50000, callback=TensorboardCallback())

How to pickle function from imported module with dill

I'm trying to pickle functions with dill. I want to include the whole function and not just a reference to it. Here are my two files:
fun.py:
import dill
from foo import ppp
def qqq(me):
return me + 1
print(dill.dumps(ppp, protocol=4, recurse=True, byref=True))
print(dill.dumps(qqq, protocol=4, recurse=True, byref=True))
And foo.py
def qqq(me):
return me + 1
When I run fun.py I get the following output:
b'\x80\x04\x95\x0f\x00\x00\x00\x00\x00\x00\x00\x8c\x03foo\x94\x8c\x03ppp\x94\x93\x94.'
b'\x80\x04\x95\x90\x00\x00\x00\x00\x00\x00\x00\x8c\ndill._dill\x94\x8c\x10_create_function\x94\x93\x94(h\x00\x8c\n_load_type\x94\x93\x94\x8c\x08CodeType\x94\x85\x94R\x94(K\x01K\x00K\x01K\x02KCC\x08|\x00d\x01\x17\x00S\x00\x94NK\x01\x86\x94)\x8c\x02me\x94\x85\x94\x8c\x06fun.py\x94\x8c\x03qqq\x94K\x04C\x02\x00\x01\x94))t\x94R\x94}\x94h\rNN}\x94Nt\x94R\x94.'
I want to be able to make the first line of output be more similar to the second line, and actually encapsulate the function without the need for a context when reloaded later. Is there a way to do this?
Thanks so much!
James
If the module (foo) is installed on both computers, then there should be no need to do anything but import the function. So, I'll assume the question is in regard to a module that is only installed on the first machine.
It also depends on whether the module foo is "installed" on sys.path or is just available in the current directory. See:
https://github.com/uqfoundation/dill/issues/123
If it's only available in the current directory, either use dill to pickle the file itself or use something like dill.source.getsource to extract the source of the module as a string, and then transfer the string as a "pickle" (this is what ppft does).
Generally, however, dill pickles imported functions by reference, and thus assumes they are available on both sides of the load/dump.

SymPy Wronskian function

I have been trying to compute the wronskian using SymPy, and can not figure out how to use the function. I did look at the program itself but I am very new to python. For functions any sinusoidal is okay. I just want to observe how to use SymPy in this way for future reference. Any help would be great!
~I listed my imports below
import sympy as sp
from scipy import linalg
import numpy as np
sp.init_printing()
I don't this that 'var' is the only thing wrong with what I am inputting.
You have to define the var first. You have not defined it. Also the functions should go in a list.
x = sp.Symbol('x')
## Define your var here
Wronskian_Sol = sp.matrices.dense.wronskian([sp.sin(x), 1-sp.cos(x)**2], var, method="bareiss")
Here is an example in this book "Applied Differntial Equation with Boundary Value Problems" by Vladimir A. Dobrushkin at page 199.
I computed a Wronskian for these three functions using Sympy
x
x*sin(x)
x*cons(x)
import sympy as sp
x = sp.Symbol('x')
var = x
Wronskian_Sol = sp.matrices.dense.wronskian([x, x*sp.cos(x), x*sp.sin(x)], var, method="bareiss")
print(Wronskian_Sol)
print(Wronskian_Sol.simplify())
This gives the output. The first is not simplified, the last one is simplified. You can reduce the first one to simplified version easily by taking the common factor x**3 out which leaves (sin(x)**2 + cos(x)**2) ..and this is nothing but 1.
x**3*sin(x)**2 + x**3*cos(x)**2
x**3
You can confirm the solution by manually taking the determinant of the derivative matrix.

Coefficient in support vector regression (SVR) using grid search (GridSearchCV) and Pipeline in Scikit Learn

I am having trouble to access the coefficients of a support vector regression model (SVR) in scikit learn when the model is embedded in a pipeline and a grid search.
Consider the following example:
from sklearn.datasets import load_iris
import numpy as np
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVR
from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import Pipeline
iris = load_iris()
X_train = iris.data
y_train = iris.target
clf = SVR(kernel='linear')
select = SelectKBest(k=2)
steps = [('feature_selection', select), ('svr', clf)]
pipeline = Pipeline(steps)
grid = GridSearchCV(pipeline, param_grid={"svr__C":[10,10,100],"svr__gamma": np.logspace(-2, 2)})
grid.fit(X_train, y_train)
This seems to work fine but when I try to access the coefficient of the best fitting model
grid.best_estimator_.coef_
I get an error message: AttributeError: 'Pipeline' object has no attribute 'coef_'.
I also tried to access the individual steps of the pipeline:
pipeline.named_steps['svr']
but could not find the coefficients there.
Just happened to come across the same problem and this post
had the answer:
grid.best_estimator_ contains an instance of the pipeline, which consists of steps. The last step should always be the estimator, so you should always find the coefficients at:
grid.best_estimator_.steps[-1][1].coef_

New to Python - proficient with Matlab: getting error "IndexError: list index out of range"

As the title says, I'm proficient with Matlab and already have this function written there and it works great. I wanted to learn a new language and I've been pointed to Python so I figured I would write a simple function to get used to the syntax of Python and have something to validate what I've done. I wrote the function "Xfcn" (which is non-dimensional mass flow in rocket problems) and it gives me the correct number if I only use one value. Now, I'd like to plot the X-function versus Mach and validate with my Matlab version. I need to loop through some Mach vector then plot it. Plotting comes later. I'm getting the error mentioned above and I think it's a simple indexing problem, although I can't seem to figure out what it is. I've looked here and on Python's documentation center so hopefully we can resolve this quickly. I've also checked the "type" of "i", printed the range(len(Ms)) and get 0-49, by 1's, as I expect with the particular values of Ms 0-1 by equally spaced increments, also as I expect, so I cannot figure out where my error is. My code is below.
from Xfcn import Xfcn
import pylab as pyl
import numpy as np
Ms = np.linspace(0,1,endpoint=True)
X = []
for i in range(len(Ms)):
X[i][0] = Xfcn(Ms[i])
print X
print 'Done.'
Thanks for the help!
BL
You created x as a single dimensional list and are trying to access it as if it was multi dimensional