Source code for carbatpy.utils.property_eval_mixture

# -*- coding: utf-8 -*-
"""

A script to evaluate mixtures, in order to find some with vapor pressures
in some limits at given temperatures, together with the temperature glide.
The results are stored as figure, as csv and in a json-file(Input); all in the
given directory.


The csv output file structure is as follows:

* number of calculation
* the four mole fractions, species names are in the title
* index l: the properties for saturated vapor at the given low temperature
* index sup: the poperties at superheating at pressure p_l for a prescribed superheating
* index h: the properties for saturated vapor at the given high temperature
* index is: the properties for the isentropic state (sup ->p_h) at the given low temperature
* index is80: the properties for the isentropic effic. of 80 % (sup ->p_h) at the given low temperature
* index dew: the properties for the saturated liquid at p_h
* index mid: the properties at the mean enthalpy between q=0 and q=1 at p_h
* index thr: the properties for the isenthalpic throtteling from saturated liquid to p_l
* index hplT: the properties at T_l and p_h
* index thrlow: the properties for the isenthalpic throtteling from hplt ->p_l
* index bol: the properties for saturated liquid at the low pressure p_l
* p_ratio: the pressure ratio
* T_glide_h: the temperature glide at high pressure
* dv/v'': (ca.) the mean change in volume along throtteling relative to the specific volume of the vapor, this is a measure of how much work is 'lost' along throtteling
* dv/v''-b: similar volume ratio after subcooling to thrlow, answer the question: will subcooling reduce losses (strongly)?
* COP_is: What is the predicted COP for isentropic compression (losses along throtteling are seen here)

For each indexed state : T,p,h,v,s,q,u in SI units(mass base) are listed.


part of carbatpy

Created on Thu Oct 19 14:11:14 2023

@author: atakan
"""

import os
import json
import itertools
import matplotlib.pyplot as plt
import seaborn as sbn
import pandas as pd
import numpy as np
import carbatpy as cb






[docs] def eval_is_eff_roskosch(data, file_out): """ Evaluates fluid screening data combined with the Roskosch compressor model. This method processes the output of the Roskosch compressor model (h_aus, s_aus, h_e) for states calculated during screening. .. note:: The Roskosch model calculates in kJ, while carbatpy uses SI units (J). Enthalpies are converted accordingly. Based on the output enthalpy, the **COP_comp** is calculated. Mean temperatures are derived from enthalpies and entropies along the isobaric heat transfer for two cases: a) Throttling at quality = 0. b) Throttling after subcooling to T_low (identified by the suffix *_lowT*). With these mean temperatures, the COPs for two reversible cases are calculated: * *COP_rev80*: For a fixed isentropic efficiency of 80%. * *COP_rev_r*: For the specific Roskosch 'real' case. Finally, the (pseudo-)real COP is compared to the reversible COP to determine the second law efficiency (*eff_sec_law_r* and *eff_sec_law_80*). These efficiencies include compressor and throttling losses, but **no heat transfer**! References ---------- Roskosch piston compressor model: `http://dx.doi.org/10.1016/j.ijrefrig.2017.08.011 <http://dx.doi.org/10.1016/j.ijrefrig.2017.08.011>`_ Parameters ---------- data : pandas.DataFrame Combined DataFrame containing fluid screening data and Roskosch model outputs. file_out : str Path and filename where the resulting DataFrame will be stored. Returns ------- pandas.DataFrame The input DataFrame expanded by the calculated results. """ # mean low T, first with throttling at x=0, then with subcooling to T_low # index name for the latter _lowT new_data ={} new_data["T_mean_low"] = (data['spec_Enthalpy_sup'] - data['spec_Enthalpy_thr'] ) / (data['spec_Entropy_sup'] - data['spec_Entropy_thr']) new_data["T_mean_low_lowT"] = (data['spec_Enthalpy_sup'] - data['spec_Enthalpy_thrlow'] ) / (data['spec_Entropy_sup'] - data['spec_Entropy_thrlow']) try: # if the Roskosch-model data are in the dataFrame new_data["COP_comp"] = (data["h_aus"] * 1000 - data['spec_Enthalpy_dew']) /\ ((data["h_aus"] - data["h_e"]) * 1000) new_data["T_mean_high_is_r"] = ( data['h_aus'] * 1000 - data['spec_Enthalpy_dew'])/(data['s_aus'] - data['spec_Entropy_dew']) new_data["COP_rev_r"] = data["T_mean_high_is_r"] / (data["T_mean_high_is_r"] - new_data["T_mean_low"]) new_data["COP_rev_r_lowT"] = data["T_mean_high_is_r"] / (data["T_mean_high_is_r"] - new_data["T_mean_low_lowT"]) new_data["eff_sec_law_r"] = data["COP_comp"] / data["COP_rev_r"] new_data["eff_sec_law_r_lowT"] = data["COP_comp"] / data["COP_rev_r_lowT"] except: pass # values for isentropic efficiency of 80% and throttling at a quality of 0 new_data["T_mean_high_is80"] = (data['spec_Enthalpy_is80'] - data['spec_Enthalpy_dew']) \ / (data['spec_Entropy_is80'] - data['spec_Entropy_dew']) new_data["COP_rev80"] = new_data["T_mean_high_is80"] / (new_data["T_mean_high_is80"] - new_data["T_mean_low"]) new_data["eff_sec_law_80"] = data["COP_is80"] / new_data["COP_rev80"] # values for isentropic efficiency of 80% and throttling at the low T and high p new_data["T_mean_high_is80_lowT"] = (data['spec_Enthalpy_is80'] - data['spec_Enthalpy_hplt']) \ / (data['spec_Entropy_is80'] - data['spec_Entropy_hplt']) new_data["COP_rev80_lowT"] = new_data["T_mean_high_is80"] / (new_data["T_mean_high_is80"] - new_data["T_mean_low_lowT"]) new_data["eff_sec_law_80_lowT"] = data["COP_is80"] / new_data["COP_rev80_lowT"] new_data = pd.DataFrame.from_dict(new_data) all_data= pd.concat([data, new_data], axis=1) all_data.to_csv(file_out) return all_data
[docs] def get_fluid(data): """ Extracts fluid names and compositions from screening data. This method parses the column names of the provided DataFrame to identify the fluids and their respective mole fractions, formatted for REFPROP. Parameters ---------- data : pandas.DataFrame DataFrame from fluid screening containing mole fractions. The fluid names are extracted directly from the column headers. Returns ------- fluids : list of str The plain names of the identified fluids. fluid_col : list of str The actual column names (including the ``x_`` prefix). fluid_str : str The fluid composition string formatted for compatibility with REFPROP. """ fluids = [] fluid_col = [] col_names = data.columns for name in col_names: if name.find("x_") > -1: if name not in fluid_col: # no doubles fluids.append(name[2:]) fluid_col.append(name) fluid_str = "*".join(fluids) return fluids, fluid_col, fluid_str
[docs] def combine(filenames, filename_out="automatic"): """ Combine two data frames out of two or more files with same number of lines and fitting to each other. Can be used, when after fluid screening machine efficienceies, costs, etc. are calculated as post-processing. Can help in evaluation and plotting. Parameters ---------- filenames : list of strings all filenames (incl. directories), to be read. filename_out : string, optional Where to store the result. The default is "automatic". Then the first filename isxpanded vy "-combined". Raises ------ ValueError If tgere is a problem with the files. Returns ------- combined : pandas.dataFrame the combined dataFrame. """ all_frames = [] if filename_out == "automatic": fname_new = filenames[0].split(".") filename_out = fname_new[0]+"-combined0." + fname_new[1] try: for which in filenames: all_frames.append(pd.read_csv(which)) except Exception as excep: text = f"{which} vs. {os.getcwd()}, {excep}" raise ValueError(text) from excep combined = pd.concat(all_frames, axis=1) combined.to_csv(filename_out) return combined
[docs] def data_plot(filename, what, filename_out="automatic", fig_title=""): """ Plot a DataFrame from a file using a configuration dictionary. Imports a CSV file as a DataFrame and creates a plot based on the provided mapping for x, y, hue, and other aesthetic parameters. The resulting plot is saved to a file. Parameters ---------- filename : str Path to the CSV file containing the DataFrame to be imported. what : dict Mapping of plot aesthetics to DataFrame column names. Supported keys include ``"x"``, ``"y"``, ``"hue"``, ``"style"``, and ``"size"``. filename_out : str, optional The full path and filename where the plot will be saved. If ``"automatic"``, a name is generated based on the input. The default is "automatic". fig_title : str, optional The title of the figure. The default is "". Returns ------- bool True if the plot was created and saved successfully, False otherwise. """ try: dframe = pd.read_csv(filename) set(what).issubset(set(dframe.columns)) except Exception as excep: print(f"{what} not in columns!\n{excep}") return False # Plot figure, axes = plt.subplots( figsize=(10, 10), layout="constrained", nrows=1, ncols=1) fff = sbn.scatterplot(x=what["x"], y=what["y"], hue=what["hue"], size=what["size"], style=what["style"], data=dframe.round(3), ax=axes) sbn.move_legend(fff, "upper left", bbox_to_anchor=(1, 1)) axes.set_title(fig_title) if filename_out == "automatic": filename_out = filename.split(".")[0] + "-plot2.png" figure.savefig(filename_out) return True
[docs] def plot_cycle(filename, dataset): try: dframe = pd.read_csv(filename) except Exception as excep: print(f"Problem: {excep}") return False
[docs] def get_cycle_points(data, index): indices =range(7) sup_names = [ "_l" , "_sup" , "_h" , "_is" , "_is80" , "_dew" , "_mid" , "_thr" , "_hplt" , "_thrlow" , "_bol" ] n_points = len(sup_names) points =np.zeros((len(indices),n_points)) for outer, variable in enumerate(indices): property_name = cb.fprop._fl_properties_names[variable] names = [property_name + sup for sup in sup_names] points[outer,:] = data.loc[index, names] return points
if __name__ == "__main__":
[docs] FLUIDS_ACTUAL = ["Propane", "Isobutane", "Pentane", "Ethane"] # ,"Butane"] # ["DME", "Ethane", "Butane","CO2"]
TEMP_LOW = 288.00 TEMP_HIGH = 368.00 PRESSURE_LOW = 10E4 PRESSURE_HIGH = 22E5 DIRECTORY_NAME = cb._RESULTS_DIR + r"\optimal_hp_fluid\fluid_select_restricted" TEMPERATURE_LIMIT = True warn = mixture_search(FLUIDS_ACTUAL, [TEMP_LOW, TEMP_HIGH], [PRESSURE_LOW, PRESSURE_HIGH], DIRECTORY_NAME, resolution=21, temp_limit=TEMPERATURE_LIMIT, fig_title="std") ##################################################### COMPRESSOR_MODELL = False if COMPRESSOR_MODELL: directory = cb._CARBATPY_BASE_DIR directory += "\\tests\\test_files\\" filename1 = directory + r"test_data_ProEthPenBut\2024-02-06-16-51-ProEthPenBut.csv" filename2 = directory + \ r"test_data_ProEthPenBut\2024-02-06-16-51-ProEthPenBut-compressor-Roskosch.csv" combined_data = cb.utils.property_eval_mixture.combine([filename1, filename2], filename_out="automatic") ############################################## what_act = {"x": 'spec_Volume_sup', "y": 'COP_is80', "hue": 'T_glide_h', "size": 'p_ratio', 'style': 'Temperature_hplt'} SUCCESS = data_plot(filename1, what_act) ############################################ fluids_act, fluid_col_act, fluid_str_act = get_fluid(combined_data) ######################################### evaluated_data = eval_is_eff_roskosch(combined_data, directory+'evaluated.csv')