# ROsmose tutorial : Pinch analysis and Utility integration

Theses classes will be given by Soline Corre (soline.corre@epfl.ch) and Meire Ellen Ribeiro Domingos (meire.ribeirodomingos@epfl.ch).

## Overview

Pinch analysis is a powerful method to obtain the minumum energy requirement (MER) of the system and to identify the penalizing heat exchangers. Here, we give an example based on the evaluated example processes for pinch analysis. We need to use a new tool called Rosmose, which is developed by IPESE aiming for process integration and optimization.


```{r, echo = FALSE, fig.cap="", out.width="30%", fig.align = 'center'}
knitr::include_graphics("Figures/rosmose.png")
```

**ROSMOSE** is a meta-language created to generate energetical optimization problems. This tool is based on the RMarkdown
ecosystem, and allows users to turn their work to a powerfull report or presentation. The idea of this ecosystem is to execute
computer code chunks embedded in Markdown to latter render output format such as PDF, HTML, LaTeX and so on.

**Rosmose** technology allows users to:

- define problems
- define energy technologies
- call external software
- solve optimization problems

The idea here was to create a meta-language also called *engines* to base the computer
code into energetic related jobs.

**ROSMOSE** is a package written in python and used with reticulate in the RMarkdown ecosystem.

In this section, you will use Rosmose to run optimizations and build composite curves. The guidelines to use Rosmose are available [here](https://ipese-internal.epfl.ch/rosmose/basics.html) or in the ROSMOSE tutorial uploaded on Moodle.


## How to run Rosmose

The Rosmose tool is installed in the folder `Rosmose`. In this folder, you can find the following directories and files.

- `frontend_MER.qmd` - the file setting up the assumptions for your project in case of Minimum Energy Requirement calculation.
- `frontend_TotalCost.qmd` - the file setting up the assumptions for your project in case of utility integration calculation.
- `model` - the folder including your process model and different energy technologies
- `results` - containing the results of your calculation

To obtain the report of the Rosmose optimization, choose one method from the following options:

- run the following command in your terminal: `quarto preview ./Rosmose/frontend_MER.qmd` OR `quarto preview ./Rosmose/frontend_TOtalCost.qmd`

- or open the file `Rosmose/frontend_MER.qmd`, click "preview" on the top-right (@fig-render).

A wonderful report will be generated, listing all the information you want to know.

```{r url-render, out.width='80%', fig.align='center', fig.cap='Where to find the render option'}
#| label: fig-render
knitr::include_graphics('Figures/render.png')
```


***More details will be given for Rosmose during the semester. You will be guided to go through the `Rosmose` folder.***


## How to adapt the results to your report

The results are saved in the `Rosmose/result/` file. You can use `r` or `python` chunks to access the information which are useful for your project reporting. 

```{r, eval = T , echo=FALSE}
library(jsonlite)
pfilename<-"Rosmose/result/methanol-1.json"
data <- fromJSON(pfilename, flatten=FALSE)
```


## How to plot your composite curves

The hot and cold composite curves of the process can be plotted using the following code chunk

**Hot and Cold Composite Curves**

```{r cc, eval = TRUE, message =F, echo=FALSE}
library ('purrr')
library('plotly')
display_cc <- function(time=1){
  graphs <- data$results$graph[[1]]
  graph <- graphs[[time]]
  graph <- graph[graph$plot_type == "cc",]$data[[1]]
  hcc <- graph[graph$title == "Hot streams",]$curve[[1]]
  ccc <- graph[graph$title == "Cold streams",]$curve[[1]]

  if (!is_empty(hcc) && !is_empty(ccc)){
    plot_ly() %>%
            add_trace(x=hcc$Q, y=hcc$T-273.15, mode = 'lines', line=list(color='red'), name='Hot Streams') %>%
            add_trace(x=ccc$Q, y=ccc$T-273.15, mode = 'lines', line=list(color='blue'),  name='Cold Streams') %>%
            layout(xaxis= list(title = "Heat load [kW]"),
                   yaxis= list(title = "Corrected Temperature [°C]"),
                   margin= list(l=50, r=0, b=40, t=40),
                   title = "Composite Curves"
            )


  } else {
    print(paste("There is no CC for timestep", time))
  }
}

display_cc()
```

The grand composite curve is plotted using a similar function


**Grand Composite Curve**

```{r gcc, eval = TRUE, message =F}
library ('purrr')
library('plotly')
display_gcc <- function(time=1){
  graphs <- data$results$graph[[1]]
  graph <- graphs[[time]]
  graph <- graph[graph$plot_type == "gcc",]$data[[1]]
  gcc <- graph$curve[[1]]

  if (!is_empty(gcc)){
    plot_ly() %>%

      add_trace(x=gcc$Q, y=gcc$T-273.15, mode = 'lines', line=list(color='green'), name='GCC') %>%
      layout(xaxis= list(title = "Heat load [kW]"),
             yaxis= list(title = "Corrected Temperature [°C]"),
             margin= list(l=50, r=50, b=40, t=40),
             title = "Grand Composite Curve"
            )
  } else {
    print(paste("There is no GCC for timestep", time))
  }
}

display_gcc()
```


Finally, once you start integrating utilities to close the energy balance of your system you would need to plot the integrated composite curve which shows both process and utility streams as follows. 


```{r, eval = T, echo=FALSE}

library(jsonlite)
pfilename<-"Rosmose/result/methanol-3.json"
data <- fromJSON(pfilename, flatten=FALSE)
totex<-data$results$KPIs$totalcost
capex<-data$results$KPIs$capex
opex<-data$results$KPIs$opex

costs<-data.frame(totex, opex, capex)
```


**Integrated Composite Curve**

```{r icc, message =F, echo=FALSE}
library ('purrr')
library('plotly')
display_icc <- function(time=1){
  graphs <- data$results$graph[[1]]
  graph <- graphs[[time]]
  graph <- graph[graph$plot_type == "icc.utilities",]$data[[1]]
  base <- graph[graph$title == "base",]$curve[[1]]
  utilities <- graph[graph$title == "utilities",]$curve[[1]]

  if (!is_empty(base) && !is_empty(utilities)){
    plot_ly() %>%
            add_trace(x=base$Q, y=base$T-273.15, mode = 'lines', line=list(color='red'),  name='base') %>%
            add_trace(x=utilities$Q, y=utilities$T-273.15, mode = 'lines', line=list(color='blue'),  name='utilities') %>%
            layout(xaxis= list(title = "Heat load [kW]"),
                   yaxis= list(title = "Corrected Temperature [°C]"),
                   margin= list(l=50, r=20, b=40, t=40),
                   yaxis2 = list(overlaying = "y", side = "right", title = 'Carnot factor 1-To/T [-]'),
                   title = "Integrated Composite Curve"
            )

  } else {
    print(paste("There is no ICC for timestep", time))
  }
}

display_icc()
```
# Utility integration

## Overview

Once the heat recovery is implemented, the energy balance of the process system is closed by converting energy resources like natural and electricity into useful heat, cold or refrigeration heat loads for the process.

This is alreay the last task of your project. Similar to heat recovery, you will use **Rosmose** to solve the problem.
Some tips of utility integration are given below:

## Requirement for this section

Two tutorials will be given on ROsmose and heat integration systems. 

## Questions

During theses tutorials, try to answer the following questions:

ROsmose tutorial 1:
1. Change the name in Aspen of at least 2 streams and 2 units and update the corresponding path in ROsmose.

*Answer 1:*

2. Change the power of the co-electrolysis system and record the changes for the heating demand and composite curves.

*Answer 2:*

ROsmose tutorial 2:
3. Solve the problem using methanol, cooling tower, furnace, market and refrigerator. Compare the performance with the existing example. 

*Answer 3:*

4. Change the temperature levels in the Steam Network file. Solve the frontend and retrieve the new integrated composite curve, while identifying the representative streams.

*Answer 4:*

## Recommandations for the project

For your project, you can proceed by the following steps :

1. Generating the Grand composite curve (GCC) of the process system and analysing the temperature levels and the amount for the heat deficits and surplus in the system. 
2. From the Grand composite curve analysis, a list of possible energy conversion technologies like boilers, steam or Rankine cycles, heat pumps, cooling water or refrigeration system will be established. The hot and cold streams as well as the resources consumption/production as well as the associated investment will be defined based on the estimated heat loads and temperatures from the process system GCC.
3. System **Key Performance Indicators (KPI)** will be defined to characterise :
     1. the operating expenditure (OPEX) in [CHF/year]: cost of the resources and the waste flows to supply the energy requirements of the process on a yearly basis.
     2. the capital expenditure (CAPEX) in [CHF]: the investment associated with energy conversion units
     3. the total expenditure (TOTEX) in [CHF/year]: total cost of the energy supply considering the annualised investment and operating cost
     3. the exergy losses in [kW] or in [kJ/$kg_{product}$] when converting hte resources to useful heat, electricity, cooling and refrigeration needs.
     4. the emissions  in [$kg_{CO_{2}}$/year] and the associated life cycle environmental impact in [$kg_{CO_{2}eq}$/year] of the energy supply.

