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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""tempx.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1Vf5N8mlJ4efrplevzTY2qQCIEhCvd1jy
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import math # For access to infinity
|
| 11 |
+
|
| 12 |
+
import gradio # For building the interface
|
| 13 |
+
import pandas # For working with tables
|
| 14 |
+
|
| 15 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline # For LLMS
|
| 16 |
+
|
| 17 |
+
# Instantiate the model that we'll be calling. This is a tiny one!
|
| 18 |
+
MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
|
| 19 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 20 |
+
pipe = pipeline(
|
| 21 |
+
task="text-generation",
|
| 22 |
+
model=AutoModelForCausalLM.from_pretrained(
|
| 23 |
+
MODEL_ID,
|
| 24 |
+
),
|
| 25 |
+
tokenizer=tokenizer
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Create a function to do the beam calculations
|
| 29 |
+
def calculate_heat_flow(T_out, h_out, thickness1, k1, thickness2, k2, T_in, h_in):
|
| 30 |
+
"""Calculates heat flux and temperatures through a two-layer wall.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
T_out: Outdoor temperature (Celsius).
|
| 34 |
+
h_out: Outdoor convection coefficient (W/(m^2*K)).
|
| 35 |
+
thickness1: Thickness of layer 1 (m).
|
| 36 |
+
k1: Thermal conductivity of layer 1 (W/(m*K)).
|
| 37 |
+
thickness2: Thickness of layer 2 (m).
|
| 38 |
+
k2: Thermal conductivity of layer 2 (W/(m*K)).
|
| 39 |
+
T_in: Indoor temperature (Celsius).
|
| 40 |
+
h_in: Indoor convection coefficient (W/(m^2*K)).
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
A tuple containing:
|
| 44 |
+
Q: Total heat flux (W/m^2).
|
| 45 |
+
T_outer_surface: Temperature at the outer surface (Celsius).
|
| 46 |
+
T_interface: Temperature at the interface between layers (Celsius).
|
| 47 |
+
T_inner_surface: Temperature at the inner surface (Celsius).
|
| 48 |
+
"""
|
| 49 |
+
# Assume A = 1 m^2
|
| 50 |
+
area = 1
|
| 51 |
+
|
| 52 |
+
# Calculate thermal resistances
|
| 53 |
+
R_out = 1 / (h_out * area)
|
| 54 |
+
R1 = thickness1 / (k1 * area)
|
| 55 |
+
R2 = thickness2 / (k2 * area)
|
| 56 |
+
R_in = 1 / (h_in * area)
|
| 57 |
+
|
| 58 |
+
# Calculate total thermal resistance
|
| 59 |
+
R_total = R_out + R1 + R2 + R_in
|
| 60 |
+
|
| 61 |
+
# Calculate total heat flux
|
| 62 |
+
Q = (T_out - T_in) / R_total
|
| 63 |
+
|
| 64 |
+
# Calculate temperatures at different points
|
| 65 |
+
T_outer_surface = T_out - Q * R_out
|
| 66 |
+
T_interface = T_outer_surface - Q * R1
|
| 67 |
+
T_inner_surface = T_interface - Q * R2
|
| 68 |
+
|
| 69 |
+
return Q, T_outer_surface, T_interface, T_inner_surface
|
| 70 |
+
|
| 71 |
+
def calculate_heat_flow_gr(T_out, h_out, thickness1, k1, thickness2, k2, T_in, h_in):
|
| 72 |
+
"""Calculates heat flux and temperatures through a two-layer wall for Gradio output.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
T_out: Outdoor temperature (Celsius).
|
| 76 |
+
h_out: Outdoor convection coefficient (W/(m^2*K)).
|
| 77 |
+
thickness1: Thickness of layer 1 (m).
|
| 78 |
+
k1: Thermal conductivity of layer 1 (W/(m*K)).
|
| 79 |
+
thickness2: Thickness of layer 2 (m).
|
| 80 |
+
k2: Thermal conductivity of Layer 2 (W/(m*K)).
|
| 81 |
+
T_in: Indoor temperature (Celsius).
|
| 82 |
+
h_in: Indoor convection coefficient (W/(m^2*K)).
|
| 83 |
+
|
| 84 |
+
Returns:
|
| 85 |
+
A pandas DataFrame containing the calculated results.
|
| 86 |
+
"""
|
| 87 |
+
Q, T_outer_surface, T_interface, T_inner_surface = calculate_heat_flow(T_out, h_out, thickness1, k1, thickness2, k2, T_in, h_in)
|
| 88 |
+
|
| 89 |
+
results = {
|
| 90 |
+
"Metric": ["Total Heat Flux (W/m^2)", "Outer Surface Temperature (°C)", "Interface Temperature (°C)", "Inner Surface Temperature (°C)"],
|
| 91 |
+
"Value": [Q, T_outer_surface, T_interface, T_inner_surface]
|
| 92 |
+
}
|
| 93 |
+
return pd.DataFrame(results)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# This helper function applies a chat format to help the LLM understand what
|
| 97 |
+
# is going on
|
| 98 |
+
def _format_chat(system_prompt: str, user_prompt: str) -> str:
|
| 99 |
+
messages = [
|
| 100 |
+
{"role": "system", "content": system_prompt},
|
| 101 |
+
{"role": "user", "content": user_prompt},
|
| 102 |
+
]
|
| 103 |
+
template = getattr(tokenizer, "chat_template", None)
|
| 104 |
+
return tokenizer.apply_chat_template(
|
| 105 |
+
messages,
|
| 106 |
+
tokenize=False,
|
| 107 |
+
add_generation_prompt=True
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# This functoin uses hte LLM to generate a response.
|
| 111 |
+
def _llm_generate(prompt: str, max_tokens: int) -> str:
|
| 112 |
+
out = pipe(
|
| 113 |
+
prompt,
|
| 114 |
+
max_new_tokens=max_tokens,
|
| 115 |
+
do_sample=True,
|
| 116 |
+
temperature=0.8, # Increased temperature for more varied output
|
| 117 |
+
return_full_text=False,
|
| 118 |
+
)
|
| 119 |
+
return out[0]["generated_text"]
|
| 120 |
+
|
| 121 |
+
# This function generates an explanation of the results
|
| 122 |
+
def llm_explain(results: dict, inputs: list) -> str:
|
| 123 |
+
T_out, h_out, thickness1, k1, thickness2, k2, T_in, h_in = inputs
|
| 124 |
+
Q = results["Value"][0]
|
| 125 |
+
T_outer_surface = results["Value"][1]
|
| 126 |
+
T_interface = results["Value"][2]
|
| 127 |
+
T_inner_surface = results["Value"][3]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
system_prompt = (
|
| 131 |
+
"You are a friendly and simple assistant that explains heat transfer in one concise sentence."
|
| 132 |
+
"Focus on the direction of heat flow and the main factor influencing it (like temperature difference or insulation)."
|
| 133 |
+
"Explain if the heat is flowing into the indoor space or not, keep it simple"
|
| 134 |
+
"Also explain how the insulation choice impacts this with simple topics"
|
| 135 |
+
"Avoid technical jargon and complex formulas."
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
user_prompt = (
|
| 139 |
+
f"Given an outdoor temperature of {T_out}°C and an indoor temperature of {T_in}°C,\n"
|
| 140 |
+
f"and a wall with layers having thermal conductivities {k1} W/(m*K) and {k2} W/(m*K),\n"
|
| 141 |
+
f"the total heat flux through the wall is {Q:.2f} W/m^2.\n"
|
| 142 |
+
"Explain this result in one simple sentence."
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
formatted = _format_chat(system_prompt, user_prompt)
|
| 146 |
+
return _llm_generate(formatted, max_tokens=128) # Reduced max_tokens for a more concise response
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# This function ties everythign together (evaluation, LLM explanaation, output)
|
| 150 |
+
# And will be out main entry point for teh GUI
|
| 151 |
+
def run_once(T_out, h_out, thickness1, k1, thickness2, k2, T_in, h_in):
|
| 152 |
+
inputs = [T_out, h_out, thickness1, k1, thickness2, k2, T_in, h_in]
|
| 153 |
+
df = calculate_heat_flow_gr(
|
| 154 |
+
T_out=float(T_out),
|
| 155 |
+
h_out=float(h_out),
|
| 156 |
+
thickness1=float(thickness1),
|
| 157 |
+
k1=float(k1),
|
| 158 |
+
thickness2=float(thickness2),
|
| 159 |
+
k2=float(k2),
|
| 160 |
+
T_in=float(T_in),
|
| 161 |
+
h_in=float(h_in)
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
narrative = llm_explain(df, inputs) # Removed split("\n")[0] to get the full explanation
|
| 165 |
+
return df, narrative
|
| 166 |
+
|
| 167 |
+
# Last but not least, here's the UI!
|
| 168 |
+
with gradio.Blocks() as demo:
|
| 169 |
+
|
| 170 |
+
# Let's start by adding a title and introduction
|
| 171 |
+
gradio.Markdown(
|
| 172 |
+
"# Run and Explain Heat Flow Calcs"
|
| 173 |
+
)
|
| 174 |
+
gradio.Markdown(
|
| 175 |
+
"""
|
| 176 |
+
This app runs a basic heat tranfer calculation between two spaces with two walls. Users can adjust indoor and outdoor
|
| 177 |
+
temperatures and heat transfer coefficients along with wall materials and thicknesses.
|
| 178 |
+
|
| 179 |
+
The calculations work well, but the LLM has issues. I played with the prompting for a while but the large number of inputs
|
| 180 |
+
and small model size made outputs very incosistent. Sometimes they explain the importance of the thickness and material choise and
|
| 181 |
+
other times it will just display the outputs. I couln't fix this, to improve this I would use a larger model with GPU processing.
|
| 182 |
+
|
| 183 |
+
**Goals:**
|
| 184 |
+
* Simulate heat transfer through a composite wall.
|
| 185 |
+
* Calculate heat flux and temperatures at different points in the wall.
|
| 186 |
+
* Provide a simple interface to adjust parameters and see the impact on heat flow.
|
| 187 |
+
|
| 188 |
+
**Assumptions:**
|
| 189 |
+
* One-dimensional steady-state heat transfer.
|
| 190 |
+
* Constant thermal properties of materials.
|
| 191 |
+
* Uniform temperatures and convection coefficients on the surfaces.
|
| 192 |
+
* No internal heat generation.
|
| 193 |
+
"""
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
# Define material thermal conductivities
|
| 197 |
+
material_k = {
|
| 198 |
+
"Wood": 0.12, # Example k value for wood
|
| 199 |
+
"Brick": 0.72, # Example k value for brick
|
| 200 |
+
"Insulation": 0.04 # Example k value for insulation
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
# Create a list of tuples for dropdown choices (label, value)
|
| 204 |
+
material_choices = [(f"{name}: k = {k}", k) for name, k in material_k.items()]
|
| 205 |
+
|
| 206 |
+
# Row for outdoor conditions
|
| 207 |
+
with gradio.Row():
|
| 208 |
+
T_out = gradio.Number(value=0, label="Outdoor Temperature (°C)")
|
| 209 |
+
h_out = gradio.Number(value=25, label="Outdoor Convection Coefficient (W/(m^2*K))")
|
| 210 |
+
|
| 211 |
+
# Rows for wall conditions
|
| 212 |
+
with gradio.Row():
|
| 213 |
+
thickness1 = gradio.Number(value=0.1, label="Thickness of Layer 1 (m)")
|
| 214 |
+
k1 = gradio.Dropdown(material_choices, label="Thermal Conductivity of Layer 1 (W/(m*K))", value=material_k["Wood"])
|
| 215 |
+
|
| 216 |
+
with gradio.Row():
|
| 217 |
+
thickness2 = gradio.Number(value=0.1, label="Thickness of Layer 2 (m)")
|
| 218 |
+
k2 = gradio.Dropdown(material_choices, label="Thermal Conductivity of Layer 2 (W/(m*K))", value=material_k["Wood"])
|
| 219 |
+
|
| 220 |
+
# Row for indoor conditions
|
| 221 |
+
with gradio.Row():
|
| 222 |
+
T_in = gradio.Number(value=20, label="Indoor Temperature (°C)")
|
| 223 |
+
h_in = gradio.Number(value=5, label="Indoor Convection Coefficient (W/(m^2*K))")
|
| 224 |
+
|
| 225 |
+
# Add a button to click to run the interface
|
| 226 |
+
run_btn = gradio.Button("Compute")
|
| 227 |
+
|
| 228 |
+
# These are the outputs. We use both a dataframe (for tabular info) and a markdown box
|
| 229 |
+
# for info from teh LLM
|
| 230 |
+
results_df = gradio.Dataframe(label="Numerical results (deterministic)", interactive=False)
|
| 231 |
+
explain_md = gradio.Markdown(label="Explanation")
|
| 232 |
+
|
| 233 |
+
# Run the calculations when the button is clicked
|
| 234 |
+
run_btn.click(fn=run_once, inputs=[T_out, h_out, thickness1, k1, thickness2, k2, T_in, h_in], outputs=[results_df, explain_md])
|
| 235 |
+
|
| 236 |
+
# Finally, add a few examples
|
| 237 |
+
gradio.Examples(
|
| 238 |
+
examples=[
|
| 239 |
+
[0, 25, 0.1, material_k["Wood"], 0.1, material_k["Wood"], 20, 5],
|
| 240 |
+
[10, 10, 0.2, material_k["Brick"], 0.05, material_k["Insulation"], 22, 8],
|
| 241 |
+
[-5, 30, 0.05, material_k["Insulation"], 0.15, material_k["Brick"], 18, 3],
|
| 242 |
+
],
|
| 243 |
+
inputs=[T_out, h_out, thickness1, k1, thickness2, k2, T_in, h_in],
|
| 244 |
+
label="Representative cases",
|
| 245 |
+
examples_per_page=3,
|
| 246 |
+
cache_examples=False,
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
demo.launch(debug=True)
|