Mo *_*and 2 python vtk pde fenics google-colaboratory
我正在尝试访问保存热方程解的 VTK 文件,但我不知道它在 Colab 中的保存位置。
from fenics import *
import time
T = 2.0 # final time
num_steps = 50 # number of time steps
dt = T / num_steps # time step size
# Create mesh and define function space
nx = ny = 30
mesh = RectangleMesh(Point(-2, -2), Point(2, 2), nx, ny)
V = FunctionSpace(mesh, 'P', 1)
# Define boundary condition
def boundary(x, on_boundary):
return on_boundary
bc = DirichletBC(V, Constant(0), boundary)
# Define initial value
u_0 = Expression('exp(-a*pow(x[0], 2) - a*pow(x[1], 2))',
degree=2, a=5)
u_n = interpolate(u_0, V)
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(0)
F = u*v*dx + dt*dot(grad(u), grad(v))*dx - (u_n + dt*f)*v*dx
a, L = lhs(F), rhs(F)
# Create VTK file for saving solution
vtkfile = File('heat_gaussian/solution.pvd')
# Time-stepping
u = Function(V)
t=0
for n in range(num_steps):
# Update current time
t += dt
# Compute solution
solve(a == L, u, bc)
# Save to file and plot solution
vtkfile << (u, t)
plot(u)
# Update previous solution
u_n.assign(u)
# Hold plot
#interactive()
Run Code Online (Sandbox Code Playgroud)
我试过了;
from google.colab import files
plt.savefig("vtkfile")
files.download("vtkfile")
Run Code Online (Sandbox Code Playgroud)
和
from google.colab import files files.upload()
from google.colab import drive drive.mount('vtkfile')
Run Code Online (Sandbox Code Playgroud)
但仍然出现错误。在笔记本中创建的文件存储在哪里?
Ste*_*ven 10
这里的许多答案都集中在您可以在 Colab UI 中直观地看到文件的位置。
实际上,这些文件存储在Colab 托管虚拟机中。当您启动笔记本实例时,Google 会启动一个专用的临时虚拟机,您的 Jupyter 笔记本将在其中运行。这是存储和执行笔记本的位置,也是读取和写入代码中的任何文件的位置。当此笔记本最终超时(您将收到“运行时断开连接”消息)时,VM 以及您创建的所有文件都会被销毁。正如其他答案所示,只要虚拟机正在运行,您就可以使用 UI 查看驻留在该虚拟机上的文件:
您的代码需要读取的任何外部文件必须首先上传到虚拟机。同样,如果您想保留代码创建的任何文件,则必须在它们被销毁之前从虚拟机本地下载它们。您可以使用“文件”区域手动向虚拟机上传和下载文件。
您可以使用以下代码在代码中执行此操作google.colab.files:
from google.colab import files
# Upload a file from local PC to your Colab VM
files.upload('mylocalfile.txt')
# Download a file from your Colab VM to local PC
files.download('mylocalfile.txt')
Run Code Online (Sandbox Code Playgroud)
您还可以通过将驱动器安装到 Colab VM 来让 VM 直接访问 Google Drive 上的文件,使用google.colab.drive:
from google.colab import drive
drive.mount('/content/drive') # Mount your Google Drive to the local /content/drive directory
with open('/content/drive/My Drive/foo.txt', 'w') as f:
# read / write like any VM-local file
f.write('Hello Google Drive!')
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息和示例,请参阅有关本地文件系统的官方Colab 文档。
顺便说一句,托管虚拟机并不是唯一的选择:
您还可以连接到本地运行时,在这种情况下,文件将位于您的计算机本地,就像本地 Jupyter 实例或 GCE (Google 计算引擎)VM一样,GCE(Google 计算引擎)VM 可以单独租用,并允许您使用大量更强大的虚拟机,不会超时并且由您完全控制。
如果您安装了 GDrive,则文件应存储在名为Colab Notebooks的文件夹中
您还可以使用以下命令之一检查当前文件夹。
%cd
Run Code Online (Sandbox Code Playgroud)
或者
!pwd
Run Code Online (Sandbox Code Playgroud)