如何将数据保存到 csv Cantera 和错误 <cantera.composite.SolutionArray object at 0x7f4badca0fd0>

如何解决如何将数据保存到 csv Cantera 和错误 <cantera.composite.SolutionArray object at 0x7f4badca0fd0>

我在 Cantera 上有这个脚本。我想将脚本的两个部分的数据保存到 csv 中:第一个评估 Tfinal 与自燃延迟时间,第二个评估 NTC 行为。在第一部分,示例建议取消注释 #timeHistory.to_csv("time_history.csv") 但它不起作用。我想我需要创建一个数据框,因为它没有很好地定义(我想)。不仅如此,我还看到了这个错误

我该如何解决这个问题,以及如何为此脚本创建两个 csv?

非常感谢

    import pandas as pd
    import numpy as np
    
    import time
    
    import cantera as ct
    print('Runnning Cantera version: ' + ct.__version__)
    
    import matplotlib.pyplot as plt
    
    plt.rcParams['axes.labelsize'] = 18
    plt.rcParams['xtick.labelsize'] = 12
    plt.rcParams['ytick.labelsize'] = 12
    plt.rcParams['figure.autolayout'] = True
    
    plt.style.use('ggplot')
    plt.style.use('seaborn-pastel')
    
    gas = ct.solution('Seiser.cti')
    
    # Define the reactor temperature and pressure
    reactor_temperature = 1000  # Kelvin
    reactor_pressure = 101325  # Pascals
    
    gas.TP = reactor_temperature,reactor_pressure
    
    # Define the fuel,oxidizer and set the stoichiometry
    gas.set_equivalence_ratio(phi=1.0,fuel="nc7h16",oxidizer={"o2": 1.0,"n2": 3.76})
    
    # Create a batch reactor object and add it to a reactor network
    # In this example,the batch reactor will be the only reactor
    # in the network
    r = ct.IdealGasReactor(contents=gas,name="Batch Reactor")
    reactor_network = ct.ReactorNet([r])
    
    # use the above list to create a DataFrame
    time_history = ct.solutionArray(gas,extra="t")
    
    def ignition_delay(states,species):
        """
        This function computes the ignition delay from the occurence of the
        peak in species' concentration.
        """
        i_ign = states(species).Y.argmax()
        return states.t[i_ign]
    
    reference_species = "oh"
    
    # Tic
    t0 = time.time()
    
    # This is a starting estimate. If you do not get an ignition within this time,increase it
    estimated_ignition_delay_time = 0.1
    t = 0
    
    counter = 1
    while t < estimated_ignition_delay_time:
        t = reactor_network.step()
        if not counter % 10:
            # We will save only every 10th value. Otherwise,this takes too long
            # Note that the species concentrations are mass fractions
            time_history.append(r.thermo.state,t=t)
        counter += 1
    
    # We will use the 'oh' species to compute the ignition delay
    tau = ignition_delay(time_history,reference_species)
    
    # Toc
    t1 = time.time()
    
    print(f"Computed Ignition Delay: {tau:.3e} seconds. Took {t1-t0:3.2f}s to compute")
    
    # If you want to save all the data - molefractions,temperature,pressure,etc
    # >>>>>>>>>>>>>>>>>>>>>>>>uncomment the next line
    time_history.to_csv("time_history_TEST.csv")
    
    plt.figure()
    plt.plot(time_history.t,time_history(reference_species).Y,"-o")
    plt.xlabel("Time (s)")
    plt.ylabel("$Y_{OH}$")
    
    plt.xlim([0,0.05])
    plt.arrow(0,0.008,tau,width=0.0001,head_width=0.0005,head_length=0.001,length_includes_head=True,color="r",shape="full")
    plt.annotate(r"$Ignition Delay: \tau_{ign}$",xy=(0,0),xytext=(0.01,0.0082),fontsize=16);

# Make a list of all the temperatures we would like to run simulations at
T = np.hstack((np.arange(1800,900,-100),np.arange(975,475,-25)))

estimated_ignition_delay_times = np.ones_like(T,dtype=float)

# Make time adjustments for the highest and lowest temperatures. This we do empirically
estimated_ignition_delay_times[:6] = 6 * [0.1]
estimated_ignition_delay_times[-4:-2] = 10
estimated_ignition_delay_times[-2:] = 100

# Now create a SolutionArray out of these
ignition_delays = ct.solutionArray(gas,shape=T.shape,extra={"tau": estimated_ignition_delay_times})
ignition_delays.set_equivalence_ratio(1.0,"n2": 3.76})
ignition_delays.TP = T,reactor_pressure

for i,state in enumerate(ignition_delays):
    # Setup the gas and reactor
    gas.TPX = state.TPX
    r = ct.IdealGasReactor(contents=gas,name="Batch Reactor")
    reactor_network = ct.ReactorNet([r])

    reference_species_history = []
    time_history = []

    t0 = time.time()

    t = 0
    while t < estimated_ignition_delay_times[i]:
        t = reactor_network.step()
        time_history.append(t)
        reference_species_history.append(gas[reference_species].X[0])

    i_ign = np.array(reference_species_history).argmax()
    tau = time_history[i_ign]
    t1 = time.time()

    print('Computed Ignition Delay: {:.3e} seconds for T={}K. Took {:3.2f}s to compute'.format(tau,state.T,t1-t0))

    ignition_delays.tau[i] = tau

fig = plt.figure()
ax = fig.add_subplot(111)
ax.semilogy(1000/ignition_delays.T,ignition_delays.tau,'o-')
ax.set_ylabel('Ignition Delay (s)')
ax.set_xlabel(r'$\frac{1000}{T (K)}$',fontsize=18)

# Add a second axis on top to plot the temperature for better readability
ax2 = ax.twiny()
ticks = ax.get_xticks()
ax2.set_xticks(ticks)
ax2.set_xticklabels((1000/ticks).round(1))
ax2.set_xlim(ax.get_xlim())
ax2.set_xlabel(r'Temperature: $T(K)$');

解决方法

我修改了脚本的第一部分。我删除了 time_history 作为 ct.SolutionArray(gas,extra="t") 的函数,因为它在创建功能数据框以保存数据时产生了问题。现在,我实现了熊猫以保存到 csv 中,但是,它创建了带有列和变量声明的 csv 文件,但它没有填充 csv。此外,我看到了错误:

Traceback (most recent call last):
  File "test.py",line 77,in <module>
    tau = ignition_delay(tHyBatch_base,reference_species)
  File "test.py",line 50,in ignition_delay
    i_ign = states(species).Y.argmax()
TypeError: 'DataFrame' object is not callable



import pandas as pd
import numpy as np

import time
import csv
import cantera as ct
print('Running Cantera version: ' + ct.__version__)


import matplotlib.pyplot as plt

plt.rcParams['axes.labelsize'] = 18
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
plt.rcParams['figure.autolayout'] = True

plt.style.use('ggplot')
plt.style.use('seaborn-pastel')

gas = ct.Solution('Seiser.cti')

# Define the reactor temperature and pressure
reactor_temperature = 1000  # Kelvin
reactor_pressure = 101325  # Pascals

gas.TP = reactor_temperature,reactor_pressure

# Define the fuel,oxidizer and set the stoichiometry
gas.set_equivalence_ratio(phi=1.0,fuel="nc7h16",oxidizer={"o2": 1.0,"n2": 3.76})

# Create a batch reactor object and add it to a reactor network
# In this example,the batch reactor will be the only reactor
# in the network
r = ct.IdealGasReactor(contents=gas,name="Batch Reactor")
reactor_network = ct.ReactorNet([r])
 

# Now compile a list of all variables for which we will store data
columnNames = [r.component_name(item) for item in range(r.n_vars)]
columnNames = ['pressure'] + columnNames

tHyBatch_base=pd.DataFrame(columns=columnNames)
tHyBatch_base.index.name = 'time'

def ignition_delay(states,species):
    """
    This function computes the ignition delay from the occurence of the
    peak in species' concentration.
    """
    i_ign = states(species).Y.argmax()
    return states.t[i_ign]

reference_species = "oh"


# Tic
t0 = time.time()

# This is a starting estimate. If you do not get an ignition within this time,increase it
estimated_ignition_delay_time = 0.1
t = 0

counter = 1
while t < estimated_ignition_delay_time:
    t = reactor_network.step()
    if not counter % 10:
        # We will save only every 10th value. Otherwise,this takes too long
        # Note that the species concentrations are mass fractions
         state = np.hstack([r.thermo.state])
                    
         # Update the dataframe
         tHyBatch_base.append(pd.Series(state,index=tHyBatch_base.columns[:len(state)]),ignore_index=True)
    counter += 1

tHyBatch_base.to_csv("TESTCSV.csv")
# We will use the 'oh' species to compute the ignition delay
tau = ignition_delay(tHyBatch_base,reference_species)

# Toc
t1 = time.time()

print(f"Computed Ignition Delay: {tau:.3e} seconds. Took {t1-t0:3.2f}s to compute")

有人可以帮忙吗?感谢所有想为我解答使用 Pandas 的内在问题的人。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?