=Paper= {{Paper |id=Vol-3894/paper12 |storemode=property |title=Design and Optimization of Heat Exchangers Using Large Language Models |pdfUrl=https://ceur-ws.org/Vol-3894/paper12.pdf |volume=Vol-3894 |authors=Sandeep Mishra,Vishal Jadhav,Shirish Karande,Venkataramana Runkana |dblpUrl=https://dblp.org/rec/conf/kil/MishraJKR24 }} ==Design and Optimization of Heat Exchangers Using Large Language Models== https://ceur-ws.org/Vol-3894/paper12.pdf
                                Design and Optimization of Heat Exchangers Using Large
                                Language Models
                                Sandeep Mishra1,† , Vishal Jadhav1,† , Shirish Karande1 and Venkataramana Runkana1,*
                                1
                                    Tata Research Development and Design Centre, Pune, Maharashtra, India


                                                  Abstract
                                                  Heat exchangers (HEs) are essential in process industries for efficient thermal energy transfer. Their design and optimization
                                                  are crucial for improving energy efficiency, reducing costs, and ensuring reliable system performance. However, these tasks
                                                  are complex due to varying fluid properties, phase changes, and fouling. This study proposes the HxLLM framework, utilizing
                                                  Large Language Models (LLMs) to aid in the design and optimization of HEs. The framework identifies the mathematical
                                                  model for heat transfer in HEs, followed by retrieval-augmented generation (RAG) based code generation and correction. In
                                                  this study, a repository was created by extracting mathematical models from relevant literature along with common errors
                                                  observed in such tasks. These repositories, combined with carefully crafted prompts, were used to extract the mathematical
                                                  model and generate the corresponding code within this framework. We observed that LLMs can effectively identify and
                                                  generate initial code for mathematical models, though first responses often needed corrections. The RAG approach for code
                                                  correction significantly enhanced code accuracy. This study demonstrates that LLMs, with a RAG framework, can automate
                                                  and improve the design and optimization process of HEs, offering a promising tool for engineers and researchers to achieve
                                                  better efficiency and cost-effectiveness.

                                                  Keywords
                                                  Heat Exchangers, Design and Optimization, Large Language Models, Retrieval Augmented Generation



                                1. Introduction                                                                                       operates at optimal efficiency, meeting both economic
                                                                                                                                      and environmental goals [5] .
                                A heat exchanger is a device designed to transfer heat                                                   Designing and optimizing heat exchangers are chal-
                                between two or more fluids. It plays a critical role in lenging tasks, especially since these systems operate in
                                various industries such as chemical processing, power harsh environments such as power plants. Researchers
                                generation, HVAC systems, automotive, and renewable have explored various surrogate modeling approaches, in-
                                energy [1]. The design and optimization of heat ex- cluding machine learning [6, 7, 8, 9, 10] and deep learning
                                changers are vital for enhancing energy efficiency, re- [11, 12, 13, 14, 15, 16], to accelerate this process (further
                                ducing operational costs, and minimizing environmental details on these approaches can be found in appendix 6).
                                impact. Effective heat exchanger design ensures the ef- While these methods have demonstrated improvements
                                ficient transfer of thermal energy, leading to significant in design and optimization, implementing them for new
                                energy savings and reduced greenhouse gas emissions [2]. designs requires engineers to undergo extensive training.
                                Currently, methods such as the Log-Mean Temperature Consequently, applying these approaches to new design
                                Difference (LMTD), Effectiveness-Number of Transfer problems can be time-consuming.
                                Units (𝜖-NTU), Computational Fluid Dynamics (CFD) [3],                                                   Recently, large language models (LLMs) have shown
                                heuristic search techniques like Genetic Algorithms and significant potential in design and optimization within
                                artificial intelligence (AI) and machine learning(ML) al- the engineering domain. Pluhacek et al. [17] used LLMs
                                gorithms based techniques like artificial neural networks like GPT-4 to create new hybrid swarm intelligence opti-
                                (ANNs) are used for the design and optimization of heat mization algorithms, highlighting their innovative role
                                exchangers [4, 5]. The typical steps in design and opti- in tackling optimization challenges. Ma et al. [18] found
                                mization of heat exchanger involve problem definition, that LLM-generated design solutions were more feasible
                                selection of design method, initial design, detailed anal- and useful than crowdsourced ones, enhancing design
                                ysis, optimization, validation and testing, iteration, and quality through advanced natural language processing.
                                implementation. These steps ensure the heat exchanger Sabbatella et al., [19] focused on prompt optimization
                                                                                                                                      to improve LLM performance, emphasizing the impor-
                                KiL’24: Workshop on Knowledge-infused Learning co-located with
                                                                                                                                      tance of fine-tuning. Ma et al,[20] introduced LLaMoCo,
                                30th ACM KDD Conference, August 26, 2024, Barcelona, Spain
                                *
                                  Corresponding author.                                                                               a framework that fine-tunes LLMs for optimization tasks,
                                †
                                  These authors contributed equally.                                                                  showing superior performance compared to other mod-
                                $ sandeepm.mishra@tcs.com (S. Mishra); vi.suja@tcs.com                                                els. Yang et al. [21] frame LLMs as optimizers, using
                                (V. Jadhav); shirish.karande@tcs.com (S. Karande);                                                    them to generate candidate solutions from natural lan-
                                venkat.runkana@tcs.com (V. Runkana)                                                                   guage prompts in an iterative loop. Liu et al.[22] sur-
                                         © 2024 Copyright for this paper by its authors. Use permitted under Creative Commons License
                                            Attribution 4.0 International (CC BY 4.0).




                                                                                                              1




CEUR
                  ceur-ws.org
Workshop      ISSN 1613-0073
Proceedings
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                       1–22



veyed ChatGPT-related research, highlighting LLM ap-             2. Methodology
plications in education, medicine, and physics, driven
by innovations in pre-training and fine-tuning. Kashefi          Designing and optimizing a heat exchanger typically in-
and Mukerji [23] directly explore using ChatGPT [24]             volves the following steps: defining the problem, select-
to generate code for numerical algorithms, with promis-          ing a design method, optimizing, validating and testing,
ing results. Yao et al[25] introduces frameworks like the        iterating, and implementing. The design method selec-
"Tree of Thoughts" enable LLMs to explore multiple rea-          tion includes the mathematical formulation describing
soning paths and make global decisions for challenging           heat transfer, while optimization involves finding the
tasks. Wang et al.[26] propose an interactive "chain of          optimal design parameters by evaluating various pairs
repairing" approach where LLM agents work together               of heat transfer metrics and their corresponding design
to iteratively debug and improve generated code. Xu et           parameters.
al.[27] proposes integrating information retrieval into             To mimic real-world scenarios, this study relies on
the LLM reasoning chain for knowledge-intensive tasks,           available literature on heat exchanger design and opti-
enabling the model to dynamically incorporate relevant           mization. Initially, some literature texts were provided
information and modify its reasoning trajectory. Addi-           as context to the LLM model with prompts to extract
tionally, Li and Mellou [28] introduce OptiGuide, a frame-       mathematical model summaries. These summaries were
work utilizing LLMs to bridge the gap between supply             then stored in the mathematical model summary reposi-
chain automation and human comprehension. Chen et                tory. For each of these mathematical models, an expert
al. [29] present OptiChat, a system equipped with a chat-        wrote the Python script to evaluate the mathematical
bot GUI for diagnosing infeasible optimization models            model equations. Also, the frequent errors were stored
using natural language interactions. Liu et al. [30] in-         in the code error repository. The details of the mathe-
troduce CodeMind, a framework designed to evaluate               matical model repository and code error repository are
the code reasoning abilities of LLMs. CodeMind sup-              as follows:
ports three code reasoning tasks and shows that while
LLMs can follow control flow constructs and explain how          Mathematical Model Repository Our repository, a
inputs evolve to output for simple programs, their per-          CSV file, currently contains over 115 entries, organized
formance drops for more complex code. Also Ni and                into three columns: ID, Summary, and Code. The Sum-
Buehler [31] demonstrate how teams of interacting LLM            mary section comprises summaries of articles, which
agents can autonomously collaborate to solve mechanics           were generated using prompts (Table 1) for research arti-
problems, write code, and incorporate domain knowl-              cles. After creating the code for each mathematical model,
edge. Ahmadi Teshnizi et al.[32] propose OptiMUS, an             we processed it through an error correction framework
LLM-based agent for formulating and solving mixed in-            to ensure its accuracy. Once refined, the code was added
teger linear programming (MILP) problems from natural            to the Code section corresponding to its respective sum-
language descriptions. In summary, above studies have            mary.
shown their effectiveness of LLMs in creating new al-
gorithms, enhancing design solutions, improving opti-            Code Error Repository This repository is a collection
mization tasks, and generating code. Various frameworks          of complex errors that the LLM had difficulty solving,
and approaches, such as LLaMoCo, OptiGuide, and Op-              documented as metadata. Each entry includes the error
tiChat, demonstrate LLMs’ capabilities in tackling com-          description and its solution, provided as the page content
plex problems, including optimization, code reasoning,           of a document object.
and collaborative tasks.                                            We propose the HxLLM framework for LLM-assisted
   Inspired by these developments, this study explores           design and optimization of heat exchangers. It has three
the application of LLMs for automating the design and            main components: mathematical model identification,
optimization of heat exchangers with HxLLM framework.            code retrieval for the mathematical model, and code gen-
The primary objective is to develop a system that can gen-       eration and correction. In subsequent sections, we dis-
erate mathematical models and optimization algorithms            cuss the components of the HxLLM framework and how
based on user-input, leveraging the capabilities of LLMs         it utilizes the mathematical model repository and code
to determine optimal parameter values and perform cost           error repository.
optimization. By extracting relevant information from
research articles, LLMs could potentially generate mod-
els and propose optimized designs through an iterative,
                                                                 2.1. Mathematical model identification
interactive process, reducing the manual effort required.        This component extracts the mathematical model from
                                                                 the user input. User input can also include a research
                                                                 article that the user might want to use for a new design.
                                                                 Figure 1 (a) shows the mathematical model identification



                                                             2
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                             1–22



Table 1                                                             2.2. Code retrieval for mathematical
Prompt for extracting the mathematical model summary from                model
user input
                                                                    The highest similarity score obtained with mathemati-
  
  {raw_text}
                                                                    cal model extraction component, is then compared with
                                                            threshold similarity score. In this case, if the similarity
  Please carefully read through the mathematical model              score is greater than 75%, the summary corresponding
  section of the paper above. Identify and list all the             to the highest similarity score is extracted. Subsequently,
  unique equations that are used to construct the model.            we retrieve the code associated with that summary, which
  For each equation you find:                                       serves as our sample base code for further processing.
  - Give it a specific, descriptive name based on what              The details of this step are illustrated in Fig. 1 (b). If the
  it represents or calculates. For example, if there is an          similarity score is less than 75%,then the paper is new
  equation for "tube side heat transfer coefficient", name it       and does not match any summary in our repository, and
  something like "Tube side heat transfer coefficient (ht)".
                                                                    an alternative approach is employed. This approach pairs
  - Briefly describe how to calculate the equation based
                                                                    a most similar research article mathematical model with
  on the information in the paper.
  Avoid using generic labels like "Equation ()" for the             its corresponding code and, when presented with a new
  names. Also avoid using phrases like "Calculated using            research article, uses a sequential prompting technique
  equation ()" in your descriptions. Instead, just provide a        to produce the desired output.This essentially represents
  general description of how each equation is calculated.           a few-shot prompting example, as illustrated in Fig. 2
  Output your final list of named and described equations
  inside tags.
                                                                    2.3. Code generation using LLM
                                                                    The sample base code obtained from previous compo-
component. The user provides scientific text or a research          nent, along with chain of thought prompting technique,
article (in PDF file format), which is then processed by the        enables the LLM to generate new code through sequen-
LLM. The LLM is prompted (see table 1 for the prompt                tial prompting (see prompts in table 2 and table 3). In
provided to the LLM) to summarize the mathematical                  this component, we created the error database for errors
model described in the article, focusing solely on its de-          that were encountered while creating the code for each
scription instead of detailed equations. This approach              mathematical model (see Fig. 1(c)). It contains a list of
was chosen due to challenges with accurately parsing                potential errors encountered in mathematical models for
and reading equations (mathematical expressions present             heat exchangers. Code generated by LLM is executed,
in the article) using our current PyPDF reader for text             and if the execution results in an error , then RAG based
extraction from the research article PDF file.                      technique is used to get similar error and its resolution
                                                                    . Then again the prompt with similar error and its res-
                                                                    olution is given to the LLM (see prompt in table 4 and
                                                                    table prompt 5). This iteration continues until specific
                                                                    number of times (in this case 3) or terminates early if
                                                                    the execution is successful. In case code exits with error
                                                                    then human provides the resolution of the error and then
                                                                    once again the code generation loop continues.

                                                                    2.4. Code Generation for Optimization
                                                                         Algorithm
Figure 1: HxLLM Framework
                                                        The final stage in our methodology involves generating
                                                        the code for the optimization algorithm, following a sim-
                                                        ilar approach to the code generation component. We
   Further, the generated mathematical model is com- start by providing a sequential prompt to generate the
pared with mathematical models available in mathemati- initial code. This code then goes through an iterative
cal model summary database. Using TF-IDF vectorizer co- correction process to identify and fix any complex errors,
sine similarity score is evaluated between mathematical leveraging suggestions from the RAG system.Here are
model summary generated by LLM and model summary the two prompts(Table:6,Table:7) that we have used for
in mathematical model summary repository.               generation of final optimisation algorithm.
                                                           After utilizing the Chain of Thought prompting to
                                                        generate the code for the optimization algorithm using




                                                                3
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                               1–22



Table 2                                                            Table 3
Prompt for code generation, by detecting which part of base        Prompt for Generating New Code for Mathematical Model
code required change
                                                                     
  Your task is to recreate the Python code for the specified         {a1}
  research paper. The goal is to generate code that can              
  be directly copied and pasted for execution on a user’s            And here are the modified lines of code:
  system. You will be provided with a series of prompts to           
  guide you through the process.                                     {b}
                                                              
  {a}                                                                The specific lines or code blocks that need to be replaced
                                                             from the modified code into the original code are:
  First, carefully study the mathematical models and equa-           {b}
  tions provided in the paper above. Pay close attention             Please carefully examine the original code and modi-
  to the details and notations used.                                 fied code provided. Your task is to surgically replace the
                                                        lines/blocks specified in modified code from the into the appropriate locations in the                                                      nal_code>.
  Next, compare the sample code provided above with                  When doing the replacements, make sure the modified
  the original paper. Identify which functions need to be            code integrates properly with the surrounding original
  changed based on the equations and models described                code. Fix any mismatched variable names, indentation
  in the paper.                                                      issues, or other small inconsistencies introduced by in-
  When writing the code, make sure to write out the full             serting the modified code.
  formula. As an example, for equation (3) instead of sim-           Once you have an updated version of the code with
  ply representing it as a comment like # equation (3). This         the changes incorporated, your next step is to create a
  will ensure clarity and completeness.                              unified linking function. This function should contain all
  To optimize your work, only write the equations that               the key parameters used throughout the different code
  are different and need to be changed. If a function is             blocks. The goal is to have a single master function that
  already the same as in the original paper, there’s no need         can be called with all the necessary parameters, which
  to rewrite it.                                                     will then appropriately call the other functions and code
  Remember, it’s crucial that any generated results are              blocks in the proper sequence to produce the end result.
  complete and accurate. Double-check your work to en-               When you have completed the unified linking function,
  sure the code aligns with the paper’s specifications.              test the code to make sure it runs without any errors.
  Please provide your response inside tags.                    Debug if necessary.
                                                               Finally, provide the full corrected code, from first line to
  Your generated code goes here.                                     last line, inside tags. Format it cleanly
                                                              so that I can directly copy and paste your code and run
  You don’t need to provide the entire code in one go. I             it without issues.
  will provide more prompts in a sequence to guide you
  through the process. Let’s work together to recreate the
  code accurately and efficiently.                      taining mathematical models from multiple papers to
                                                        check for similarity. If a match is found, we retrieve the
                                                        base code as a reference for the LLM to generate the
the previously created mathematical model as the objec- mathematical model described in the paper. To ensure
tive function, we then pass this code through our final the accuracy of the generated code, we incorporate a
code correction framework. This framework employs the code correction framework along with RAG techniques.
same RAG techniques to produce the correct final code. If the base code is not present, we use few-shot examples
                                                        to generate the mathematical model and subsequently
2.5. HxLLM Workflow                                     the optimization model.
In summary, HxLLM framework takes user input in the
form of research article PDF and generates the code for            3. Results and Discussion
mathematical model and optimization algorithm men-
tioned in the research article. The entire workflow is             In this study, we used the Anthropic Claude 3 Opus model
presented in Fig, 2. Initially, the workflow processes a           as the LLM, and several research articles, including [33]
research article focused primarily on heat exchanger mod-          and [34], were utilized as user input.
els and their cost optimization. Using LLM and prompt                 We applied HxLLM framework to 115 research articles.
engineering, we identify the mathematical model. We                In the following subsections, we describe representative
then compare the provided article with a database con-             results of our framework for research articles with similar



                                                               4
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                            1–22



Table 4                                                          Table 6
Prompt for Error Correction                                      Prompt - 1 for code generation for final optimisation algorithm
  Here is a Python code that encountered an error when             You will be optimizing the mathematical model of a heat
  run:                                                             exchanger based on provided code and an optimization
                                                             algorithm from a research paper.
  {code}                                                           Here is the code for the heat exchanger model:
                                                            
  The error message was:                                           {Code}
  {error_message}                                                  
  Please carefully read the error message and identify             And here is the paper having the optimization algorithm:
  which line number and what part of the code is causing           
  the error.                                                       {raw_text}
  Then, make the necessary changes to fix the code so              
  that it will run without any errors.                             Please carefully read through the code and paper to
  Provide the full corrected code inside tags.         understand the heat exchanger model and the proposed
  The pattern should be Corrected version              optimization approach.
  of the code . Double check it so that it            After reviewing the materials, please identify the tar-
  should not contain any type of other errors and should           get/design variables that the paper aims to optimize,
  return results.                                                  along with any specified limits on those variables. List
                                                                   out each variable and its limits (if given).
                                                                   Next, find the unified linking function described in the
Table 5                                                            paper. Show how to incorporate this linking function
Prompt for Error Correction with RAG                               into the optimization algorithm.
  Here is a Python code that encountered an error when             Then, write out the full code that performs the optimiza-
  run:                                                             tion of the heat exchanger model. Use the target/design
                                                             variables, limits, and unified linking function you identi-
  {code}                                                           fied from the paper. Aim to closely follow the optimiza-
                                                            tion approach from the paper while integrating it with
  The error message was:                                           the existing heat exchanger model code.
  {error_message}                                                  Before outputting the final code, take a moment to dou-
  The solution you can refer to solve this problem is:             ble check that your code follows the optimization algo-
  {Solution}                                                       rithm correctly and that you have used the right vari-
  Please carefully read the error message and identify             ables and limits. Think through the optimization process
  which line number and what part of the code is causing           step-by-step to verify the logic.
  the error.                                                       Finally, output the complete optimized code inside
                                                         tags. Also output the final opti-
  Think step-by-step about:                                        mized values of the target/design variables inside tags.
  2. Which line of code it references                              Remember, the goal is to implement the paper’s opti-
  3. How the provided solution addresses the issue                 mization approach to find optimal values for the heat
                                                        exchanger model’s design variables. Let me know if you
  Then, make the necessary changes to fix the code so              have any other questions!
  that it will run without any errors.
  Provide the full corrected code inside tags.
                                                             3.1. Model Extraction and Code
                                                                  Generation for Similar Research
mathematical models present in the mathematical model
repository, as well as for research articles without similar
                                                                  Articles
models in the repository. Finally, we discuss optimization       3.1.1. Mathematical Model Extraction
algorithm code generation. .
                                                                 As mentioned before, it is expected that user will provide
                                                                 the scientific text containing the mathematical model for
                                                                 heat exchanger design. This text is passed as context
                                                                 along with prompt (mentioned in table 1 to LLM for
                                                                 extraction of the mathematical model and its parameters.
                                                                 For this study, we have considered the research article
                                                                 by [33] as the scientific text example. The mathematical
                                                                 model extracted by LLM for this research article is given




                                                             5
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                              1–22



Table 7                                                           Table 8
Prompt – 2 for code generation for final optimisation algo-       LLM-Generated Summary for User-Provided Article
rithm
                                                                    1. Tube side heat transfer coefficient for laminar flow
  You will be combining two code snippets, one for a math-          (ht_laminar): Calculated using the tube inside diameter,
  ematical model and another for an optimization algo-              thermal conductivity, tube side Reynolds number, tube
  rithm, to produce a final output that can be copy-pasted          side Prandtl number, and tube length.
  and run.                                                          2. Tube side heat transfer coefficient for transition flow
  Here is the code for the mathematical model:                      (ht_transition): Calculated using the tube inside diam-
                                                             eter, thermal conductivity, tube side Reynolds number,
  {Code}                                                            tube side Prandtl number, tube length, and the Darcy
                                                            friction factor.
  And here is the code for the optimization algorithm:              3. Tube side heat transfer coefficient for turbulent flow
                                                             (ht_turbulent): Calculated using the tube outside diam-
  {d}                                                               eter, thermal conductivity, tube side Reynolds number,
                                                            tube side Prandtl number, tube side dynamic viscosity,
  Please carefully review both code snippets and think              and wall dynamic viscosity.
  about how they should be combined to produce a work-              4. Darcy friction factor (ft): Calculated using the tube
  ing final output. Write out your thought process for              side Reynolds number.
  combining the code inside tags.                       5. Tube side Reynolds number (Ret): Calculated using
                                                        the tube side fluid density, tube side flow velocity, tube
                                                       inside diameter, and tube side dynamic viscosity.
  Once you have determined the best way to combine                  6. Tube side flow velocity (vt): Calculated using the tube
  the code snippets, please provide the final combined              side mass flow rate, tube inside diameter, tube side fluid
  code that can be copy-pasted and run inside tags.                                                  7. Number of tubes (Nt): Calculated approximately using
                                                     the shell inside diameter, tube outside diameter, number
                                                    of tube passes, and coefficients that depend on the flow
                                                                    arrangement and number of passes.
                                                                    8. Tube side Prandtl number (Prt): Calculated using the
                                                                    tube side dynamic viscosity, tube side specific heat, and
                                                                    tube side thermal conductivity.
                                                                    9. Shell side heat transfer coefficient (hs): Calculated us-
                                                                    ing the shell equivalent diameter, thermal conductivity,
                                                                    shell side Reynolds number, shell side Prandtl number,
                                                                    shell side dynamic viscosity, and wall dynamic viscosity.
                                                                    ...continued...


                                                          compared to other approaches. Hence, TF-IDF vectorizer
                                                          was used to identify the similar mathematical model with
                                                          cosine similarity as metric for the similarity. Threshold of
Figure 2: HxLLM Framework Workflow                        75% for the similarity metric (through trial and error) was
                                                          selected to decide if the mathematical model extracted
                                                          by LLM is similar to any of the model present in the
in table 8.                                               repository.
                                                             Output of the TF-IDF vectorizer based retrieval for
3.1.2. Code Retrieval for Mathematical Model              mathematical   model similar to the extracted mathemati-
                                                          cal model is shown in table:9. It can be seen that identi-
Post extraction of the mathematical model summary, we fied similar mathematical model has similarity score of
identify the similar mathematical model present in our 0.924 as the elements like, tube side heat transfer coeffi-
mathematical model repository. We experimented with cient, friction factor etc are common in both extracted
several retrieval approaches like retrieval using LLM, mathematical model (see table 8) and identified similar
parent document retriever and RAG fusion with query mathematical model (see table 9).
duplication and reformulation along with TF-IDF based
retrieval method, to identify the similar mathematical 3.1.3. Code generation and Correction
model from repository. However, we observed that TF-
IDF based retrieval was providing the satisfactory result Post identifying the similar mathematical model from
                                                          the repository, the python code corresponding to similar



                                                              6
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                           1–22



Table 9                                                             the equations present within the original codebase that
Output of TF-IDF vectorizer method showing the similarity           necessitate alterations. It details which segments in the
scores and closest summary                                          base code should be modified to ensure the accuracy
  Output of TF-IDF vectorizer method                                and logical integrity of extracted mathematical model.
  Closest summary index: 11                                         Following this, we provided the next prompt (Table:3),
  Similarity score: 0.924                                           instructing the model to include these changes in the
  Closest summary:                                                  base code and rewrite it coherently. The generated code
  1. Heat transfer area (A): Calculated using the heat              for this step is given in appendix 5.2.
  transfer rate, overall heat transfer coefficient, LMTD               To ensure that, the generated code is accurate and runs
  correction factor, and logarithmic mean temperature               without any errors, this code was passed to the code cor-
  difference.                                                       rection framework. The errors encountered during the
  2. Heat transfer rate (Q): Determined from an energy              execution of the code, are presented in figure 3. Simple
  balance using the mass flow rates and specific heats of
                                                                    errors (not present in the error repository) was resolved
  the hot and cold fluids along with their inlet and outlet
  temperatures.
                                                                    by prompting (see table 4) LLM and errors which was not
  3. Tube side flow velocity (Vi): Calculated from the              so obvious for LLM (listed in error repository) were re-
  tube side mass flow rate, fluid density, number of tubes,         solved through RAG based approach with prompt (given
  number of tube passes, and tube inner diameter.                   in table 5). It may happen, though, that errors may still
  4. Number of tubes (NT): Estimated using an empirical             not be resolved; in that case, the error was resolved man-
  correlation based on the shell diameter, tube outer di-           ually, and the solution for the error was added to the
  ameter, and coefficients that depend on the tube layout           error repository for further reference by LLM.
  and number of passes.                                                By learning from past errors in this way, the RAG
  5. Tube side Reynolds number (Re): Calculated from                system can iteratively improve the quality and accuracy
  the tube side flow velocity, tube inner diameter, and
                                                                    of the code it produces. The final result of the error-free
  kinematic viscosity of the tube side fluid.
                                                                    mathematical code generated by the LLM is provided in
  ...continued...
                                                                    (Appendix:5.2).

Table 10
List of functions to be updated to match key equations from
the original paper
  Block-2 function calculate_fs() - Replace with cor-
  rect equation for friction factor fs from the paper.
  Block-7      function     Tube_side_heat_transfer
  _coefficient() - Replace ht equations with correct
  ones from paper.
  Block-12 function Shell_Side_heat_transfer
  _coefficient() - Replace hs equation with correct
                                                                    Figure 3: Error Correction Framework Response
  one from paper.
  Block-13 function for overall heat transfer coefficient U -
  Replace with equation (2) from paper.
  Block-15 function Correction_factor() - Replace
  with correct F equation from paper.                               3.2. Model Extraction and Code
  Block-19 function calculate_Cod() - Verify discount-                   Generation for Non-Similar Research
  ing equation matches paper.                                            Articles
  Block-20 function Calculate_Total_Cost() - Verify
  capital cost equation matches paper.                              In the previous section 3.1, we described the steps for
                                                                    user input for which we had similar mathematical model.
                                                                    However, in practical scenario user may come up with
mathematical model was taken as base code (see appendix             models that may not be similar to model available in
5.1) for further processing. Since our aim is to get the            mathematical model repository. In such scenario, we
code for extracted mathematical model, we first identify            adopted the different steps for code generation of mathe-
the changes required in base code by passing the base               matical models. These steps are described below:
code as context with prompt mentioned in table 2 to LLM
and ask LLM to identify the changes required in base                3.2.1. Mathematical Model Extraction
code. The changes suggested by the LLM are given in
table 10.                                                           We have selected the research article [34], for which sim-
   The changes mentioned in LLM response illustrates                ilar mathematical model is not available in the model




                                                                7
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                            1–22



Table 11                                                          Table 12
Summary generated by LLM for dissimilar paper                     Mathematical code generation prompt for dissimilar paper
  Shear stress constraint(𝐶1(𝑥)): Ensures the shear stress         You will be recreating the Python code for a specified re-
  is less than the maximum allowable shear stress 𝑆 , cal-         search paper. The goal is to generate code that can be
  culated using the maximum load 𝑃max , coil diameter 𝐷,           directly copied and pasted for execution. I will provide you
  and wire diameter 𝑑.                                             with a series of prompts to guide you through the process.
  Free length constraint(𝐶2(𝑥)): Ensures the free length           First, here is a sample paper for your reference:
  is greater than the minimum required length, calculated          
  using the deflection 𝛿 , number of coils 𝑛, and wire di-         {SAMPLE_PAPER}
  ameter 𝑑.                                                        
  Minimum wire diameter constraint(𝐶3(𝑥)): Ensures the             And here is the sample code associated with the mathemat-
  wire diameter is greater than the minimum allowable              ical model from that paper:
  wire diameter 𝑑min .                                             
  Continued...                                                     {SAMPLE_CODE}
                                                                   
                                                                   Note that the sample code may be entirely different from the
repository. The provided paper mainly discusses the                paper you will be working with. It is only provided to give
application of Rao algorithms to optimize mechanical               you an idea of how to proceed in creating the code for the
                                                                   mathematical model of the given paper. The mathematical
system component designs, assessing their comparative
                                                                   expressions and logic in your paper may be different.
effectiveness against established methods in addressing            Now, here is the paper you will be recreating the code for:
complex constraints and mixed-type variables. However,             
our database contains papers focused on the cost opti-             {PAPER}
mization of heat exchangers. We use the prompt (given              
in table 1) to generate the mathematical model summary.            Please carefully study the mathematical models and equa-
LLM generated summary is given in table 11.                        tions provided in this paper.
                                                                   Next, write out the equations for all the formulas in the
                                                                   paper as Python functions, similar to how it was done in
3.2.2. Code Retrieval for Mathematical Model
                                                                   the sample code. First, you will need to figure out the logic
The mathematical model summary (in table 11) when                  and all the formulas. Then, write out each formula as a
compared using TF-IDF vectorizer based retriever, we               Python function.
found that, similarity index was 0.512, indicating that            If there are no mathematical models or formulas given in
no mathematical model closely matches the generated                the paper, simply state "No mathematical models or
                                                                   formulas are present in this paper."
mathematical model summary. Hence, the sample code
                                                                   When writing the code, make sure to write out the full
was taken as reference base code for the step of code              formula for clarity. For example, instead of representing
generation.                                                        equation (3) as a comment like # equation (3), write
                                                                   out the entire equation. This will ensure completeness.
3.2.3. Code generation and Correction                              It’s crucial that any generated results are complete and
                                                                   accurate. Double-check your work to ensure the code aligns
Since we are not using the base code which is similar to           with the paper’s specifications.
the mathematical model, in this case we ask the LLM to             Please provide your generated code inside  tags like
generate the code from scratch with sample code using              this:
few-shot example prompting approach (Table:12). We                 
provided a closely matched reference paper, the math-              Your generated code goes here.
ematical model related to the paper, and associated it             
with the prompt in a way that the model learns from                You don’t need to provide the entire code all at once. I will
the example how to build the mathematical model for an             provide more prompts in a sequence to guide you through
                                                                   the process. Let’s work together to recreate the code accu-
optimization algorithm problem. The result generated
                                                                   rately and efficiently.
with this approach is given in appendix 5.3.
   This code demonstrates that Claude 3 Opus is a very ca-
pable model, able to learn from examples and write code
                                                                  3.3. Optimisation code generation
in a manner required for our case. However, the code
generated by the LLM needs to be executed to ensure               Once the mathematical model code is generated, it can
correctness. For this, we sent the code to our code correc-       be integrated with optimization algorithm for obtain-
tion framework (as described in sub section 3.1.3), and           ing the configuration with optimal cost. It is achieved
the output of that framework after multiple correction            with two steps, first code generation for optimization
iterations, is given in appendix:5.4.                             algorithm and second integration of mathematical model




                                                              8
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                         1–22



with optimization algorithm. The first step is performed           ysis. Also, the current framework relies heavily on the
in this study, by providing the user provided research             user input for the mathematical model, its parameters
article as context to LLM with prompt (Table:6), to gen-           and optimization algorithm to be used. To reduce this
erate the code for optimization. Here we have illustrated          dependency on user input, the external data repositories
the output of this approach for research article by Pa-            (like the mathematical model repository and code error
tel and Rao [33]. This article [33] describes the use of           repository mentioned in this framework) for material
PSO (Particle Swarm Optimization) techniques, where                properties, optimization methodologies, program synthe-
the target variables are three design variables: shell in-         sis, domain specific information etc. can be integrated in
ternal diameter, outer tube diameter, and baffle spacing.          this framework to obtain the reliable and comprehensive
These variables are considered for optimization. As per            framework for design and optimization across different
the prompt, the LLM correctly identified the design vari-          design problems. Developing such framework, is the
ables along with their limits. It also accurately replicated       future goal of the present authors.
the PSO algorithm as described in the paper to optimize
the cost function and determine the values of these tar-
get variables. The code generated by LLM is given in               4. Conclusion
appendix:5.5.
                                                           This study introduced the HxLLM framework, leveraging
   In next step, prompt (given in table7), that instructs
                                                           Large Language Models (LLMs) to automate the design
LLM to combine both the mathematical model and the op-
                                                           and optimization of heat exchangers (HEs). Our approach
timization code to produce the final code for optimization.
                                                           integrated mathematical model extraction, code genera-
This combined code was then passed through the code
                                                           tion, and error correction using a RAG framework. The
correction framework. The output of code correction
                                                           LLMs effectively identified and generated initial code for
framework is presented in appendix:5.6.
                                                           the mathematical models, although initial responses of-
   The LLM performed remarkably well in identifying
                                                           ten required corrections. Our results demonstrated that
and writing most of the code logic accurately. However,
                                                           LLMs, when combined with RAG, offer a promising tool
the final answer did not exactly match the results de-
                                                           for automating the design and optimization processes of
scribed in the paper, as some of the parameter values
                                                           HEs. This can lead to increased energy efficiency and
were guessed by LLM since it was not present in the ar-
                                                           reduced costs in the process industry. However, the study
ticle provided by user. Also the code generated by LLM
                                                           also highlighted the limitations of current LLM capabili-
relied on the pdf text, which did not have accurate infor-
                                                           ties, particularly in handling diverse mathematical mod-
mation of mathematical model equation due to limitation
                                                           els and optimizing complex designs without substantial
of pdf text parsing.
                                                           human input. Future work should focus on enhancing
                                                           the LLM’s ability to parse complex information from var-
3.4. Limitations and Future Work                           ious document formats and reducing reliance on user
Research articles are often in pdf format, and parsing input by integrating extensive external data repositories.
these pdfs to text can result in loss of equation informa- Additionally, incorporating agent-based workflows may
tion, table or graph image information. In present study, further improve the code generation process. These ad-
we have ignored this loss of information. However, the vancements will help create a more comprehensive and
concrete methodology to parse the information in pdf reliable framework for designing and optimizing diverse
files or any other similar files which contains multiple engineering systems.
type of information needs to formulated for better com-
prehension of context by LLMs. Combination of meth- References
ods like, use of neural networks [35], vision transformer
based models [36] or LLM based models [37, 38] can           [1] J. B. B. Rao, V. R. Raju,          Numerical and
be explored further for overcoming this limitation. The           heat transfer analysis of shell and tube heat ex-
code generation capability of the LLMs have improved              changer with circular and elliptical tubes, In-
in recent times, however LLMs require human inputs                ternational Journal of Mechanical and Materials
(prompts) code generation of complete design and op-              Engineering 11 (2016) 2198–2791. URL: https://
timization of heat exchangers and can not be achieved             doi.org/10.1186/s40712-016-0059-x. doi:10.1186/
in one shot. This further can be improved with agent              s40712-016-0059-x.
based workflows for better code generation. Also, the cur- [2] S. Jung, H. Jung, Y. Ahn,              Optimal eco-
rent benchmark studies does not consider requirements             nomic–environmental design of heat exchanger
of such design and optimization workflows and can’t be            network in naphtha cracking center considering
used for evaluating the framework proposed in this study          fuel type and co2 emissions, Energies 15 (2022).
and human evaluation approach was selected for anal-



                                                               9
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                   1–22



     URL: https://www.mdpi.com/1996-1073/15/24/9538.               Air Pre-Heaters Through Deep Learning
     doi:10.3390/en15249538.                                       ASME 2021 Power Conference (2021). URL:
 [3] S. Hall, 2 - heat exchangers, in: S. Hall (Ed.),              https://doi.org/10.1115/POWER2021-64665.
     Branan’s Rules of Thumb for Chemical Engineers                doi:10.1115/POWER2021-64665, v001T01A002.
     (Fifth Edition), fifth edition ed., Butterworth-         [12] A. Gupta, V. Jadhav, A. Deodhar, V. Runkana,
     Heinemann, Oxford, 2012, pp. 27–57. URL:                      Physics-assisted long-short-term-memory network
     https://www.sciencedirect.com/science/article/pii/            for forecasting of fouling in a regenerative heat ex-
     B9780123877857000025. doi:https://doi.org/                    changer, in: Heat Transfer Summer Conference,
     10.1016/B978-0-12-387785-7.00002-5.                           volume 85796, American Society of Mechanical En-
 [4] K. J. Bell, Heat Exchanger Design for the Process             gineers, 2022, p. V001T20A001.
     Industries , Journal of Heat Transfer 126 (2005) 877–    [13] S. Sundar, M. C. Rajagopal, H. Zhao, G. Kuntumalla,
     885. URL: https://doi.org/10.1115/1.1833366. doi:10.          Y. Meng, H. C. Chang, C. Shao, P. Ferreira,
     1115/1.1833366.                                               N. Miljkovic, S. Sinha, S. Salapaka, Fouling model-
 [5] S. Kharaji, Heat exchanger design and optimiza-               ing and prediction approach for heat exchangers
     tion, in: L. C. Gómez, V. M. V. Flores, M. N.                 using deep learning, International Journal of
     Procopio (Eds.), Heat Exchangers, IntechOpen, Ri-             Heat and Mass Transfer 159 (2020) 120112. URL:
     jeka, 2021. URL: https://doi.org/10.5772/intechopen.          https://www.sciencedirect.com/science/article/pii/
     100450. doi:10.5772/intechopen.100450.                        S0017931020330489. doi:https://doi.org/10.
 [6] M. Saeed, A. S. Berrouk, Y. F. Al Wahedi,                     1016/j.ijheatmasstransfer.2020.120112.
     M. P. Singh, I. A. Dagga, I. Afgan,           Perfor-    [14] V. Jadhav, A. Deodhar, A. Gupta, V. Runkana,
     mance enhancement of a c-shaped printed cir-                  Physics informed neural network for health moni-
     cuit heat exchanger in supercritical co2 brayton              toring of an air preheater PHM Society European
     cycle: A machine learning-based optimization                  Conference, 7(1) (2022). URL: https://doi.org/10.
     study, Case Studies in Thermal Engineering 38                 36001/phme.2022.v7i1.3343. doi:10.36001/phme.
     (2022) 102276. URL: https://www.sciencedirect.com/            2022.v7i1.3343.
     science/article/pii/S2214157X22005226. doi:https:        [15] R. Majumdar, V. Jadhav, A. Deodhar, S. Karande,
     //doi.org/10.1016/j.csite.2022.102276.                        L. Vig, V. Runkana, Real-time health monitoring of
 [7] H. Keramati, F. Hamdullahpur, M. Barzegari,                   heat exchangers using hypernetworks and pinns,
     Deep reinforcement learning for heat exchanger                2022. arXiv:2212.10032.
     shape optimization,       International Journal of       [16] Z. Wu, B. Zhang, H. Yu, J. Ren, M. Pan, C. He,
     Heat and Mass Transfer 194 (2022) 123112. URL:                Q. Chen,        Accelerating heat exchanger de-
     https://www.sciencedirect.com/science/article/pii/            sign by combining physics-informed deep
     S001793102200583X. doi:https://doi.org/10.                    learning and transfer learning,              Chemi-
     1016/j.ijheatmasstransfer.2022.123112.                        cal Engineering Science 282 (2023) 119285.
 [8] J. Zou, T. Hirokawa, J. An, L. Huang, J. Camm,                URL:       https://www.sciencedirect.com/science/
     Recent advances in the applications of machine                article/pii/S0009250923008412.           doi:https:
     learning methods for heat exchanger model-                    //doi.org/10.1016/j.ces.2023.119285.
     ing—a review, Frontiers in Energy Research 11            [17] M. Pluhacek, A. Kazikova, T. Kadavy, A. Viktorin,
     (2023). URL: https://www.frontiersin.org/articles/            R. Senkerik, Leveraging large language models
     10.3389/fenrg.2023.1294531. doi:10.3389/fenrg.                for the generation of novel metaheuristic optimiza-
     2023.1294531.                                                 tion algorithms, in: Proceedings of the Compan-
 [9] L. Huang, J. Zou, B. Liu, Z. Jin, J. Qian, Machine            ion Conference on Genetic and Evolutionary Com-
     learning assisted microchannel geometric optimiza-            putation, GECCO ’23 Companion, Association for
     tion—a case study of channel designs, Energies 17             Computing Machinery, New York, NY, USA, 2023,
     (2024). URL: https://www.mdpi.com/1996-1073/17/               p. 1812–1820. URL: https://doi.org/10.1145/3583133.
     1/44. doi:10.3390/en17010044.                                 3596401. doi:10.1145/3583133.3596401.
[10] E. Efatinasab, N. Irannezhad, M. Rampazzo,               [18] K. Ma, D. Grandi, C. McComb, K. Goucher-Lambert,
     A. Diani, Machine and deep learning driven                    Conceptual design generation using large language
     models for the design of heat exchangers with                 models, 2023. arXiv:2306.01779.
     micro-finned tubes, Energy and AI 16 (2024)              [19] A. Sabbatella, A. Ponti, I. Giordani, A. Cande-
     100370. URL: https://www.sciencedirect.com/                   lieri, F. Archetti, Prompt optimization in large
     science/article/pii/S2666546824000363. doi:https:             language models, Mathematics 12 (2024). URL:
     //doi.org/10.1016/j.egyai.2024.100370.                        https://www.mdpi.com/2227-7390/12/6/929. doi:10.
[11] A. Gupta, V. Jadhav, M. Patil, A. Deodhar,                    3390/math12060929.
     V. Runkana,           Forecasting of Fouling in          [20] Z. Ma, H. Guo, J. Chen, G. Peng, Z. Cao, Y. Ma,



                                                         10
Sandeep Mishra et al. CEUR Workshop Proceedings                                                               1–22



     Y.-J. Gong, Llamoco: Instruction tuning of large        [34] R. Venkata Rao, R. Pawar, Design of Me-
     language models for optimization code generation,            chanical Components Using Variants of Rao
     2024. arXiv:2403.01131.                                      Algorithm, 2023, pp. 687–700. doi:10.1007/
[21] C. Yang, X. Wang, Y. Lu, H. Liu, Q. V. Le, D. Zhou,          978-981-19-9285-8_64.
     X. Chen, Large language models as optimizers, 2024.     [35] Z. Wang, J.-C. Liu,        Translating math for-
     arXiv:2309.03409.                                            mula images to latex sequences using deep neu-
[22] Y. Liu, T. Han, S. Ma, J. Zhang, Y. Yang, J. Tian,           ral networks with sequence-level training, In-
     H. He, A. Li, M. He, Z. Liu, Z. Wu, L. Zhao,                 ternational Journal on Document Analysis and
     D. Zhu, X. Li, N. Qiang, D. Shen, T. Liu, B. Ge,             Recognition (IJDAR) 24 (2021) 1–13. doi:10.1007/
     Summary of chatgpt-related research and per-                 s10032-020-00360-2.
     spective towards the future of large language           [36] L. Blecher, G. Cucurull, T. Scialom, R. Stojnic,
     models, Meta-Radiology 1 (2023) 100017. URL:                 Nougat: Neural optical understanding for academic
     https://www.sciencedirect.com/science/article/pii/           documents, 2023. arXiv:2308.13418.
     S2950162823000176. doi:https://doi.org/10.              [37] LlamaIndex, Llamaparse, https://docs.llamaindex.
     1016/j.metrad.2023.100017.                                   ai/en/stable/module_guides/loading/connector/
[23] A. Kashefi, T. Mukerji, Chatgpt for programming              llama_parse/, 2024. Accessed: 15 May 2024.
     numerical methods, 2023. arXiv:2303.12093.              [38] anthropic, claude3, https://anthropic.com/claude,
[24] OpenAI, Chatgpt,         https://www.openai.com/             2024. Accessed: 15 May 2024.
     chatgpt, 2023. Accessed: 15 May 2024.
[25] S. Yao, D. Yu, J. Zhao, I. Shafran, T. L. Griffiths,
     Y. Cao, K. Narasimhan, Tree of thoughts: Deliberate
     problem solving with large language models, 2023.
                                                             5. Code Listing
     arXiv:2305.10601.
[26] H. Wang, Z. Liu, S. Wang, G. Cui, N. Ding, Z. Liu,
                                                             5.1. Retrieved Base Code for similar
     G. Yu, Intervenor: Prompting the coding ability of           research article
     large language models with the interactive chain
     of repair, 2024. arXiv:2311.09868.                      import math
[27] S. Xu, L. Pang, H. Shen, X. Cheng, T.-S. Chua,          import numpy as np

     Search-in-the-chain: Interactively enhancing large
                                                             pie = 3.141
     language models with search for knowledge-
     intensive tasks, 2024. arXiv:2304.14732.                def Prandtl_number(mew,Cp,Kt):
[28] B. Li, K. Mellou, B. Zhang, J. Pathuri, I. Menache,        Pr = (mew*Cp)/Kt
     Large language models for supply chain optimiza-           return Pr
     tion, 2023. arXiv:2307.03875.
[29] H. Chen, G. E. Constante-Flores, C. Li, Diagnos-        def calculate_fs(Re):
     ing infeasible optimization problems using large           fs = 2 * 0.72 * Re**(-0.15) # equation (28)
     language models, 2023. arXiv:2308.12923.
[30] C. Liu, S. D. Zhang, A. R. Ibrahimzada, R. Jab-            return fs
     barvand, Codemind: A framework to challenge
                                                             def Number_of_tubes(C, n, DG, do):
     large language models for code reasoning, 2024.
                                                                NT = C * ((DG/do)**(-n)) # equation (4)
     arXiv:2402.09664.
                                                                return NT
[31] B. Ni, M. J. Buehler, Mechagents: Large language
     model multi-agent collaborations can solve me-          def Flow_velocity_tube(m, di, rho, NT, s):
     chanics problems, generate new data, and integrate         Vi = m / ((math.pi/4) * (di**2) * rho * (
     knowledge, 2023. arXiv:2311.08166.                             NT/s))
[32] A. AhmadiTeshnizi, W. Gao, M. Udell, Optimus:              # equation (3)
     Optimization modeling using mip solvers and large          return Vi
     language models, 2023. arXiv:2310.06116.
[33] V. Patel, R. Rao,        Design optimization of         def Reynolds_number_tube(rho_t,vt,di,mew_t):
                                                                Re = (rho_t*vt*di)/mew_t
     shell-and-tube heat exchanger using particle
                                                                return Re
     swarm optimization technique, Applied Ther-
     mal Engineering 30 (2010) 1417–1425. URL:               def calculate_friction_factor(Re):
     https://www.sciencedirect.com/science/article/pii/         ft = (1.82*math.log10(Re) - 1.64)**(-2) #
     S1359431110001080. doi:https://doi.org/10.                     equation (5)
     1016/j.applthermaleng.2010.03.001.                         return ft




                                                        11
Sandeep Mishra et al. CEUR Workshop Proceedings                                                  1–22



                                                         F = numerator * denominator # equation (20)
def Tube_side_heat_transfer_coefficient(di,
     Re, Pr, k):                                         return F
   Nu = 0.023 * (Re**0.8) * (Pr**0.4) #
        equation (6)                                   def Sensible_heat(Cp_h,mh,Th_i,Th_o):
   hi = (Nu * k) / di                                     Q = mh*Cp_h*(Th_i-Th_o)
   return hi                                              return Q

def Shell_hydaulic_diameter(St, do):                   def calculate_DPt(s, L, di, rho, Vi, mu, mu0,
   if St == 1.25*do: # square pitch                          m):
      De = (1.27 / do) * (St**2 - 0.785*do**2)            DPt = s * ((0.092 * (L/di) * ((rho * Vi**2)
      # equation (7a)                                          /2) *
   else: # triangular pitch                               ((mu/mu0)**(-m))) + 2.5) * ((rho * Vi**2)
      De = (1.10 / do) * (St**2 - 0.917*do**2)                 /2)
      # equation (7b)                                     # equation (16)
   return De                                              return DPt

def Cross_section_area(St, do, e, DG):                 def calculate_DPs(jf, DG, De, Le, rho, Vo, mu,
   As = (St - do) * e * DG / St # equation (8)               mu0):
                                                          DPs = 8 * jf * (DG/De) * (Le/DG) *
   return As                                              ((rho * Vo**2)/2) * ((mu/mu0)**(-0.14))
                                                          # equation (16)
def Flow_velocity_shell(ms,rho_s,As):                     return DPs
   vs = ms/(rho_s*As)
   return vs                                           def calculate_Cod(n, i, C_o):
                                                          X = np.arange(1, n + 1) # Create an array
def Reynolds_number_shell(ms,de,As,mew_s):                    of X
   re = (ms*de)/(As*mew_s)                                values from 1 to n
   return re                                              terms = C_o / (1 + i) ** X
                                                          C_od = np.sum(terms)
def Shell_Side_heat_transfer_coefficient(k,               return C_od
     De, Re, Pr, mu,
mu0, jh):                                              def Calculate_Total_Cost(C, n, DG, do, m,
   Nu = jh * Re * (Pr**(1/3)) * ((mu/mu0)                   rho_t, rho_s,
        **0.14)                                        s, mew_t, L, Kt, St, e, ms, mew_s, Ks, Rfi,
   # equation (11)                                          Rfo, Th_i,
   ho = (Nu * k) / De                                  Th_o, Tc_i, Tc_o, Cp_h, Cp_c, etta, ny, H, Ce,
   return ho                                                 i, kw,
                                                       xw, jh, jf, mu0, m_exp):
def Overall_heat_transfer_coefficient(hi, di,             di = 0.8*do
      do, Rfi, kw,                                        NT = Number_of_tubes(C, n, DG, do)
xw, Rfo, ho):                                             Vi = Flow_velocity_tube(m, di, rho_t, NT,
   K = 1 / ((do/(hi*di)) + (Rfi*do/di) + (xw/                  s)
        kw) + Rfo +                                       Re_t = Reynolds_number_tube(rho_t, Vi, di,
   (1/ho)) # equation (12)                                      mew_t)
   return K                                               Pr_t = Prandtl_number(mew_t, Cp_c, Kt)
                                                          hi = Tube_side_heat_transfer_coefficient(
def LMTD(Th_i,Th_o,Tc_i,Tc_o):                                 di, Re_t,
   deltaT1 = Th_i - Tc_o                                  Pr_t, Kt)
   deltaT2 = Th_o - Tc_i
   lmtd = (deltaT1 - deltaT2) / math.log(                De = Shell_hydaulic_diameter(St, do)
       deltaT1 / deltaT2)                                As = Cross_section_area(St, do, e, DG)
   return lmtd                                           Vo = Flow_velocity_shell(ms, rho_s, As)
                                                         Re_s = Reynolds_number_shell(ms, De, As,
def Correction_factor(R, P):                                 mew_s)
   numerator = ((R**2 + 1)**0.5) / (R - 1)               Pr_s = Prandtl_number(mew_s, Cp_h, Ks)
   denominator = math.log((1 - P) / (1 - P*R))           ho = Shell_Side_heat_transfer_coefficient(
        / math.log                                           Ks, De, Re_s,
   ((2 - P*(R + 1 - (R**2 + 1)**0.5)) /                  Pr_s, mew_s, mu0, jh)
   (2 - P*(R + 1 + (R**2 + 1)**0.5)))




                                                  12
Sandeep Mishra et al. CEUR Workshop Proceedings                                                               1–22



   K = Overall_heat_transfer_coefficient(hi,              Ce = 0.12
       di, do, Rfi, kw,                                   i = 10
   xw, Rfo, ho)                                           kw = 50
   lmtd = LMTD(Th_i, Th_o, Tc_i, Tc_o)                    xw = 0.0005
   R = (Th_i - Th_o) / (Tc_o - Tc_i)                      jh = 0.0035
   P = (Tc_o - Tc_i) / (Th_i - Tc_i)                      jf = 0.0035
   F = Correction_factor(R, P)                            mu0 = 0.0004
   A = (m*Cp_c*(Tc_o-Tc_i))/(K*F*lmtd)                    m_exp = 0.25
   Span = (A/(math.pi*do*NT))
                                                          C_tot = Calculate_Total_Cost(C, n, DG, do,
   DPt = calculate_DPt(s, Span, di, rho_t, Vi,                 m, rho_t,
        mew_t, mu0,                                       rho_s, s, mew_t, L, Kt, St, e, ms, mew_s,
   m_exp)                                                     Ks, Rfi, Rfo,
   DPs = calculate_DPs(jf, DG, De, L, rho_s,              Th_i, Th_o, Tc_i, Tc_o, Cp_h, Cp_c, etta,
       Vo, mew_s, mu0)                                        ny, H, Ce, i,
                                                          kw, xw, jh, jf, mu0, m_exp)
   a1 = 8000                                              print(f""The value of Objective function (
   a2 = 259.2                                                 Total cost)
   a3 = 0.93 # Exchanger made with Stainless              is = {C_tot}"")
       steel for both
   shell and tubes                                     if __name__ == ""__main__"":
   C_i = a1 + a2 * (A**(a3/3))                            main()

   P = 1 / etta * (((m / rho_t) * DPt) + ((ms
        / rho_s) * DPs))                               5.2. Final Mathematical code for similar
   C_o = P * Ce * H
   C_od = calculate_Cod(ny, i, C_o)
                                                            research article
                                                       This is the final result of the error-free mathematical code
   C_tot = C_i + C_od                                  generated by the LLM.
   return C_tot
                                                       import math
# Unified linking function                             import numpy as np
def main():
   C = 0.158                                           pie = 3.141
   n = 2.263
   DG = 0.54                                           def Prandtl_number(mew,Cp,Kt):
   do = 0.0254                                            Pr = (mew*Cp)/Kt
   m = 18.80                                              return Pr
   rho_t = 995
   rho_s = 850                                         def calculate_fs(b0, Re):
   s = 4                                                  fs = 2 * b0 * Re**(-0.15)
   mew_t = 0.00358                                        return fs
   L = 4.88
   Kt = 0.13                                           def Number_of_tubes(C,n1,Ds,d0):
   St = 1.25*do                                           Nt = C*((Ds/d0)**n1)
   e = 0.127                                              return Nt
   ms = 5.52
   mew_s = 0.0004                                      def Flow_velocity_tube(mt,dt,rho_t,n,Nt):
   Ks = 0.13                                              vt = (mt*(n/Nt))/((pie/4)*(dt**2)*rho_t)
   Rfi = 0.00061                                          return vt
   Rfo = 0.00061
   Th_i = 199                                          def Reynolds_number_tube(rho_t,vt,di,mew_t):
   Th_o = 93.3                                            Re = (rho_t*vt*di)/mew_t
   Tc_i = 37.80                                           return Re
   Tc_o = 76.7
   Cp_h = 2.47                                         def calculate_friction_factor(Re):
   Cp_c = 2.05                                            ft = (1.82 * math.log10(Re) - 1.64)**(-2)
   etta = 0.9                                             return ft
   ny = 10
   H = 7000                                            def Tube_side_heat_transfer_coefficient(Kt,di




                                                  13
Sandeep Mishra et al. CEUR Workshop Proceedings                                                  1–22



,Re,Pr,L,d0,mew_t,mew_w):                              def Sensible_heat(ms,Cps,Tis,Tos):
   if Re < 2300:                                          Q = ms*Cps*(Tis-Tos)
      ht = (Kt/di)*(3.657+(0.0677*(Re*Pr*(di/L            return Q
          ))
      **1.33)/(1+0.1*Pr*((Re*di/L)**0.3)))             def calculate_DPt(rho_t,vt,L,dt,ft,n):
   elif 2300 < Re < 10000:                                p = 4
      ft = calculate_friction_factor(Re)                  DPt = rho_t*vt**2/2 * ((L/dt)*ft + p) * n
      ht = (Kt/di)*((ft/8)*(Re-1000)*Pr)                  return DPt
          /(1+12.7
      *math.sqrt(ft/8)*(Pr**(2/3)-1))*(1+(di/L         def calculate_DPs(fs,rho_s,vs,L,B,Ds,De):
          )**0.67)                                        DPs = fs * rho_s*vs**2/2 * (L/B) * (Ds/De)
   else:                                                  return DPs
      ht = 0.027*(Kt/d0)*(Re**0.8)*(Pr**(1/3))
          *                                            def calculate_Cod(n, i, C_o):
      ((mew_t/mew_w)**0.14)                               X = np.arange(1, n + 1)
   return ht                                              terms = C_o / (1 + i) ** X
                                                          C_od = np.sum(terms)
def Shell_hydaulic_diameter(Pt,d0):                       return C_od
   De = 4*(Pt**2 - (math.pi*d0**2)/4)/(math.
       pi*d0)                                          def Calculate_Total_Cost(C, n1, Ds, mt, rho_t,
   return De
                                                       rho_s, n, mew_t, L, Kt, Pt, d0, B, ms, mew_s,
def Cross_section_area(Ds,b,C1):                       Ks, Rfs, Rft, Tis, Tos, Tit, Tot, Cp_h, Cp_c,
   As = Ds*b*C1                                        etta, ny, H, Ce, i, b, C1, mew_w):
   return As                                              p = 4
                                                          di = 0.8*d0
def Flow_velocity_shell(ms,rho_s,As):                     De = Shell_hydaulic_diameter(Pt,d0)
   vs = ms/(rho_s*As)                                     Re_s = Reynolds_number_shell(ms,De,
   return vs                                              Cross_section_area(Ds,b,C1),mew_s)
                                                          Pr_s = Prandtl_number(mew_s,Cp_h,Ks)
def Reynolds_number_shell(ms,de,As,mew_s):                hs = Shell_Side_heat_transfer_coefficient
   re = (ms*de)/(As*mew_s)                                (Ks,De,Re_s,Pr_s,mew_s,mew_w)
   return re                                              Nt = Number_of_tubes(C, n1, Ds, d0)
                                                          vt = Flow_velocity_tube(mt,di,rho_t,n,Nt)
def Shell_Side_heat_transfer_coefficient(Ks,              Re_t = Reynolds_number_tube(rho_t,vt,di,
     De,                                                      mew_t)
Re,Pr,mew_s,mew_w):                                       Pr_t = Prandtl_number(mew_t,Cp_c,Kt)
   hs = 0.36*(Ks/De)*(Re**0.55)*(Pr**(1/3))*              ht = Tube_side_heat_transfer_coefficient
   ((mew_s/mew_w)**0.14)                                  (Kt,di,Re_t,Pr_t,L,d0,mew_t,mew_w)
   return hs                                              U = 1/((1/hs)+Rfs+(d0/di)*(Rft+(1/ht)))
                                                          lmtd = LMTD(Tis,Tos,Tit,Tot)
def LMTD(Tis,Tos,Tit,Tot):                                F = Correction_factor(Tis,Tos,Tit,Tot)
   deltaT1 = Tis - Tot                                    A = (mt*Cp_c*(Tot-Tit))/(U*F*lmtd)
   deltaT2 = Tos - Tit                                    Span = (A/(pie*d0*Nt))
   lmtd = (deltaT1 - deltaT2) /                           ft = calculate_friction_factor(Re_t)
   math.log(deltaT1 / deltaT2)                            DPt = calculate_DPt(rho_t,vt,Span,di,ft,n)
   return lmtd                                            b0 = 0.72
                                                          fs = calculate_fs(b0, Re_s)
def Correction_factor(Tis, Tos, Tit, Tot):                vs = Flow_velocity_shell(ms,rho_s,
   R = (Tis - Tos) / (Tot - Tit)                          Cross_section_area(Ds,b,C1))
   P = (Tot - Tit) / (Tis - Tit)                          DPs = calculate_DPs(fs,rho_s,vs,L,B,Ds,De)
   numerator = math.sqrt(R**2 + 1) / (R - 1) *            a1 = 8000
                                                          a2 = 259.2
   math.log((1 - P) / (1 - P*R))                          a3 = 0.93
   denominator = math.log((2 - P*(R + 1 -                 C_i = a1 + a2 * (A**(a3/3))
   math.sqrt(R**2 + 1))) / (2 - P*(R + 1 +                P = 1 / etta * (((mt / rho_t) * DPt) +
   math.sqrt(R**2 + 1))))                                 ((ms / rho_s) * DPs))
   F = numerator / denominator                            C_o = P * Ce * H
   return F                                               C_od = calculate_Cod(ny, i, C_o)
                                                          C_tot = C_i + C_od




                                                  14
Sandeep Mishra et al. CEUR Workshop Proceedings                                                   1–22



   return C_tot                                          (9/2))**(-2/9)
                                                         *gamma**(2/9) * (1-gamma)**(29/27) * (1+
                                                             gamma)
5.3. First Instance Code generation for                  **(1/4)
                                                         * (le)**(7/9) * Dr**(29/27) * Z**(3/4)
     Non Similar research article
                                                       # Spherical roller bearing objective function
import math                                            def spherical_roller_bearing_dynamic_capacity
                                                            (bm,
# Rao-1 algorithm                                      lv, gamma, Dr, le, Z, alpha):
def rao1_update(Xu_v_w, Xbest_v_w, Xworst_v_w,            return 207.9 * bm * lv *
      r1):                                                (1 + (1.04 * ((1-gamma)/(1+gamma))
   return Xu_v_w + r1 * (Xbest_v_w -                   **(143/108))**(9/2))**
        Xworst_v_w)                                    (-2/9) * gamma**(2/9) * (1-gamma)**(29/27)
                                                        * (1+gamma)**(1/4) *
# Rao-2 algorithm                                       (le*math.cos(alpha))**(7/9) * Z**(3/4) * Dr
def rao2_update(Xu_v_w, Xbest_v_w, Xworst_v_w,               **(29/27)
      r1, r2,
Xu_v_w_or_XU_v_w, XU_v_w_or_Xu_v_w):                    # Plate fin heat exchanger objective
   return Xu_v_w + r1 * (Xbest_v_w -                         function
        Xworst_v_w) + r2                               def
   * (abs(Xu_v_w_or_XU_v_w) - abs(                          plate_fin_heat_exchanger_entropy_generation
        XU_v_w_or_Xu_v_w))
                                                       (epsilon, Tci, Thi, Rc, teh, Cph, dPh, Phi,
# Rao-3 algorithm                                      tec, Cpc, dPc, Pci):
def rao3_update(Xu_v_w, Xbest_v_w, Xworst_v_w,            return (1-epsilon) * ((Tci-Thi)**2 /
      r1, r2,                                             (Tci*Thi)) + (Rc*teh/Cph) * (dPh/Phi)
Xu_v_w_or_XU_v_w, XU_v_w_or_Xu_v_w):                      + (Rc*tec/Cpc) * (dPc/Pci)
   return Xu_v_w + r1 * (Xbest_v_w - abs(
        Xworst_v_w))                                   # Shell and tube heat exchanger objective
   + r2 * (abs(Xu_v_w_or_XU_v_w) - (                        function
        XU_v_w_or_Xu_v_w))                             def shell_and_tube_heat_exchanger_total_cost(
                                                            Ci, Cod):
# Helical compression spring objective                    return Ci + Cod
     function
def helical_spring_volume(D, d, n):                    # Welded beam objective function
   return math.pi**2 * D * d**2 * (n+2) / 4            def welded_beam_cost(c1, x1, t, l, h, c2, b,
                                                            L):
# Hydrostatic thrust bearing objective                    return (1+c1) * (x1*t + l) * h**2 + c2*t*b
     function                                                  *(l+L)
def hydrostatic_thrust_bearing_power_loss(Q,
     Po, Ef):                                          # Belt-pulley drive objective function
   return Q * Po / 0.7 + Ef                            def belt_pulley_drive_weight(rho, b, d1,
                                                       t1, d2, t2, d1_1, t1_1, d1_2, t1_2):
# Multiple disc clutch brake objective                    return math.pi * rho * b * (d1*t1 +
     function                                             d2*t2 + d1_1*t1_1 + d1_2*t1_2)
def multiple_disc_clutch_brake_mass(ro, ri, t,
      z, rho):                                         # Hollow shaft objective function
   return math.pi * (ro**2 - ri**2) * t * (z           def hollow_shaft_weight(do, di, L, rho):
        +1) * rho                                         return math.pi/4 * (do**2 - di**2) * L *
                                                              rho
# Cylindrical roller bearing objective
     function                                    def run_optimization(Xu_v_w, Xbest_v_w,
def                                              Xworst_v_w, r1, r2, Xu_v_w_or_XU_v_w,
     cylindrical_roller_bearing_dynamic_capacity XU_v_w_or_Xu_v_w,D, d, n, Q, Po, Ef,
     (bm, lv,                                    ro, ri, t, z, rho, bm, lv, gamma, Dr,
gamma, Dr, le, Z):                               le, Z, alpha, epsilon, Tci, Thi, Rc,
   return 207.9 * bm * lv *                      teh, Cph, dPh, Phi, tec, Cpc, dPc,
   (1 + (1.04 * ((1-gamma)/(1+gamma))            Pci, Ci, Cod, c1, x1, l, h, c2, b, L, do, di):
        **(143/108))**




                                                  15
Sandeep Mishra et al. CEUR Workshop Proceedings                                               1–22



   """                                                 (bm, lv, gamma, Dr, le, Z)
   Runs the optimization process using                 spherical_roller_bearing_result =
   the Rao algorithms and objective functions.             spherical
                                                       _roller_bearing_dynamic_capacity
                                                       (bm, lv, gamma, Dr, le, Z, alpha)
   Parameters:                                         plate
   - Xu_v_w, Xbest_v_w, Xworst_v_w,                    _fin_heat_exchanger_result = plate
   r1, r2, Xu_v_w_or_XU_v_w,                           _fin_heat_exchanger_entropy_generation
   XU_v_w_or_Xu_v_w: Parameters for Rao                (epsilon, Tci, Thi, Rc, teh, Cph, dPh, Phi,
       algorithms
   - D, d, n: Parameters for helical                   tec, Cpc, dPc, Pci)
   compression spring                                  shell_and_tube_heat_exchanger_result =
   - Q, Po, Ef: Parameters for hydrostatic                 shell
       thrust bearing                                  _and_tube_heat_exchanger_total_cost
   - ro, ri, t, z, rho: Parameters for                 (Ci, Cod)
       multiple                                        welded_beam_result = welded_beam_cost(c1,
   disc clutch brake                                   x1, t, l, h, c2, b, L)
   - bm, lv, gamma, Dr, le, Z: Parameters for          belt_pulley_drive_result =
   cylindrical roller bearing                              belt_pulley_drive_weight
   - alpha: Additional parameter for                   (rho, b, d1, t1, d2, t2, d1_1, t1_1, d1_2,
       spherical                                            t1_2)
   roller bearing                                      hollow_shaft_result = hollow_shaft_weight(
   - epsilon, Tci, Thi, Rc, teh, Cph, dPh,                 do, di, L, rho)
       Phi,
   tec, Cpc, dPc, Pci: Parameters for plate            # Return results
       fin                                             return {
   heat exchanger                                         ’rao1_result’: rao1_result,
   - Ci, Cod: Parameters for shell and tube               ’rao2_result’: rao2_result,
       heat exchanger                                     ’rao3_result’: rao3_result,
   - c1, x1, l, h, c2, b, L: Parameters for               ’helical_spring_result’:
       welded beam                                        helical
   - do, di: Additional parameters for hollow             _spring_result,
        shaft                                             ’hydrostatic
   """                                                    _thrust_bearing_result’: hydrostatic
                                                          _thrust_bearing_result,
   # Run Rao algorithms                                   ’multiple_disc_clutch_brake_result’:
   rao1_result = rao1_update(Xu_v_w,                          multiple
       Xbest_v_w, Xworst_v_w, r1)                         _disc_clutch_brake_result,
   rao2_result = rao2_update(Xu_v_w,                      ’cylindrical_roller_bearing_result’:
       Xbest_v_w, Xworst_v_w,                                 cylindrical
   r1, r2, Xu_v_w_or_XU_v_w, XU_v_w_or_Xu_v_w)            _roller_bearing_result,
                                                          ’spherical_roller_bearing_result’:
   rao3_result = rao3_update(Xu_v_w,                      spherical
       Xbest_v_w, Xworst_v_w,                             _roller_bearing_result,
   r1, r2, Xu_v_w_or_XU_v_w, XU_v_w_or_Xu_v_w)            ’plate_fin_heat_exchanger_result’:
                                                          plate_fin_heat_exchanger_result,
                                                          ’shell_and_tube_heat_exchanger_result’:
   # Calculate objective functions                            shell
   helical_spring_result =                                _and_tube_heat_exchanger_result,
       helical_spring_volume                              ’welded_beam_result’: welded_beam_result
   (D, d, n)                                                  ,
   hydrostatic_thrust_bearing_result =                    ’belt_pulley_drive_result’:
       hydrostatic_                                           belt_pulley_drive_result,
   thrust_bearing_power_loss(Q, Po, Ef)                   ’hollow_shaft_result’:
   multiple_disc_clutch_brake_result =                        hollow_shaft_result
   multiple_disc_clutch_brake_mass(ro, ri, t,          }
        z, rho)
   cylindrical_roller_bearing_result =
       cylindrical
   _roller_bearing_dynamic_capacity




                                                  16
Sandeep Mishra et al. CEUR Workshop Proceedings                                                   1–22



5.4. Final revised Mathematical model for                * (le)**(7/9) * Dr**(29/27) * Z**(3/4)
     the non-similar research article
                                                       # Spherical roller bearing objective function
     following the code correction                     def spherical_roller_bearing_dynamic_capacity
     framework                                         (bm, lv, gamma, Dr, le, Z, alpha):return
                                                       207.9 * bm * lv * (1 +
import math                                            (1.04 * ((1-gamma)/(1+gamma))**(143/108))
                                                       **(9/2))**(-2/9) * gamma**(2/9) * (1-gamma)
# Rao-1 algorithm                                          **(29/27)
def rao1_update(Xu_v_w, Xbest_v_w, Xworst_v_w,         * (1+gamma)**(1/4) * (le*math.cos(alpha))
      r1):                                                 **(7/9) * Z**(3/4) *
   return Xu_v_w + r1 * (Xbest_v_w -                   Dr**(29/27)
        Xworst_v_w)
                                                       # Plate fin heat exchanger objective function
# Rao-2 algorithm                                      def
def rao2_update                                            plate_fin_heat_exchanger_entropy_generation
(Xu_v_w, Xbest_v_w, Xworst_v_w, r1,
r2, Xu_v_w_or_XU_v_w, XU_v_w_or_Xu_v_w):               (epsilon, Tci, Thi, Rc, teh, Cph,
     return                                            dPh, Phi, tec, Cpc, dPc, Pci):return
   Xu_v_w + r1 * (Xbest_v_w - Xworst_v_w)              (1-epsilon) * ((Tci-Thi)**2 / (Tci*Thi)) +
   + r2 * (abs(Xu_v_w_or_XU_v_w) - abs(                (Rc*teh/Cph) * (dPh/Phi) + (Rc*tec/Cpc) * (
        XU_v_w_or_Xu_v_w))                                 dPc/Pci)


# Rao-3 algorithm                                      # Shell and tube heat exchanger objective
def rao3_update(Xu_v_w, Xbest_v_w, Xworst_v_w,              function
     r1, r2,                                           def shell_and_tube_heat_exchanger_total_cost(
Xu_v_w_or_XU_v_w, XU_v_w_or_Xu_v_w):return                  Ci, Cod):
Xu_v_w + r1 * (Xbest_v_w - abs(Xworst_v_w)) +             return Ci + Cod
r2 * (abs(Xu_v_w_or_XU_v_w) - (
    XU_v_w_or_Xu_v_w))                                 # Welded beam objective function
                                                       def welded_beam_cost(c1, x1, t, l, h, c2, b,
# Helical compression spring objective                      L):
     function                                             return (1+c1) * (x1*t + l) * h**2 + c2*t*b
def helical_spring_volume(D, d, n):                            *(l+L)
   return math.pi**2 * D * d**2 * (n+2) / 4
                                                       # Belt-pulley drive objective function
# Hydrostatic thrust bearing objective                 def belt_pulley_drive_weight(rho, b, d1, t1,
     function                                          d2, t2, d1_1, t1_1, d1_2, t1_2):return
def hydrostatic_thrust_bearing_power_loss(Q,           math.pi * rho * b * (d1*t1 + d2*t2 + d1_1*
     Po, Ef):                                              t1_1 + d1_2*t1_2)
   return Q * Po / 0.7 + Ef
                                                       # Hollow shaft objective function
# Multiple disc clutch brake objective                 def hollow_shaft_weight(do, di, L, rho):
     function                                             return math.pi/4 * (do**2 - di**2) * L *
def multiple_disc_clutch_brake_mass(ro, ri, t,                rho
      z, rho):
   return math.pi * (ro**2 - ri**2) * t * (z     def run_optimization(Xu_v_w, Xbest_v_w,
        +1) * rho                                Xworst_v_w, r1, r2, Xu_v_w_or_XU_v_w,
                                                      XU_v_w_or_Xu_v_w,
# Cylindrical roller bearing objective           D, d, n, Q, Po, Ef, ro, ri, t, z, rho, bm,
     function                                    lv, gamma, Dr, le, Z, alpha,, Tci, Thi, Rc,
def                                                   teh,
     cylindrical_roller_bearing_dynamic_capacity Cph, dPh, Phi, tec, Cpc, dPc, Pci, Ci, Cod,
                                                 c1, x1, l, h, c2, b, L, do, di):""""""
(bm, lv, gamma, Dr, le, Z):                         Runs the optimization process using the
   return 207.9 * bm * lv *                              Rao algorithms
   (1 + (1.04 * ((1-gamma)/(1+gamma))               and objective functions.
   **(143/108))**(9/2))**(-2/9)
   * gamma**(2/9) * (1-gamma)**(29/27) * (1+             Parameters:
       gamma)**(1/4)                                     - Xu_v_w, Xbest_v_w, Xworst_v_w, r1, r2,




                                                  17
Sandeep Mishra et al. CEUR Workshop Proceedings                                                 1–22



   Xu_v_w_or_XU_v_w, XU_v_w_or_Xu_v_w:                   result = plate_fin_heat_exchanger_entropy_
       Parameters                                        generation
   for Rao algorithms                                    (epsilon, Tci, Thi, Rc, teh, Cph, dPh, Phi,
   - D, d, n: Parameters                                      tec, Cpc,
   for helical compression spring                        dPc, Pci)
   - Q, Po, Ef: Parameters                               shell_and_tube_heat_exchanger_
   for hydrostatic thrust bearing                        result =
   - ro, ri, t, z, rho: Parameters                           shell_and_tube_heat_exchanger_total_cost
   for multiple disc clutch brake
   - bm, lv, gamma, Dr, le, Z: Parameters                (Ci, Cod)
   for cylindrical roller bearing                        welded_beam_result = welded_beam_cost
   - alpha: Additional                                   (c1, x1, t, l, h, c2, b, L)
   parameter for spherical roller bearing                belt_pulley_drive_result =
   - epsilon, Tci, Thi, Rc,                                  belt_pulley_drive_weight
   teh, Cph, dPh, Phi, tec, Cpc, dPc, Pci:               (rho, b, d1, t1, d2, t2, d1_1, t1_1, d1_2,
       Parameters                                             t1_2)
   for plate fin heat exchanger                          hollow_shaft_result = hollow_shaft_weight
   - Ci, Cod: Parameters for shell and tube              (do, di, L, rho)
       heat exchanger
   - c1, x1, l, h, c2, b, L: Parameters for              # Return results
       welded beam                                       return {
   - do, di: Additional parameters for hollow               ’rao1_result’: rao1_result,
        shaft                                               ’rao2_result’: rao2_result,
   """"""                                                   ’rao3_result’: rao3_result,
                                                            ’helical_spring_result’:
   # Run Rao algorithms                                         helical_spring_result,
   rao1_result = rao1_update(Xu_v_w,                        ’hydrostatic_thrust_bearing_result’:
       Xbest_v_w,                                               hydrostatic_
   Xworst_v_w, r1)                                          thrust_bearing_result,
   rao2_result = rao2_update(Xu_v_w,                        ’multiple_disc_clutch_brake_result’:
       Xbest_v_w,                                               multiple_disc_
   Xworst_v_w, r1, r2, Xu_v_w_or_XU_v_w,                    clutch_brake_result,
       XU_v_w_or_Xu_v_w)                                    ’cylindrical_roller_bearing_result’:
   rao3_result = rao3_update(Xu_v_w,                            cylindrical_roller
       Xbest_v_w,                                           _bearing_result,
   Xworst_v_w, r1, r2, Xu_v_w_or_XU_v_w,                    ’spherical_roller_bearing_result’:
       XU_v_w_or_Xu_v_w)                                        spherical_
                                                            roller_bearing_result,
   # Calculate objective functions                          ’plate_fin_heat_exchanger_result’:
   helical_spring_result =                                      plate_fin_
       helical_spring_volume                                heat_exchanger_result,
   (D, d, n)                                                ’shell_and_tube_heat_exchanger_result’:
   hydrostatic_thrust_bearing_                                  shell_and_tube_
   result =                                                 heat_exchanger_result,
       hydrostatic_thrust_bearing_power_loss                ’welded_beam_result’: welded_beam_result
   (Q, Po, Ef)                                                  ,
   multiple_disc_clutch_brake_                              ’belt_pulley_drive_result’:
   result = multiple_disc_clutch_brake_mass                     belt_pulley_drive_result,
   (ro, ri, t, z, rho)                                      ’hollow_shaft_result’:
   cylindrical_roller_bearing_                                  hollow_shaft_result
   result =                                              }
       cylindrical_roller_bearing_dynamic_capacity

   (bm, lv, gamma, Dr, le, Z)                   5.5.       Initial code generation for
   spherical_roller_bearing_
   result =
                                                           optimization model outlined in the
       spherical_roller_bearing_dynamic_capacity           research article
   (bm, lv, gamma, Dr, le, Z, alpha)                   def PSO
   plate_fin_heat_exchanger_




                                                  18
Sandeep Mishra et al. CEUR Workshop Proceedings                                                     1–22



(num_particles, max_iterations, w, c1, c2,                            i][2])
    Ds_min,
Ds_max, do_min, do_max, B_min, B_max):                         particles[i][0] += velocities[i][0]
                                                               particles[i][1] += velocities[i][1]
   particles = []                                              particles[i][2] += velocities[i][2]
   velocities = []
   best_positions = []                                         particles[i][0] = max(min(particles[i
   best_costs = []                                                 ][0], Ds_max)
                                                               , Ds_min)
   global_best_position = None                                 particles[i][1] = max(min(particles[i
   global_best_cost = float(’inf’)                                 ][1], do_max)
                                                               , do_min)
   for i in range(num_particles):                              particles[i][2] = max(min(particles[i
      Ds = random.uniform(Ds_min, Ds_max)                          ][2], B_max)
      do = random.uniform(do_min, do_max)                      , B_min)
      B = random.uniform(B_min, B_max)
                                                               cost = Calculate_Total_Cost(params)
      particles.append([Ds, do, B])
      velocities.append([0, 0, 0])                             if cost < best_costs[i]:
                                                                  best_positions[i] = particles[i].
      cost = Calculate_Total_Cost(0.158,                              copy()
          2.263, Ds,                                              best_costs[i] = cost
      18.80, 995, 850, 4, 0.00358, 4.88, 0.13,
           1.25*                                                     if cost < global_best_cost:
      0.0254, do, B, 5.52, 0.0004, 0.13,                                global_best_position =
          0.00061,                                                          particles[i].copy()
      0.00061, 199, 93.3, 37.80, 76.7, 2.47,                            global_best_cost = cost
          2.05,
      0.9, 10, 7000, 0.12, 10, 0.127, 0.4,               return global_best_position
          0.0004)
                                                       # PSO parameters
      best_positions.append([Ds, do, B])               num_particles = 50
      best_costs.append(cost)                          max_iterations = 100
                                                       w = 0.7
      if cost < global_best_cost:                      c1 = 1.4
         global_best_position = [Ds, do, B]            c2 = 1.4
         global_best_cost = cost
                                                       # Variable limits
   for iteration in range(max_iterations):             Ds_min = 0.1
      for i in range(num_particles):                   Ds_max = 1.5
         r1 = random.random()                          do_min = 0.015
         r2 = random.random()                          do_max = 0.051
                                                       B_min = 0.05
          velocities[i][0] = w*velocities[i][0]        B_max = 0.5
               + c1*r1*
          (best_positions[i][0] - particles[i          optimal_values = PSO(num_particles,
              ][0]) + c2*r2*                           max_iterations, w, c1, c2, Ds_min, Ds_max,
          (global_best_position[0] - particles[            do_min,
              i][0])                                   do_max, B_min, B_max)
          velocities[i][1] = w*velocities[i][1]
               + c1*r1*
          (best_positions[i][1] - particles[i          5.6. Final revised optimisation model
              ][1]) + c2*r2*
          (global_best_position[1] - particles[
                                                            following the code correction
              i][1])                                        framework
          velocities[i][2] = w*velocities[i][2]
               + c1*r1*                                import math
          (best_positions[i][2] - particles[i          import numpy as np
              ][2]) + c2*r2*
          (global_best_position[2] - particles[        pie = 3.141




                                                  19
Sandeep Mishra et al. CEUR Workshop Proceedings                                                     1–22



                                                       (Ks,De,Re,Pr,mew_s,mew_w):
def Prandtl_number(mew,Cp,Kt):                            hs = 0.36*(Ks/De)*(Re**0.55)
   Pr = (mew*Cp)/Kt                                       *(Pr**(1/3))*((mew_s/mew_w)**0.14)
   return Pr                                              return hs

def calculate_fs(b0, Re):                              def LMTD(Tis,Tos,Tit,Tot):
   fs = 2 * b0 * Re**(-0.15)                              deltaT1 = Tis - Tot
   return fs                                              deltaT2 = Tos - Tit
                                                          lmtd = (deltaT1 - deltaT2) / math.log(
def Number_of_tubes(C,n1,Ds,d0):                              deltaT1 / deltaT2)
   Nt = C*((Ds/d0)**n1)                                   return lmtd
   return Nt
                                                       def Correction_factor(Tis, Tos, Tit, Tot):
def Flow_velocity_tube(mt,dt,rho_t,n,Nt):                 R = (Tis - Tos) / (Tot - Tit)
   vt = (mt*(n/Nt))/((pie/4)*(dt**2)*rho_t)               P = (Tot - Tit) / (Tis - Tit)
   return vt                                              numerator = math.sqrt(R**2 + 1) /
                                                          (R - 1) * math.log((1 - P) / (1 - P*R))
def Reynolds_number_tube(rho_t,vt,di,mew_t):              denominator = math.log((2 - P*
   Re = (rho_t*vt*di)/mew_t                               (R + 1 - math.sqrt(R**2 + 1))) /
   return Re                                              (2 - P*(R + 1 + math.sqrt(R**2 + 1))))
                                                          F = numerator / denominator
def calculate_friction_factor(Re):                        return F
   ft = (1.82 * math.log10(Re) - 1.64)**(-2)
   return ft                                           def Sensible_heat(ms,Cps,Tis,Tos):
                                                          Q = ms*Cps*(Tis-Tos)
def Tube_side_heat_transfer_coefficient                   return Q
(Kt,di,Re,Pr,L,d0,mew_t,mew_w):
   if Re < 2300:                                       def calculate_DPt(rho_t,vt,L,dt,ft,n):
      ht = (Kt/di)*(3.657+(0.0677*                        p = 4
      (Re*Pr*(di/L))**1.33)/(1+0.1*Pr*((Re*di/            DPt = rho_t*vt**2/2 * ((L/dt)*ft + p) * n
          L)**0.3)))                                      return DPt
   elif 2300 < Re < 10000:
      ft = calculate_friction_factor(Re)               def calculate_DPs(fs,rho_s,vs,L,B,Ds,De):
      ht = (Kt/di)*((ft/8)*                               DPs = fs * rho_s*vs**2/2 * (L/B) * (Ds/De)
      (Re-1000)*Pr)/(1+12.7*                              return DPs
      math.sqrt(ft/8)*(Pr**(2/3)-1))*(1+(di/L)
          **0.67)                                      def calculate_Cod(n, i, C_o):
   else:                                                  X = np.arange(1, n + 1)
      ht = 0.027*(Kt/d0)*(Re**0.8)*(Pr**(1/3))            terms = C_o / (1 + i) ** X
      *((mew_t/mew_w)**0.14)                              C_od = np.sum(terms)
   return ht                                              return C_od

def Shell_hydaulic_diameter(Pt,d0):                    def Calculate_Total_Cost(C, n1, Ds, mt, rho_t,
   De = 4*(Pt**2 - (math.pi*d0**2)/4)/(math.
       pi*d0)                                          rho_s, n, mew_t, L, Kt, Pt, d0, B, ms, mew_s,
   return De                                           Ks, Rfs, Rft, Tis, Tos, Tit, Tot, Cp_h, Cp_c,
                                                       etta, ny, H, Ce, i, b, C1, mew_w):
def Cross_section_area(Ds,b,C1):                          p = 4
   As = Ds*b*C1                                           di = 0.8*d0
   return As                                              De = Shell_hydaulic_diameter(Pt,d0)
                                                          Re_s = Reynolds_number_shell(ms,De,
def Flow_velocity_shell(ms,rho_s,As):                     Cross_section_area(Ds,b,C1),mew_s)
   vs = ms/(rho_s*As)                                     Pr_s = Prandtl_number(mew_s,Cp_h,Ks)
   return vs                                              hs = Shell_Side_heat_transfer_coefficient
                                                          (Ks,De,Re_s,Pr_s,mew_s,mew_w)
def Reynolds_number_shell(ms,de,As,mew_s):                Nt = Number_of_tubes(C, n1, Ds, d0)
   re = (ms*de)/(As*mew_s)                                vt = Flow_velocity_tube(mt,di,rho_t,n,Nt)
   return re                                              Re_t = Reynolds_number_tube(rho_t,vt,di,
                                                              mew_t)
def Shell_Side_heat_transfer_coefficient                  Pr_t = Prandtl_number(mew_t,Cp_c,Kt)




                                                  20
Sandeep Mishra et al. CEUR Workshop Proceedings                                                  1–22



   ht = Tube_side_heat_transfer_coefficient
   (Kt,di,Re_t,Pr_t,L,d0,mew_t,mew_w)                  for iteration in range(max_iterations):
   U = 1/((1/hs)+Rfs+(d0/di)*(Rft+(1/ht)))                for i in range(num_particles):
   lmtd = LMTD(Tis,Tos,Tit,Tot)                              r1 = random.random()
   F = Correction_factor(Tis,Tos,Tit,Tot)                    r2 = random.random()
   A = (mt*Cp_c*(Tot-Tit))/(U*F*lmtd)
   Span = (A/(pie*d0*Nt))                                   velocities[i][0] = w*velocities[i][0]
   ft = calculate_friction_factor(Re_t)                          + c1*r1*
   DPt = calculate_DPt(rho_t,vt,Span,di,ft,n)               (best_positions[i][0] - particles[i
   b0 = 0.72                                                    ][0]) + c2*r2*
   fs = calculate_fs(b0, Re_s)                              (global_best_position[0] - particles[
   vs = Flow_velocity_shell(ms,rho_s,                           i][0])
   Cross_section_area(Ds,b,C1))                             velocities[i][1] = w*velocities[i][1]
   DPs = calculate_DPs(fs,rho_s,vs,L,B,Ds,De)                    + c1*r1*
   a1 = 8000                                                (best_positions[i][1] - particles[i
   a2 = 259.2                                                   ][1]) + c2*r2*
   a3 = 0.93                                                (global_best_position[1] - particles[
   C_i = a1 + a2 * (A**(a3/3))                                  i][1])
   P = 1 / etta * (((mt / rho_t) * DPt) +                   velocities[i][2] = w*velocities[i][2]
   ((ms / rho_s) * DPs))                                         + c1*r1*
   C_o = P * Ce * H                                         (best_positions[i][2] - particles[i
   C_od = calculate_Cod(ny, i, C_o)                             ][2]) + c2*r2*
   C_tot = C_i + C_od                                       (global_best_position[2] - particles[
   return C_tot                                                 i][2])

import random                                               particles[i][0] += velocities[i][0]
                                                            particles[i][1] += velocities[i][1]
def PSO(num_particles, max_iterations, w,                   particles[i][2] += velocities[i][2]
c1, c2, Ds_min, Ds_max, do_min, do_max, B_min,
     B_max):                                                particles[i][0] = max(min(particles[i
                                                                ][0], Ds_max),
   particles = []                                           Ds_min)
   velocities = []                                          particles[i][1] = max(min(particles[i
   best_positions = []                                          ][1], do_max),
   best_costs = []                                          do_min)
                                                            particles[i][2] = max(min(particles[i
   global_best_position = None                                  ][2], B_max),
   global_best_cost = float(’inf’)                          B_min)

   for i in range(num_particles):                           cost = Calculate_Total_Cost(0.158,
      Ds = random.uniform(Ds_min, Ds_max)                       2.263,
      do = random.uniform(do_min, do_max)                   particles[i][0], 18.80, 995, 850, 4,
      B = random.uniform(B_min, B_max)                          0.00358
                                                            , 4.88, 0.13, 1.25*0.0254, particles[
      particles.append([Ds, do, B])                             i][1],
      velocities.append([0, 0, 0])                          particles[i][2], 5.52, 0.0004, 0.13,
                                                                0.00061
      cost = Calculate_Total_Cost(0.158,                    , 0.00061, 199, 93.3, 37.80, 76.7,
      2.263, Ds, 18.80, 995, 850, 4, 0.00358                    2.47, 2.05
      , 4.88, 0.13, 1.25*0.0254, do, B, 5.52                , 0.9, 10, 7000, 0.12, 10, 0.127,
      , 0.0004, 0.13, 0.00061, 0.00061, 199,                    0.4, 0.0004)
      93.3, 37.80, 76.7, 2.47, 2.05, 0.9, 10
      , 7000, 0.12, 10, 0.127, 0.4, 0.0004)                 if cost < best_costs[i]:
                                                               best_positions[i] = particles[i].
      best_positions.append([Ds, do, B])                           copy()
      best_costs.append(cost)                                  best_costs[i] = cost

      if cost < global_best_cost:                              if cost < global_best_cost:
         global_best_position = [Ds, do, B]                       global_best_position =
         global_best_cost = cost                                      particles[i].




                                                  21
Sandeep Mishra et al. CEUR Workshop Proceedings                                                                        1–22



                  copy()                                         quently training machine learning models, they demon-
                  global_best_cost = cost                        strated significant improvements in thermo-hydraulic
                                                                 performance using a multi-objective genetic algorithm.
   return global_best_position                                   Concurrently, Keramati et al. [7] explored the poten-
                                                                 tial of deep reinforcement learning (Deep RL) for heat
# PSO parameters
                                                                 exchanger shape optimization, integrating a deep neu-
num_particles = 50
max_iterations = 100
                                                                 ral network (DNN) with a CFD solver. Their approach,
w = 0.7                                                          based on Proximal Policy Optimization (PPO), resulted
c1 = 1.4                                                         in notable enhancements in heat transfer efficiency and
c2 = 1.4                                                         pressure drop reduction. Zou et al. [8] reviewed the appli-
                                                                 cations of machine learning methods for heat exchanger
# Variable limits                                                modeling, highlighting the effectiveness of these models
Ds_min = 0.1                                                     for design optimization. Additionally, Long et al. [9] and
Ds_max = 1.5                                                     EFATINASAB et al. [10] investigated the use of machine
do_min = 0.015                                                   learning and deep learning models for microchannel and
do_max = 0.051
                                                                 micro-finned tube heat exchangers, respectively, demon-
B_min = 0.05
                                                                 strating the competitive performance and scalability of
B_max = 0.5
                                                                 these techniques in design optimization.
optimal_values, optimal_cost = PSO(
    num_particles,
max_iterations, w, c1, c2, Ds_min, Ds_max,
    do_min,
do_max, B_min, B_max)

print(f"Optimal values: Shell diameter =
{optimal_values[0]}, Tube outer diameter =
{optimal_values[1]}, Baffle spacing = {
    optimal_values[2]}")




6. Heat Exchanger Design with
   Surrogate Models
Researchers have explored various surrogate modeling
approaches, including machine learning [6, 7, 8, 9, 10]
and deep learning [11, 12, 13, 14, 15, 16], to accelerate the
design and optimization of heat exchangers.
   Fouling, the deposition of chemical compounds, re-
duces the heat transfer efficiency of heat exchangers and
can lead to operational stoppages. Measuring the extent
of fouling is challenging due to the lack of direct measure-
ments. Recently, deep learning-based models have been
developed to provide real-time visibility and forecast the
health of heat exchangers, aiding in better planning and
optimization of operations [11, 12, 13]. Physics-informed
deep learning approaches have further enhanced real-
time visibility into fouling severity, facilitating real-time
operational optimizations in plants [14, 15]. These ap-
proaches have also been applied to accelerate the design
process [16].
   Saeed et al. [6] applied machine learning algorithms
to improve the performance of a C-shaped printed cir-
cuit heat exchanger (PCHE) within a supercritical CO2
Brayton cycle. By analyzing 81 channel configurations
using computational fluid dynamics (CFD) and subse-



                                                            22