Example #1
0
 def __init__(self, s1, s2, T):
     self.s1 = s1
     self.s2 = s2
     self.p1_s = get_psat(s1, T)
     self.p2_s = get_psat(s2, T)
     self.q1 = get_volume(self.s1, T)
     self.q2 = get_volume(self.s2, T)
Example #2
0
def main(x1, y1, P, G_e, T, s1, s2):
    style.use('classic')

    w = Wohls(s1, s2, T)
    A = get_parameter(x1, G_e, s1, s2, T)
    acc = get_accuracy(G_e, w.Ge(x1, A))

    x = np.linspace(0, 1, 50)

    fig4 = plt.figure(facecolor='white')
    plt.title(r"$G^E-x$")
    plt.xlim(0, 1)
    plt.xlabel(r'$x_1$')
    plt.ylabel(r'$G^E\ (J/mol)$')
    plt.scatter(x1, G_e)
    plt.plot(x, w.Ge(x, A), label=r"$Wohls\ model$", color='red')
    plt.axhline(0, color='black')

    q1 = get_volume(s1, T)
    q2 = get_volume(s2, T)
    z = x * q1 / (x * q1 + (1 - x) * q2)

    p1_s = get_psat(s1, T)
    p2_s = get_psat(s2, T)

    P_Wohls = x * p1_s * w.gamma1(z, A) + (1 - x) * p2_s * w.gamma2(z, A)
    y_Wohls = x * p1_s * w.gamma1(z, A) / P_Wohls

    P_raoult = x * p1_s + (1 - x) * p2_s

    fig5 = plt.figure(facecolor='white')
    plt.title(r"$P-x$")
    plt.xlim(0, 1)
    plt.ylim(0, 1.2 * max(P))
    plt.xlabel(r'$x_1$')
    plt.ylabel(r'$P\ (kPa)$')
    plt.scatter(x1, P)
    plt.plot(x, P_Wohls, label=r"$Wohls\ model$", color='red')
    plt.plot(x, P_raoult, color='black', label=r"$Raoult's\ Law$")
    plt.legend(loc='best', fontsize=10)

    fig6 = plt.figure(facecolor='white')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.title(r"$y-x$")
    plt.xlim(0, 1)
    plt.ylim(0, 1)
    plt.xlabel(r'$x_1$')
    plt.ylabel(r'$y_1$')
    plt.scatter(x1, y1)
    plt.plot(x, y_Wohls, label=r"$Wohls\ model$", color='red')
    plt.plot(x, x, color='black')
    plt.legend(loc='best', fontsize=10)

    return A, acc, fig4, fig5, fig6
Example #3
0
    def process(self, x):
        p = len(x)

        # the first cluster
        if len(self.clusters) == 0:
            self.clusters.append(new_cluster(x, self.frac, self.fac, p,
                                             self.m))

        else:
            # elect winning cluster
            win_cluster = min_dist(x, self.clusters)
            win_cluster_radius = get_radius(self.fac, p, self.m, win_cluster.k)

            # point is not contained in the winning cluster
            if (distance.mahalanobis(x, win_cluster.centroid,
                                     win_cluster.inv_cov) >
                    win_cluster_radius):
                self.clusters.append(
                    new_cluster(x, self.frac, self.fac, p, self.m))

            else:
                self.clusters.remove(win_cluster)
                # update winning cluster
                update_winner_cluster(x, win_cluster)

                if len(self.clusters) != 0:
                    # update nearest neighbor of winning cluster
                    update_nearest_cluster(x, win_cluster, self.clusters)

                # check overlap
                (max_olap, max_cluster) = overlap(win_cluster, self.clusters)
                if (max_olap > 0):
                    cluster_merged = merge(win_cluster, max_cluster)

                    V_m = get_volume(cluster_merged, self.fac, p, self.m)
                    V_w = get_volume(win_cluster, self.fac, p, self.m)
                    V_c = get_volume(max_cluster, self.fac, p, self.m)
                    # Check volume, for the final decision
                    if V_m <= p * (V_w + V_c):
                        self.clusters.remove(max_cluster)
                        self.clusters.append(cluster_merged)
                    else:
                        self.clusters.append(win_cluster)
        pass
Example #4
0
def test(nyu2_loader, model, width, height):
    for i, image in enumerate(nyu2_loader):     
        image = torch.autograd.Variable(image, volatile=True).cuda()
        out = model(image)
        out = out.view(out.size(2),out.size(3)).data.cpu().numpy()
        max_pix = out.max()
        min_pix = out.min()
        out = (out-min_pix)/(max_pix-min_pix)*255
        out = cv2.resize(out,(width,height),interpolation=cv2.INTER_CUBIC)
        cv2.imwrite(os.path.join(args.output, "out_grey.png"),out)
        out_grey = cv2.imread(os.path.join(args.output, "out_grey.png"),0)
        out_color = cv2.applyColorMap(out_grey, cv2.COLORMAP_JET)
        cv2.imwrite(os.path.join(args.output, "out_color.png"),out_color)
        vol = get_volume(out_grey, args.json)
        print("Volume:")
        print(vol)
        print("unit: cm^3")
        out_file = open(os.path.join(args.output, "out.txt"), "w")
        out_file.write("Volume:\n")
        out_file.write(str(vol))
        out_file.write("\n")
        out_file.write("unit: cm^3")
        out_file.close()
        get_mask(out_grey, args.json, args.output)
Example #5
0
File: main.py Project: xwa9860/FIG
main file to 

1) read fuel composition from Mk1.txt MCNP input

2) generate fuel composition files that can be used in FIG to 
generate serpent input files

'''
import volume
import config
import pandas as pd
from ave_fuel_mat import sum_comp, sum_comp_2_zones
import numpy as np

# the weight(volume or flux) matrices have dimension 5x4x8
volmat = np.array(volume.get_volume()).reshape((4, 5, 1))
volmat = np.swapaxes(volmat, 0, 1)
print(volmat.shape)



print('compute average fuel composition for near wall zones')

# build a flux matrix for the wall regions by setting the
# active region flux to 0 in the full core flux matrix

# read volume*flux in each zone
fluxdf = pd.read_csv(config.FLUX_CSV_PATH, header=None)
fluxmat = fluxdf.values.reshape((5, 4, 8))
print('fluxmat')
print(fluxmat)
Example #6
0
def get_brain(subject, fname_surf_L=None, fname_surf_R=None, fname_tex_L=None,
              fname_tex_R=None, bad_areas=None, fname_vol=None, name_lobe_vol='Subcortical',
              trans=False, fname_atlas=None, fname_color=None):
    # type: (object, object, object, object, object, object, object, object, object, object, object) -> object
    """show structures

    Parameters
    ----------
    subject : str
        The name of the subject
    fname_surf_L : None | str
        The filename of the surface of the left hemisphere
    fname_surf_R : None | str
        The filename of the surface of the right hemisphere
    fname_tex_L : None | str
        The filename of the texture surface of the right hemisphere
        The texture is used to select areas in the surface
    fname_tex_R : None | str
        The filename of the texture surface of the left hemisphere
    bad_areas : list of int
        Areas that will be excluded from selection
    fname_vol : None | str
        The filename of mri labelized
    name_lobe_vol : None | list of str | str
        Interest lobe names
    trans : str | None
        The filename that contains transformation matrix for surface
    fname_atlas : str | None
        The filename of the area atlas
    fname_color : Brain surfer instance
        The filename of color atlas
    Returns
    -------
    figure : Figure object
    -------
    Author : Alexandre Fabre
    """

    list_hemi = ['lh', 'rh']
    volumes = None
    surfaces = None

    fname_surf = [fname_surf_L, fname_surf_R]
    fname_tex = [fname_tex_L, fname_tex_R]

    print('build surface areas')

    for i, hemi in enumerate(list_hemi):

        if fname_surf[i] is not None and fname_tex[i] is not None:

            if surfaces is None:
                surfaces = []

            surface = get_surface(fname_surf[i], subject=subject, hemi=hemi, trans=trans)

            # save to project areas on the hemisphere
            surface.save_as_ref()

            areas_hemi = get_surface_areas(surface, texture=fname_tex[i], hemi=hemi,
                                           subject=subject, fname_atlas=fname_atlas,
                                           fname_color=fname_color)
            # Delete WM (values of texture 0 and 255)
            bad_areas = [0, 42]
            if bad_areas is not None:
                areas_hemi = np.delete(areas_hemi, bad_areas, axis=0)

            surfaces.append(areas_hemi)

    print('[done]')

    print('build volume areas')
        
    if fname_vol is not None:
        volumes = []

        for hemi in list_hemi:
            cour_volume = get_volume(fname_vol, fname_atlas, name_lobe_vol, subject,
                                     hemi, True)

            volumes.append(cour_volume)

    print('[done]')

    brain = Brain(surfaces, volumes)

    return brain
Example #7
0
 def __init__(self, s1, s2, T):
     self.q1 = get_volume(s1, T)
     self.q2 = get_volume(s2, T)
     self.T = T
Example #8
0
main file to 

1) read fuel composition from Mk1.txt MCNP input

2) generate fuel composition files that can be used in FIG to 
generate serpent input files

'''
import volume
import config
import pandas as pd
from ave_fuel_mat import sum_comp, sum_comp_2_zones
import numpy as np

# the weight(volume or flux) matrices have dimension 5x4x8
volmat = np.array(volume.get_volume()).reshape((4, 5, 1))
volmat = np.swapaxes(volmat, 0, 1)
print(volmat.shape)

print('compute average fuel composition for near wall zones')

# build a flux matrix for the wall regions by setting the
# active region flux to 0 in the full core flux matrix

# read volume*flux in each zone
fluxdf = pd.read_csv(config.FLUX_CSV_PATH, header=None)
fluxmat = fluxdf.values.reshape((5, 4, 8))
print('fluxmat')
print(fluxmat)
fluxmat_wall = fluxmat
for passno in range(1, 9):
Example #9
0
def main():
    st.title("Correlations")
    st.write(
        """ The *Margules* model, *Redlich-Kister Expansion* truncated to two terms, *van Laar* model and the *Truncated Wohls expansion* are implemented here. """
        r"In case $\alpha$ fits the data with an accuracy of 80% or above, the $\alpha_{GM}$ value is displayed."
    )

    compounds = [
        'Acetonitrile', 'Acetone', '1,2-Ethanediol', 'Ethanol',
        'Diethyl ether', 'Ethyl acetate', 'Benzene', '1-Butanol', 'Chloroform',
        'Cyclohexane', 'Acetic acid butyl ester', 'Acetic acid', 'Hexane',
        '2-Propanol', '1-Hexene', 'Methanol', 'Tetrahydrofuran', 'Water',
        'm-Xylene', 'p-Xylene', 'N-Methyl-2-pyrrolidone', '1,3-Butadiene',
        'Hexadecane'
    ]

    menu_options = compounds.copy()

    for i, compound in enumerate(compounds):
        if ' ' in compound:
            compounds[i] = compound.replace(' ', '%20')

    compound1 = st.selectbox('Select compound 1',
                             menu_options,
                             key='compound1')
    compound2 = st.selectbox('Select compound 2',
                             menu_options,
                             key='compound2')

    i1 = menu_options.index(compound1)
    i2 = menu_options.index(compound2)

    st.info("You have chosen %s and %s" % (compound1, compound2))

    @st.cache(suppress_st_warning=True)
    def link_generator(i1, i2):
        url = 'http://www.ddbst.com/en/EED/VLE/VLE%20' + compounds[
            i1] + '%3B' + compounds[i2] + '.php'
        if requests.get(url).status_code == 404:
            url = 'http://www.ddbst.com/en/EED/VLE/VLE%20' + compounds[
                i2] + '%3B' + compounds[i1] + '.php'
        return url

    try:
        if compound1 == compound2:
            st.warning('Choose different compounds')
        else:
            url = link_generator(i1, i2)

        if requests.get(url).status_code == 404:
            st.error(
                "VLE data for this pair of compounds doesn't exist at DDBST.")

        dataframes = pd.read_html(url)

        isothermal_vledata = []
        T = []
        for i, data in enumerate(dataframes):
            col = data.columns
            if col.dtype == object:
                if len(col) == 3 and 'P' in col[0] and 'x1' in col[
                        1] and 'y1' in col[2]:
                    T.append(float(dataframes[i - 1][1]))
                    isothermal_vledata.append(dataframes[i])

        if isothermal_vledata == []:
            st.error(
                'There is no isothermal data available for this pair of compounds at DDBST'
            )
        else:
            for i in range(len(T)):
                st.write('%d)' % (i + 1), 'T = ', T[i], 'K')
                st.write(isothermal_vledata[i])
            if len(T) == 1:
                choice = 1
            else:
                choice = st.number_input('Choose a dataset',
                                         value=1,
                                         min_value=1,
                                         max_value=len(T))

            st.info('Analysing dataset %d ...' % choice)
            P = isothermal_vledata[choice - 1]['P [kPa]']
            x1 = isothermal_vledata[choice - 1]['x1 [mol/mol]']
            y1 = isothermal_vledata[choice - 1]['y1 [mol/mol]']
            T = T[choice - 1]
            st.write(r'$T = %0.2f K$' % T)

            p1sat = get_psat(compounds[i1], T)
            p2sat = get_psat(compounds[i2], T)

            if p1sat > p2sat:
                st.info('The more volatile component is %s' % menu_options[i1])
                s1, s2 = compounds[i1], compounds[i2]
            else:
                st.info('The more volatile component is %s' % menu_options[i2])
                s1, s2 = compounds[i2], compounds[i1]

            p1_s = max(p1sat, p2sat)
            p2_s = min(p1sat, p2sat)

            st.write(r'$p_1^s = %0.3f kPa$' % p1_s)
            st.write(r'$p_2^s = %0.3f kPa$' % p2_s)

            x = np.linspace(0, 1, 50)
            P_raoult = x * p1_s + (1 - x) * p2_s
            y_raoult = x * p1_s / P_raoult

            n_points = len(x1) - 1

            try:
                if x1[0] == 0 and x1[n_points] != 1:
                    x1, y1, P = x1[1:], y1[1:], P[1:]
                if x1[0] != 0 and x1[n_points] == 1:
                    x1, y1, P = x1[:n_points], y1[:n_points], P[:n_points]
                if x1[0] == 0 and x1[n_points] == 1:
                    x1, y1, P = x1[1:n_points], y1[1:n_points], P[1:n_points]
            except KeyError:
                pass

            q1, q2 = get_volume(s1, T), get_volume(s2, T)
            z1 = x1 * q1 / (x1 * q1 + (1 - x1) * q2)

            gamma1 = np.divide(P * y1, x1 * p1_s)
            gamma2 = np.divide(P * (1 - y1), ((1 - x1) * p2_s))
            G_e = constants.R * T * (xlogy(x1, gamma1) + xlogy(1 - x1, gamma2))

            alpha_gm = models.alphagm.get_alpha_gm(x1, y1)
            if alpha_gm == 0:
                pass
            else:
                st.success(r"$\alpha_{GM}=%0.3f$" % alpha_gm)
                st.text("Try using this value in the McCabe-Thiele Plotter!")

            model = st.selectbox("Choose a model", [
                "Select", "Margules", "Redlich Kister", "van Laar",
                "Truncated Wohls"
            ],
                                 key='model')

            if model == "Select":
                st.info("Select a model")
            else:
                if model != "Truncated Wohls":
                    MODELS = {
                        "Margules": models.margules,
                        "Redlich Kister": models.redlichkister,
                        "van Laar": models.vanlaar
                    }
                    latest_iteration = st.empty()
                    bar = st.progress(0)

                    for i in range(100):
                        latest_iteration.text(f'{i + 1}%')
                        bar.progress(i + 1)
                        time.sleep(0.03)

                    A, acc, fig4, fig5, fig6 = MODELS[model].main(
                        x1, y1, P, G_e, x, p1_s, p2_s, T, P_raoult)

                    if model == "Margules":
                        st.write(r"$G^E = %0.3fx_1x_2$" % A)
                    if model == "Redlich Kister":
                        st.write(r"$G^E = x_1x_2(%0.3f + (%0.3f)(x_1-x_2))$" %
                                 (A[0], A[1]))
                    if model == "van Laar":
                        st.write(
                            r"$\frac{x_1x_2}{G^E} = \frac{x_1}{%0.3f} + \frac{x_2}{%0.3f}$"
                            % (A[1], A[0]))
                    st.write(r"$R^2$ score = %0.3f" % acc)
                    st.write(fig4, fig5, fig6)
                else:
                    latest_iteration = st.empty()
                    bar = st.progress(0)

                    for i in range(100):
                        latest_iteration.text(f'{i + 1}%')
                        bar.progress(i + 1)
                        time.sleep(0.03)

                    A, acc, fig4, fig5, fig6 = models.wohls.main(
                        x1, y1, P, G_e, T, s1, s2)

                    st.write(r"Molar volumes: $q_1=%0.3e$, $q_2=%0.3e$" %
                             (q1, q2))
                    st.write(
                        r"$\frac{G^E/RT}{x_1q_1 + x_2q_2} = 2(%0.3f)z_1z_2$" %
                        A)
                    st.write(r"$R^2$ score = %0.3f" % acc)
                    st.write(fig4, fig5, fig6)
    except:
        pass

    st.sidebar.title("Note")
    st.sidebar.info(""" The saturation pressures are obtained from 
            [DDBST's database](http://ddbonline.ddbst.com/AntoineCalculation/AntoineCalculationCGI.exe?component=Ethanol)."""
                    )
    st.sidebar.info(""" The densities are obtained from 
                [DDBST's database](http://ddbonline.ddbst.de/DIPPR105DensityCalculation/DIPPR105CalculationCGI.exe?component=Diethyl%20ether)."""
                    )
    st.sidebar.info(
        "These models can only be used for binary isothermal vapor-liquid equilibrium data."
    )