审计真实建筑能耗记录
检查时间戳、传感器单位、能量至功率换算及单栋建筑的观测范围。
目标与运行方法
本课适合具备 Python 基础的本科生。先阅读每一步的方法与图注,再修改参数。AI 练习为可选部分,不需要 AI 账号即可完成核心课程。数据写在 notebook metadata 中,不需要另下载数据文件。请保持 notebook 已保存到当前工作文件夹。
学习任务是理解本课的研究问题、执行透明的计算、校验结果,并说明结论的边界。
环境与参数
from pathlib import Path
import base64, gzip, hashlib, json, platform
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display, HTML
from datetime import datetime
from IPython.display import display as _display
def display(value):
if isinstance(value,pd.DataFrame):
table=value.to_html(max_rows=12,escape=True)
style="<style>.vibeit-readable-table{max-width:100%;overflow-x:auto}.vibeit-readable-table table{width:max-content;max-width:none;border-collapse:collapse}.vibeit-readable-table td,.vibeit-readable-table th{white-space:nowrap!important;word-break:normal!important;overflow-wrap:normal!important}</style>"
return _display(HTML(style+'<div class="vibeit-readable-table">'+table+'</div>'))
return _display(value)
RECIPE_ID='en01-energy-audit'
OUTPUT_DIR=Path.cwd()/"results"/RECIPE_ID
plt.rcParams.update({"figure.dpi":120,"font.size":10,"axes.spines.top":False,"axes.spines.right":False,
"axes.prop_cycle":plt.cycler(color=["#18785f","#416aa6","#bc6541","#9974a5"])})
print("Python:",platform.python_version(),"; NumPy:",np.__version__,"; Pandas:",pd.__version__)
print("Working folder:",Path.cwd())
print("Core data mode: embedded snapshot; no network requests")
Python: 3.13.13 ; NumPy: 2.5.3 ; Pandas: 3.0.6 Working folder: /Users/zhiluo/Developer/vibeit-cookbook/cookbook/downloads Core data mode: embedded snapshot; no network requests
读取内嵌快照
def load_snapshot(recipe_id, expected_sha256, snapshot_key):
"""Read embedded data from this notebook, including a renamed copy."""
for path in sorted(Path.cwd().glob("*.ipynb")):
try:
notebook = json.loads(path.read_text(encoding="utf-8"))
metadata = notebook.get("metadata", {}).get("vibeit_cookbook", {})
blob = metadata.get("snapshots", {}).get(snapshot_key)
if metadata.get("recipe_id") != recipe_id or not blob:
continue
if blob.get("sha256") != expected_sha256:
continue
raw = gzip.decompress(base64.b64decode(blob["gzip_base64"], validate=True))
if hashlib.sha256(raw).hexdigest() != expected_sha256:
raise ValueError("Embedded snapshot checksum mismatch: " + snapshot_key)
return json.loads(raw)
except (OSError, json.JSONDecodeError):
continue
raise FileNotFoundError(
"Save/open the complete .ipynb in the active working folder. "
"The embedded snapshot could not be located for " + recipe_id)
SNAPSHOT_HASHES={'energy': '81117ee0a0706bf416bedc50f23b455ee8dd771e588c91b6a420dc3b184f638f'}
def snapshot(key):
return load_snapshot(RECIPE_ID,SNAPSHOT_HASHES[key],key)
print("Embedded snapshots:",list(SNAPSHOT_HASHES))
Embedded snapshots: ['energy']
方法函数
def audit_numeric_table(frame,columns):
"""Audit observed rows; never silently impute or remove them."""
if frame.empty or frame.index.has_duplicates:
raise ValueError('Expected a nonempty table with unique row IDs')
missing=[name for name in columns if name not in frame.columns]
if missing:raise ValueError('Missing required columns: '+str(missing))
values=frame[columns].to_numpy(dtype=float)
if not np.isfinite(values).all():raise ValueError('Non-finite measurements; inspect missing values explicitly')
return {'rows':len(frame),'features':len(columns),'finite':True,'duplicate_measurement_rows':int(frame[columns].duplicated().sum())}
print("Method ready: audit_numeric_table")
Method ready: audit_numeric_table
def iso_datetimes(values):
"""Parse source ISO dates with the standard library; keep tables as ISO strings."""
return [datetime.fromisoformat(str(value)) for value in values]
print("Method ready: iso_datetimes")
Method ready: iso_datetimes
数据与模型边界
建筑记录包含来源中单栋建筑的真实十分钟能耗及环境观测。机场天气字段含来源插值,不是同位置校准参考。梁、电路和 PID 例子是明确的数值设计模型;计算响应不能证明硬件性能或实际验收。
分步分析
1. 检查时间身份及声明单位
来源记录十分钟内能量 Wh,不是瞬时功率。W=Wh/(10/60 h),因此平均功率数值为能量字段的六倍。时间戳保留来源本地表示,不进行未声明时区转换。
energy=snapshot("energy");frame=pd.DataFrame(energy["rows"],columns=energy["columns"])
frame["timestamp"]=frame["date"].astype(str);frame=frame.sort_values("timestamp").reset_index(drop=True)
assert len(frame)==19735 and frame.timestamp.is_unique
dates=iso_datetimes(frame.timestamp)
assert all((b-a).total_seconds()==600 for a,b in zip(dates,dates[1:]))
audit=audit_numeric_table(frame,["Appliances","lights","T1","RH_1"])
assert frame.Appliances.ge(0).all() and frame.lights.ge(0).all()
frame["appliance_average_power_W"]=frame.Appliances/(600/3600)
print("Observed rows:",len(frame),"; energy: Wh/10 min; derived interval-average power: W; source timezone unspecified")
display(frame[["timestamp","Appliances","appliance_average_power_W","T1","RH_1"]].head(8))
Observed rows: 19735 ; energy: Wh/10 min; derived interval-average power: W; source timezone unspecified
| timestamp | Appliances | appliance_average_power_W | T1 | RH_1 | |
|---|---|---|---|---|---|
| 0 | 2016-01-11 17:00:00 | 60 | 360.0 | 19.890000 | 47.596667 |
| 1 | 2016-01-11 17:10:00 | 60 | 360.0 | 19.890000 | 46.693333 |
| 2 | 2016-01-11 17:20:00 | 50 | 300.0 | 19.890000 | 46.300000 |
| 3 | 2016-01-11 17:30:00 | 50 | 300.0 | 19.890000 | 46.066667 |
| 4 | 2016-01-11 17:40:00 | 60 | 360.0 | 19.890000 | 46.333333 |
| 5 | 2016-01-11 17:50:00 | 50 | 300.0 | 19.890000 | 46.026667 |
| 6 | 2016-01-11 18:00:00 | 60 | 360.0 | 19.890000 | 45.766667 |
| 7 | 2016-01-11 18:10:00 | 60 | 360.0 | 19.856667 | 45.560000 |
2. 检查实测时间模式
展示前七天从能量换算的区间平均家电功率。它是单位换算,不是新增高速电测量,不能解析电网电压/电流波形。
part=frame.iloc[:7*144]
fig,ax=plt.subplots(figsize=(10,4));ax.plot(iso_datetimes(part.timestamp),part.appliance_average_power_W,lw=.8)
ax.set(xlabel="Source-local timestamp",ylabel="Interval-average appliance power (W)",title="Observed ten-minute energy converted to average power");plt.tight_layout();plt.show()
3. 比较日变化分布
按时钟小时分组展示区间能量分布。它们不是独立家庭重复;差异可能混合行为、天气和季节。保留 Wh/区间单位,与前图 W 区分。
hour=np.array([value.hour for value in dates])
fig,ax=plt.subplots(figsize=(10,4));ax.boxplot([frame.loc[hour==h,"Appliances"] for h in range(24)],tick_labels=range(24),showfliers=False)
ax.set(xlabel="Source-local clock hour",ylabel="Energy (Wh per 10-minute interval)",title="Observed diurnal distributions; outlier markers hidden only in this drawing");plt.tight_layout();plt.show()
4. 解读环境观测
厨房温湿度散点描述单栋建筑中的测量关联,不能校准电能表,也不确定因果控制规则。湿度为百分比,温度为摄氏度。
fig,ax=plt.subplots(figsize=(7,5));im=ax.scatter(frame.T1,frame.RH_1,c=frame.Appliances,s=5,alpha=.3,cmap="viridis")
ax.set(xlabel="Kitchen temperature (°C)",ylabel="Kitchen relative humidity (%)",title="Observed environmental association")
fig.colorbar(im,ax=ax,label="Appliance energy (Wh/interval)");plt.tight_layout();plt.show()
5. 核对能量总计并导出审计
对 Wh 求和得到观测区间总能量。将平均 W 乘精确区间时长后求和,应恢复相同总量。导出保留时间间隔及原始值。
total_Wh=float(frame.Appliances.sum());integrated_Wh=float((frame.appliance_average_power_W*(600/3600)).sum())
assert np.isclose(total_Wh,integrated_Wh)
OUTPUT_DIR.mkdir(parents=True,exist_ok=True)
frame[["timestamp","Appliances","appliance_average_power_W","T1","RH_1"]].to_csv(OUTPUT_DIR/"observed-energy-audit.csv",index=False)
(OUTPUT_DIR/"units-and-cadence.json").write_text(json.dumps({"rows":len(frame),"interval_seconds":600,"original_energy_unit":"Wh per interval","derived_power_unit":"W interval average","total_observed_Wh":total_Wh,"timezone":"source unspecified; no conversion"},indent=2))
print("Energy reconciliation passed; exports:",OUTPUT_DIR)
Energy reconciliation passed; exports: /Users/zhiluo/Developer/vibeit-cookbook/cookbook/downloads/results/en01-energy-audit
自主练习与参考答案
- 将十分钟 100 Wh 换为区间平均 W。
- 为何连续观测不代表独立建筑?
参考解释。 区间平均为 600 W。记录跟踪同一栋建筑,家庭推广和观测独立性需要额外设计证据。
先保留当前 notebook 副本,再修改参数。把新图与原图一起比较,并记录改变了哪些输入、哪些计算和哪些结论。
可选的 AI 编程练习
提示词 1
仅用 NumPy、Pandas、Matplotlib 增加日观测能量总计及完整区间数量。
提示词 2
使用同样的包比较厨房与客厅温度,不将任一方称为仪器校准参考。
人工验收。 间隔仍为十分钟,保留原 Wh 数据,派生功率/能量单位明确。
检查修改后的源代码,再手动运行受影响单元及后续校验。要求助手解释修改的目的、使用的包和数据来源,并用实际输出核对解释。
可选联网扩展
RUN_ONLINE_UPDATE=False
if RUN_ONLINE_UPDATE:
import requests
try:
response=requests.get('https://archive.ics.uci.edu/dataset/374/appliances+energy+prediction',timeout=20)
response.raise_for_status()
print("Source:",response.url)
print(response.text[:700])
except requests.RequestException as error:
print("Online extension unavailable:",type(error).__name__,str(error)[:160])
else:
print("Online extension skipped; embedded core data unchanged")
Online extension skipped; embedded core data unchanged
来源、快照与下一步
- UCI energy — CC BY 4.0; credit UCI and original dataset authors; retrieved 2026-10-09. SHA-256
2fccf354445d886e7917620b0195db1f3e3e34d5a067a93b844694a4c561255a. Extract energydata_complete.csv from original download; preserve all rows and declared units; no imputation. Candanedo, L. (2017). Appliances Energy Prediction. UCI Machine Learning Repository. DOI: 10.24432/C5VC8G.
下一步。 在保留本课的数据检查、参数记录和结果校验之后,将相同方法用于自己的公开或已获授权数据。记录研究设计与方法限制,不把示例结果当成新实验的验证。完整数据许可与生成说明见 cookbook 网页。