如何使用不同参数多次运行jupyter笔记本

2024-06-25 23:58:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个开源代码,我在网上找到的,我想运行几次只改变一个参数。我怎样才能在Jupyter笔记本上做到这一点?我还下载了.py中的文件,尝试在Spyder中执行,但因为不是一个函数,而是一个完整的脚本,我不知道如何运行多次?有一种方法可以在for循环中实现这一点吗

我想做一些类似的事情: β=[0:5:1000] 对于BETA中的BETA_X: 运行笔记本测试

get_ipython().run_line_magic('matplotlib', 'inline')


# 
# EM: TDEM: 1D REAL DATA: TEMFAST data Inversion  
# ==========================================
# 
# 
# 
# 

# In this notebook, I'm trying to invert field data from a TEMFAST acquisition.
# Is a grounded square loop with 25m X 25m, with the receiver and transmiter at the same place. 

# <img src="tx_rx.png" width="400">
# 

# <img src="tem_48.png" width="400">

# In[2]:


# Import all the libraries we need
import numpy as np
import os
from scipy.optimize import curve_fit
import pandas as pd
from SimPEG import (
    Mesh, Maps, SolverLU, DataMisfit, Regularization,
    Optimization, InvProblem, Inversion, Directives, Utils
)
import SimPEG.EM as EM
from SimPEG.Utils import mkvc
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
try:
    from pymatsolver import Pardiso as Solver
except ImportError:
    from SimPEG import SolverLU as Solver



# In[3]:


# larger font size for plots
from matplotlib import rcParams
rcParams['font.size']=14
fname = 'T1P1_50_5'
fnameinv = fname+'_inv'
fnameforw = fname+'_forw'
fnameconduc = fname+'_coduct'


# In[4]:


# open the location in pc where are the files
data_directory = os.path.sep.join(["..", "p1"])
#os.listdir(data_directory)


# In[5]:



temfast_data = pd.read_table(os.path.sep.join([data_directory, "dados1.txt"]))  #Load data file
waveform_temfast = pd.read_table(
                os.path.sep.join([data_directory, "onda_reduz_V5.txt"]))  #Load waveform data

# More Code ....
.
.
.
.


# ## State the inverse problem

# In[21]:


opt = Optimization.InexactGaussNewton(maxIter=50)
opt.LSshorten = 0.5
opt.remember('xc')

invProb = InvProblem.BaseInvProblem(dmisfit, reg, opt)


# In[22]:


target = Directives.TargetMisfit()  # stop when we hit target misfit
invProb.beta = BETA_X
# betaest = Directives.BetaEstimate_ByEig(beta0_ratio=1e0)
inv = Inversion.BaseInversion(invProb, directiveList=[target])
# run the inversion
mrec = inv.run(m0)


# In[25]:


# extract the data so
dpred = -invProb.dpred


fig, ax = plt.subplots(1, 1)

ax.loglog(time_channels, dobs, "C0s", label="dobs")
plt.errorbar(time_channels, dobs, yerr=uncert, color="C0")
ax.loglog(time_channels, dpred, "C1", label="dpred")
ax.set_xlabel("time (s)")
ax.set_ylabel("db$_z$ / dt normalized [V / A.m$^4$]")
ax.grid('k', alpha=0.5)
ax.legend()
plt.savefig(fnameinv+'.eps',bbox_inches = "tight", format='eps', dpi=1000)


# In[26]:


misfit_inv = dpred - dobs
misfit_inv_err_2 = (misfit_inv/ uncert)**2
x_square = ((np.sum(misfit_inv_err_2))**0.5)/len(dobs)
print('x_square = {:.3f}'.format(x_square))





header = ["dobs", "dpred_0", "dpred", "mrec"]
r3_data = pd.DataFrame(data = np.zeros((45,4)), columns = header )


# In[28]:


r3_data["dobs"][1:] = dobs
r3_data["dpred_0"][1:] = dpred_0
r3_data["dpred"][1:] = dpred
r3_data["mrec"] = mrec


# In[29]:


r3_data.to_csv(fname+'.csv',sep = '\t')


# In[30]:


rcParams['font.size']=12
misfit = np.abs(dobs-dpred)
plt.figure(figsize=(10, 8))
ax0 = plt.subplot2grid((2, 2), (0, 0), rowspan=2)
ax1 = plt.subplot2grid((2, 2), (0, 1))



mplot = np.repeat(np.exp(mrec), 2, axis=0)
z = np.repeat(mesh.vectorCCz[active_inds][1:], 2, axis=0)
ax0.semilogx(mplot, np.r_[z[0], z, z[-1]])
ax0.set_ylabel("z (m)")
ax0.set_xlabel("conductivity (S/m)")
ax0.set_title('(a) Conductivity Profile')
ax0.set_ylim([-50, 1])
ax0.grid('k', alpha=0.5)

ax1.loglog(time_channels, misfit,'bo')
ax1.set_xlim(time_channels.min(), time_channels.max())
ax1.grid(which='both', alpha=0.5, linestyle='-', linewidth=0.2)
ax1.set_xlabel('Time (s)')
ax1.set_title('(b) |dobs - dpred|')
plt.savefig(fnameconduc+'.eps',bbox_inches = "tight", format='eps', dpi=1000)


# In[ ]:

Tags: theinfromimportdatatimenpplt