当前位置: 代码迷 >> python >> Tensorflow Odeint
  详细解决方案

Tensorflow Odeint

热度:51   发布时间:2023-06-19 09:14:16.0

我有一个系统,需要使用图形来解决此功能。

我正在尝试使用tf.contrib.integrate.odeint(),但是此函数只能获取一阶ODE,因此我将其分为两个微分方程。 这是我所做的:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import math as mat

graph = tf.Graph() 
with graph.as_default(): 
    R = tf.constant(100.)
    L = tf.constant(0.002)
    C = tf.constant(0.000005)
    E = tf.constant(10.)
    '''
    Inital EDO:
    d?2(vc)/dt?2 + R/L * dvc/dt + vc/LC = E/LC

    dvc/dt=z

    dvz/dt = (E-vc)/LC - R*z/L
    '''
    #dvz/dt = (E-vc)/LC - R*z/L
    EDO0 =  lambda z, t: (E-vc)/(L*C) - R/L * z

    #dvc/dt=z
    EDO1 = lambda vc, t: z

    #initial value
    EDO1_init = constant_op.constant(1.0, dtype=dtypes.float64)
    t = np.linspace(0.0, 1.0, 11)
    EDO1_solved = tf.contrib.integrate.odeint(EDO0, 0.5, t)

    with tf.Session() as sess:
      y_solved = sess.run(EDO1_solved)
      print(y_solved)
      tf.summary.FileWriter('/tmp/logs', tf.get_default_graph()).close()

但我在方程式方面遇到一些问题

我找不到解决方案的主要问题是我必须使用tensorflow包。

@LutzL我想使用tensorflow包,因为这是教授的必备条件。

所以我在一些朋友的帮助下找到了答案:

'''
Inital DOE:
vc'' + R/L * vc' + vc/LC = E/LC

Using state variables:
x1  = vc
x1' = vc'
x2  = vc' = x1'
x2' = vc''

       a       b       c
x2' = E/LC - R/L*x2 - 1/LC*x1
x1' = x2
y   = x1 

'''
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

graph = tf.Graph() 
with graph.as_default():  
  E = 10.0   #Source Voltage
  R = 2.5    #Resistor
  L = 0.01   #inductor
  C = 0.001  #capacitor

  a = E / (L * C)
  b = R / L
  c = 1.0 / (L * C)

  x1 = tf.constant(0.0)
  x2 = tf.constant(0.0)

  t = np.linspace(0, 1.0, num=1000)

  def SecondOrderDev(state, t):
    x1, x2 = tf.unstack(state)    
    dx1 = x2
    dx2 = -c*x1 - b*x2 + f
    return tf.stack([dx1, dx2])

  tensor_state, tensor_info = tf.contrib.integrate.odeint(SecondOrderDev, [x1, x2], t, full_output=True)

  with tf.Session() as sess:
    state, info = sess.run([tensor_state, tensor_info])
    y, _ = state.T
    tf.summary.FileWriter('/tmp/logs', tf.get_default_graph()).close()

  plt.plot(t, y)

这就是您正在使用colab并想查看该图的情况:

!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip ngrok-stable-linux-amd64.zip

LOG_DIR = '/tmp/logs'
get_ipython().system_raw(
    'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'
    .format(LOG_DIR)
)
get_ipython().system_raw('./ngrok http 6006 &')

! curl -s http://localhost:4040/api/tunnels | python3 -c \
    "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])" 
  相关解决方案