SymPy Wronskian function - 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.

Related

rdbwselect in R not showing output

I'm using the package rdrobust in R and Stata. I planned to fully implement the analysis in R, but encountered a problem with the function rdbwselect. This function computes different bandwidths depending on the selection procedure. By default, the procedure is Mean Square Error bwselect=mserd. However, I'm interested in exploring other procedures and comparing them. I then tried ALL=true; which is the option that according to the package "if specified, rdbwselect reports all available bandwidth selection procedures"
My issue is that, in R, rdbwselect is not showing me the bandwidths, not with the default not with the 'all' option or any other specification
x<-runif(1000,-1,1)
y<-5+3*x+2*(x>=0)+rnorm(1000)
## With default mserd
rdbwselect(y,x,)
## All selection procedures
rdbwselect(y,x,all= TRUE)
Output rdwselect
The output of both lines of rdbwselect code is exactly the same (see image), and it should not. I also try replicating the script from the rdrobust article in The R Journal (Page 49) and I don't get the same output as in the paper.
Nevertheless, the function is working in Stata 16
clear all
set obs 1000
set seed 1234
gen x = runiform(-1,1)
gen y = 5+3*x+2*(x>=0)+rnormal()
rdbwselect y x
rdbwselect y x, all
Could someone provide me with some guidance on why R is not showing me the complete expected output of the function rdbwselect? I'm wondering if this is an issue related to my version of R? Could this be a bug with the R package or the specific function rdbwselect? How can I verify the computation behind rdbwselect?
I appreciate any advice or follow-up questions.
Found the solution. All I needed to do was to embed the function within the summary() function
summary(rdbwselect(y,x,))
or add a pipe and the summary function
rdbwselect(y,x,all= TRUE) %>%
summary()
I want to post it as this is nowhere mentioned in the package documentation nor the article in The R Journal.

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

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".

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())

define theano function with other theano function output

I am new to theano, can anyone help me defining a theano function like this:
Basically, I have a network model looks like this:
y_hat, cost, mu, output_hiddens, cells = nn_f(x, y, in_size, out_size, hidden_size, layer_models, 'MDN', training=False)
here the input x is a tensor:
x = tensor.tensor3('features', dtype=theano.config.floatX)
I want to define two theano functions for later use:
f_x_hidden = theano.function([x], [output_hiddens])
f_hidden_mu = theano.function([output_hiddens], [mu], on_unused_input = 'warn')
the first one is fine. for the second one, the problem is both the input and the output are output of the original function. it gives me error:
theano.gof.fg.MissingInputError: An input of the graph, used to compute Elemwise{identity}(features), was not provided and not given a value.
my understanding is, both of [output_hiddens] and [mu] are related to the input [x], there should be an relation between them. I tried define another theano function from [x] to [mu] like:
f_x_mu = theano.function([x], [mu]),
then
f_hidden_mu = theano.function(f_x_hidden, f_x_mu),
but it still does not work. Does anyone can help me? Thanks.
The simple answer is NO WAY. In here
Because in Theano you first express everything symbolically and afterwards compile this expression to get functions, ...
You can't use the output of theano.function as input/output for another theano.function since they are already a compiled graph/function.
You should pass the symbolic variables, such as x in your example code for f_x_hidden, to build the model.

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