1

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

我该如何解决这个问题,如何为这个脚本创建两个 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, 0, 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,  fuel="nc7h16", oxidizer={"o2": 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)$');
4

2 回答 2

0

我修改了脚本的第一部分。我删除了 time_history 作为 ct.SolutionArray(gas, extra="t") 的函数,因为它在创建功能数据框来保存数据时产生了问题。现在,我实现了 pandas 以保存到 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")

有人可以帮忙吗?感谢所有想给我一个关于使用熊猫的内在问题的答案的人。

于 2021-07-15T10:02:27.253 回答
0

您应该只更改命令

timeHistory.to_csv("time_history.csv") 

如下 :

time_history.write_csv('time_history.csv')
于 2021-12-17T06:28:16.260 回答