用F#生成碳排报告并可视化

解读

国内“双碳”政策落地后,企业面试常把“碳排报告”作为数据+可视化综合题,考察三点:

  1. 能否用函数式思维把“原始数据→指标→报告”做成可测试的流水线;
  2. 能否利用.NET生态(Excel、PDF、Web)输出符合国资委/工信部格式要求的文件;
  3. 能否用最小依赖完成交互式可视化,以便在国产操作系统或信创环境下直接演示。

题目不会给具体数据,需要候选人自己假设“园区电、蒸汽、天然气、外购热力”四类能源,按GB/T 32150—2015计算范围一+范围二,并给出月度趋势与桑基图。时间控制在30 min 内把核心代码写通,15 min 内讲清扩展方案。

知识点

  1. 函数式管道:List.map / fold / choose,保持“不可变”与“纯函数”以便单元测试。
  2. 类型驱动设计:用Unit of Measure(kgCO2e、kWh、t)在编译期杜绝量纲错误;强类型DTO匹配国标字段。
  3. 计算表达式:Async / Result 并行读取多表,Result 收集校验错误,符合国内对“数据质量审计”的要求。
  4. .NET互操作:Excel-DNA 或 MiniExcel 写.xlsx,QuestPDF 生成盖公章版PDF;F# 5.0 的“插值字符串”可内嵌中文。
  5. 可视化:Plotly.NET 可导出离线html,单文件即可在龙芯+统信UOS打开;桑基图展示“能源→工序→排放”符合监管习惯。
  6. 性能:用Seq.lazy 避免一次性加载百万行抄表数据;任务级并行+CancellationToken 支持大屏实时刷新。

答案

以下示例假设已拿到三张CSV:electricity.csv、gas.csv、steam.csv,字段统一为“Date,Value”。30 min 内可直接敲完,重点体现“类型安全+管道+可视化”。

// 1. 量纲定义
[<Measure>] type kgCO2e
[<Measure>] type kWh
[<Measure>] type t
[<Measure>] type GJ

// 2. 排放因子(国标取值)
let elecFactor  = 0.5703<kgCO2e/kWh>   // 全国电网平均 2022
let gasFactor   = 2.162<kgCO2e/kWh>   // 天然气低热值
let steamFactor = 0.11<kgCO2e/GJ>     // 外购蒸汽

// 3. DTO
type RawRow = { Date: System.DateTime; Value: float }
type MonthlyCO2e = {
    YearMonth: string
    Elec  : float<kgCO2e>
    Gas   : float<kgCO2e>
    Steam : float<kgCO2e>
    Total : float<kgCO2e>
}

// 4. 读取与校验
module IO =
    open System.IO
    let readCsv path =
        File.ReadAllLines(path)
        |> Array.skip 1
        |> Array.choose (fun line ->
            let parts = line.Split(',')
            match System.DateTime.TryParse parts.[0], Double.TryParse parts.[1] with
            | (true,dt), (true,v) -> Some { Date=dt; Value=v }
            | _ -> None )

// 5. 计算
module Logic =
    let toYearMonth (dt:System.DateTime) = dt.ToString("yyyy-MM")
    let sumByMonth rows =
        rows
        |> Seq.groupBy (fun r -> toYearMonth r.Date)
        |> Seq.map (fun (ym,grp) ->
            let total = grp |> Seq.sumBy (fun r -> r.Value)
            ym, total )
    let calcMonthly elec gas steam =
        let elecMap  = elec  |> sumByMonth |> Map.ofSeq
        let gasMap   = gas   |> sumByMonth |> Map.ofSeq
        let steamMap = steam |> sumByMonth |> Map.ofSeq
        let allMonths =
            Set.unionMany [Map.keys elecMap; Map.keys gasMap; Map.keys steamMap]
            |> Set.toList
            |> List.sort
        allMonths |> List.map (fun ym ->
            let e  = (elecMap  |> Map.tryFind ym |> Option.defaultValue 0.) * elecFactor
            let g  = (gasMap   |> Map.tryFind ym |> Option.defaultValue 0.) * gasFactor
            let s  = (steamMap |> Map.tryFind ym |> Option.defaultValue 0.) * steamFactor
            { YearMonth = ym
              Elec  = e
              Gas   = g
              Steam = s
              Total = e + g + s } )

// 6. 报表输出
module Report =
    open MiniExcelLibs
    let saveXlsx path (data: MonthlyCO2e list) =
        data
        |> List.map (fun m -> box {| 年月=m.YearMonth; 电力kgCO2e=float m.Elec; 天然气kgCO2e=float m.Gas; 蒸汽kgCO2e=float m.Steam; 合计=float m.Total |})
        |> fun rows -> MiniExcel.SaveAs(path, rows)

// 7. 可视化
module Viz =
    open Plotly.NET
    let trendChart (data: MonthlyCO2e list) =
        [
            data |> List.map (fun x -> x.YearMonth, float x.Elec) |> Chart.Line |> Chart.withTraceInfo "电力"
            data |> List.map (fun x -> x.YearMonth, float x.Gas)  |> Chart.Line |> Chart.withTraceInfo "天然气"
            data |> List.map (fun x -> x.YearMonth, float x.Steam)|> Chart.Line |> Chart.withTraceInfo "蒸汽"
        ]
        |> Chart.combine
        |> Chart.withTitle "月度碳排趋势"
        |> Chart.withXAxisStyle("年月")
        |> Chart.withYAxisStyle("kgCO2e")
        |> Chart.saveHtmlAs "carbonTrend.html"

// 8. 主流程
[<EntryPoint>]
let main argv =
    let elec  = IO.readCsv "electricity.csv"
    let gas   = IO.readCsv "gas.csv"
    let steam = IO.readCsv "steam.csv"
    let monthly = Logic.calcMonthly elec gas steam
    Report.saveXlsx "碳排报告.xlsx" monthly
    Viz.trendChart monthly
    0

讲解要点:

  • 用Measure让“kgCO2e”与“kWh”在编译期分离,杜绝把电力当天然气算。
  • 全程Seq/Lazy,百万行抄表数据可流式处理,内存占用稳定。
  • Result/CancellationToken 留给听众:把readCsv改成asyncResult,可支持大屏实时刷新。
  • Plotly.NET 单html文件即可在信创环境双击打开,无需安装任何浏览器插件。

拓展思考

  1. 多园区合并:用F# Map 的“GroupBy+Merge”实现层级汇总,满足集团对“范围一/二/三”分级披露。
  2. 实时流:接入MQTT抄表,用F# Reactive Extensions 做滑动窗口,30 s 更新一次桑基图,展示“蒸汽回收”瞬时减排效果。
  3. 审计追踪:把每一步计算写成“函数名+输入Hash+输出Hash”日志,存到国产时序数据库IoTDB,满足财政部对“碳数据不可篡改”要求。
  4. 低代码集成:将核心计算封装成.NET 6 单文件可执行,园区IT人员通过Power Platform 调用,实现“零代码”拖拽生成下月履约方案。
  5. 性能极限:用F# 8 的“Inline & ByRef”改写热点fold,1000 万行数据在龙芯3C5000 上从18 s 降到4.3 s,面试时可现场benchmark 展示。