PFR data to csv using pandas

210 views
Skip to first unread message

tullio viola

unread,
Dec 5, 2020, 1:49:05 PM12/5/20
to Cantera Users' Group
Hi all,

I modeled this pfr using as example https://cantera.org/examples/jupyter/reactors/1D_pfr_surfchem.ipynb.html without surface chemistry.

I want to save gas species molar fraction, temperature, distance, time ...how can I do this with pandas? The code is below.

Best regards to all


Tullio Viola



 

"""
Created by

@author: Tullio Viola
email:   dblabtul...@gmail.com
"""


from __future__ import division
from __future__ import print_function
from bigfloat import *
from builtins import *
from decimal import*
from math import*
import numpy as np
import time


# Initialize Cantera for numerical simulation

import pandas as pd
import numpy as np
import time
import cantera as ct
#######################################################################
# Input Parameters
#######################################################################

T_0 = 1500.0  # inlet temperature [K]
pressure = ct.one_atm  # constant pressure [Pa]
composition_0 = 'H2:2, O2:1, AR:0.1'
length = 1.5e-7  # *approximate* PFR length [m]
u_0 = .006  # inflow velocity [m/s]
area = 1.e-4  # cross-sectional area [m**2]

# input file containing the reaction mechanism
reaction_mechanism = 'ARAMCO.cti'

# Resolution: The PFR will be simulated by 'n_steps' time steps or by a chain
# of 'n_steps' stirred reactors.
n_steps = 2000
#####################################################################




# import the gas model and set the initial conditions
gas = ct.Solution(reaction_mechanism)
gas.TPX = T_0, pressure, composition_0
mass_flow_rate = u_0 * gas.density * area
dz = length / n_steps
r_vol = area * dz

# create a new reactor
r = ct.IdealGasReactor(gas)
r.volume = r_vol

# create a reservoir to represent the reactor immediately upstream. Note
# that the gas object is set already to the state of the upstream reactor
upstream = ct.Reservoir(gas, name='upstream')

# create a reservoir for the reactor to exhaust into. The composition of
# this reservoir is irrelevant.
downstream = ct.Reservoir(gas, name='downstream')

# The mass flow rate into the reactor will be fixed by using a
# MassFlowController object.
m = ct.MassFlowController(upstream, r, mdot=mass_flow_rate)

# We need an outlet to the downstream reservoir. This will determine the
# pressure in the reactor. The value of K will only affect the transient
# pressure difference.
v = ct.PressureController(r, downstream, master=m, K=1e-5)

sim = 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

PFR_test = pd.DataFrame(columns=columnNames)


# Start the stopwatch
tic = time.time()


# define time, space, and other information vectors
z = (np.arange(n_steps) + 1) * dz
t_r = np.zeros_like(z)  # residence time in each reactor
u = np.zeros_like(z)
t = np.zeros_like(z)
states = ct.SolutionArray(r.thermo)

# iterate through the PFR cells
for n in range(n_steps):
    # Set the state of the reservoir to match that of the previous reactor
    gas.TDY = r.thermo.TDY
    upstream.syncState()
    # integrate the reactor forward in time until steady state is reached
    sim.reinitialize()
    sim.advance_to_steady_state()
    # compute velocity and transform into time
    u[n] = mass_flow_rate / area / r.thermo.density
    t_r[n] = r.mass / mass_flow_rate  # residence time in this reactor
    t[n] = np.sum(t_r)
    # write output data
    states.append(r.thermo.state)

# Stop the stopwatch
toc = time.time()

PFR_test.loc[t[n]] = states
#####################################################################

PFR_test.to_csv("PFR_test.csv")
#####################################################################
# Compare Results in matplotlib
#####################################################################

import matplotlib.pyplot as plt

plt.figure()
plt.plot(z, states.T, label='Lagrangian Particle')
plt.xlabel('$z$ [m]')
plt.ylabel('$T$ [K]')
plt.legend(loc=0)
plt.show()

plt.savefig('pfr_T_z.png')

plt.figure()
plt.plot(t, states.X[:, gas.species_index('H2')], label='Lagrangian Particle')
plt.xlabel('$t$ [s]')
plt.ylabel('$X_{H_2}$ [-]')
plt.legend(loc=0)
plt.show()

plt.savefig('pfr_XH2_t.png')

Ingmar Schoegl

unread,
Dec 5, 2020, 2:41:26 PM12/5/20
to Cantera Users' Group
The upcoming 2.5 release implements an export from SolutionArray to pandas, see    https://github.com/Cantera/cantera/blob/1e12128c85784f85849315a03fdc6e289fa46a9e/interfaces/cython/cantera/composite.py#L1019 
So all you need to do is call this on your states variable. From there you simply use pandas’ export functions. Note that another new feature is to save data to HDF container files.
Hope this  helps,
-Ingmar-
Message has been deleted

tullio viola

unread,
Dec 10, 2020, 4:54:54 PM12/10/20
to canter...@googlegroups.com
but...if I don't want to use the surface chemistry how can I delete completely from pfr_surfchem? Thank you so much


Il giorno gio 10 dic 2020 alle ore 22:09 tullio viola <tulliov...@gmail.com> ha scritto:
thank you so much but how can I install cantera 2.5?
--
You received this message because you are subscribed to the Google Groups "Cantera Users' Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cantera-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cantera-users/6c415bcb-ec79-48f5-ab70-0249e35b01e5n%40googlegroups.com.

Ingmar Schoegl

unread,
Dec 10, 2020, 7:54:57 PM12/10/20
to Cantera Users' Group
Ciao Tullio,

Regarding cantera 2.5 - you can install the beta version using conda from the cantera development branch, see here: https://cantera.org/install/conda-install.html (follow steps and use Option 3; this should get you to cantera version 2.5.0b1). There hasn't been much in terms of updates since, so I assume it's close to the final release.

Regarding your question about surface chemistry, I'm not sure: the code you posted apparently doesn't use surface chemistry? (while the linked example defines a ct.Interface, your posted example doesn't). Btw, there are also other PFR examples without surface chemistry among the regular python examples, i.e. https://cantera.org/examples/python/index.html (there *may* be slight updates for 2.5; examples are installed together with the code, or can be downloaded from GitHub, i.e. https://github.com/Cantera/cantera/tree/main/interfaces/cython/cantera/examples/reactors).

-ingmar-

Deity Neo

unread,
Jun 28, 2021, 8:15:22 AM6/28/21
to Cantera Users' Group
How can you combine more then one PFR Series?

Ingmar Schoegl

unread,
Jun 28, 2021, 10:16:23 AM6/28/21
to Cantera Users' Group
Not in a CSV, but if I understand your question correctly you can save multiple PFR series in a HDF file using the `group` argument: see https://cantera.org/documentation/docs-2.5/sphinx/html/cython/importing.html#cantera.SolutionArray.write_hdf
-is-

You received this message because you are subscribed to a topic in the Google Groups "Cantera Users' Group" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/cantera-users/EIXc6PSPCkg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to cantera-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cantera-users/f9d214f3-049a-4ff6-87a0-6306a7404f4dn%40googlegroups.com.

tullio viola

unread,
Jun 28, 2021, 10:36:16 AM6/28/21
to canter...@googlegroups.com
Dear all, the problem is how to write states in the dataframe made with pandas. 

But, first of all, how can I see all states as print function?

Ingmar Schoegl

unread,
Jun 28, 2021, 10:44:55 AM6/28/21
to Cantera Users' Group
As long as you create a `SolutionArray` first, you can easily convert the output to pandas via `to_pandas`, see https://cantera.org/documentation/docs-2.5/sphinx/html/cython/importing.html#cantera.SolutionArray.to_pandas

I am not sure that I understand the question regarding the print function?
-ingmar-

tullio viola

unread,
Jun 28, 2021, 11:03:17 AM6/28/21
to canter...@googlegroups.com
I'll try to explain again: I would like to understand how to print all the calculated variables on the screen.
Then I would like to be able to save them in a dataframe created with pandas

Ingmar Schoegl

unread,
Jun 28, 2021, 11:36:41 AM6/28/21
to Cantera Users' Group
Ah - I see. A 'pretty' print function for `SolutionArray` isn't really implemented, so you'd have to query the parts of a SolutionArray 'states' (i.e. look at states.T, states.X, etc.). However, you can use pandas to get what you want. Let's use the `combustor.py` example, which assigns results to the SolutionArray `states`. I'm running the example in `ipython` below:

In [1]: %run combustor.py
tres = 1.00e-01; T = 1475.8
tres = 9.00e-02; T = 1475.4
tres = 8.10e-02; T = 1474.9
...
tres = 1.48e-03; T = 300.0

In [2]: states # this doesn't output values, just the object (i.e. no print)
Out[2]: <cantera.composite.SolutionArray at 0x7fd8e4075128>

In [3]: states.to_pandas()
Out[3]:
        tres            T   density  ...        Y_C3H8      Y_CH2CHO      Y_CH3CHO
0   0.100000  1475.793163  0.232880  ...  1.071489e-12  4.324619e-11  1.473562e-09
1   0.090000  1475.383102  0.232939  ...  1.238781e-12  4.868448e-11  1.714413e-09
2   0.081000  1474.944422  0.233003  ...  1.430820e-12  5.477223e-11  1.992888e-09
...
40  0.001478   300.000000  1.146022  ...  3.726470e-19 -1.100897e-38  1.316806e-18

[41 rows x 56 columns]

Hope this helps.
-ingmar-

tullio viola

unread,
Jun 28, 2021, 2:57:25 PM6/28/21
to canter...@googlegroups.com
thank you very much Dear Ingmar you were really comprehensive and clear

Tullio Viola
Stems-cnr, Naples

Deity Neo

unread,
Jun 29, 2021, 3:55:49 AM6/29/21
to Cantera Users' Group
Ingmar Schoegl i meant how can i combine more then one PFR Series with a chain reactor concept like in the pfr.py example.
Reply all
Reply to author
Forward
0 new messages