SPB Git

Repository Public

MonteCarloEditor.swift 6.9 KB 146 lines swift

1import SwiftUI2import SheetCore3import SheetUI4import AnalysisKit56/// Editor of the input distributions of a simulation. The bindings live as JSON in the form values ("bindings").7struct MonteCarloEditor: View {8    let session: WorkbookSession9    @Binding var values: FormValues10    @Environment(\.compactForm) private var compact1112    private var bindings: [MCBinding] { MCBinding.decode(values.text("bindings")) }13    private func store(_ list: [MCBinding]) { values.set("bindings", text: MCBinding.encode(list)) }1415    private func binding(_ id: UUID) -> Binding<MCBinding> {16        Binding(get: { bindings.first { $0.id == id } ?? MCBinding() },17                set: { new in var list = bindings; if let i = list.firstIndex(where: { $0.id == id }) { list[i] = new; store(list) } })18    }1920    var body: some View {21        let list = bindings22        VStack(alignment: .leading, spacing: 8) {23            HStack(spacing: 8) {24                Text(L("Input distributions").uppercased())25                    .font(.system(size: 10.5, weight: .semibold)).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)26                    .accessibilityAddTraits(.isHeader)27                Spacer(minLength: 0)28                Text(L("%d inputs", list.count)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)29            }30            if list.isEmpty {31                Text(L("No input yet. Select the input cells of the model in the sheet, then choose Add Selected Cells: each one starts as a normal distribution centred on its current value (standard deviation 10 %)."))32                    .font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)33                    .padding(10)34                    .frame(maxWidth: .infinity, alignment: .leading)35                    .background(RoundedRectangle(cornerRadius: ORIX.Radius.control).fill(ORIX.Palette.surfaceRaised.opacity(0.6)))36            }37            ForEach(Array(list.enumerated()), id: \.element.id) { index, item in38                MonteCarloBindingRow(binding: binding(item.id), index: index, session: session, compact: compact) {39                    store(bindings.filter { $0.id != item.id })40                }41            }42            HStack(spacing: 8) {43                Button {44                    store(bindings + MCBinding.fromSelection(session, existing: bindings))45                } label: { Label(L("Add Selected Cells"), systemImage: "scope") }46                    .help(L("Adds the selected numeric input cells, each as a normal distribution centred on its current value"))47                    .accessibilityIdentifier("montecarlo.add-selection")48                Button {49                    store(bindings + [MCBinding()])50                } label: { Label(L("Add Input"), systemImage: "plus") }51                    .accessibilityIdentifier("montecarlo.add-input")52            }53            .controlSize(.small)54        }55        .accessibilityElement(children: .contain)56        .accessibilityLabel(L("Input distributions"))57    }58}5960private struct MonteCarloBindingRow: View {61    @Binding var binding: MCBinding62    let index: Int63    let session: WorkbookSession64    let compact: Bool65    let remove: () -> Void6667    var body: some View {68        VStack(alignment: .leading, spacing: 6) {69            HStack(spacing: 6) {70                TextField(L("Cell"), text: $binding.cell)71                    .textFieldStyle(.roundedBorder).font(ORIX.Typeface.mono).frame(width: compact ? 92 : 110)72                    .accessibilityLabel(L("Input %d, cell", index + 1))73                    .accessibilityIdentifier("montecarlo.input\(index).cell")74                TextField(placeholderName, text: $binding.name)75                    .textFieldStyle(.roundedBorder).frame(minWidth: 60, maxWidth: 220)76                    .accessibilityLabel(L("Input %d, name", index + 1))77                if !compact { kindPicker }78                Spacer(minLength: 0)79                Button(action: remove) { Image(systemName: "minus.circle") }80                    .buttonStyle(.borderless)81                    .help(L("Remove this input"))82                    .accessibilityLabel(L("Remove input %d", index + 1))83                    .accessibilityIdentifier("montecarlo.input\(index).remove")84            }85            if compact { kindPicker }86            parameters87        }88        .padding(8)89        .background(RoundedRectangle(cornerRadius: ORIX.Radius.control).fill(ORIX.Palette.surfaceRaised.opacity(0.55)))90        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control).strokeBorder(ORIX.Palette.hairline.opacity(0.7)))91    }9293    private var placeholderName: String {94        guard let c = RangeReader.cells(binding.cell, workbook: session.workbook, sheet: session.sheetIndex)?.first else { return L("Name") }95        return WhatIfSupport.name(c, in: session.workbook)96    }9798    private var kindPicker: some View {99        Picker(L("Distribution"), selection: Binding(get: { binding.kind }, set: { binding.convert(to: $0) })) {100            ForEach(MCBinding.Kind.allCases) { Text($0.title).tag($0) }101        }102        .labelsHidden().fixedSize()103        .accessibilityLabel(L("Input %d, distribution", index + 1))104        .accessibilityIdentifier("montecarlo.input\(index).kind")105    }106107    @ViewBuilder private var parameters: some View {108        if binding.kind == .discrete {109            VStack(alignment: .leading, spacing: 4) {110                labelled(L("Values")) {111                    TextField(L("e.g. 10; 20; 30"), text: $binding.valuesText).textFieldStyle(.roundedBorder).frame(maxWidth: 260)112                        .accessibilityLabel(L("Input %d, values", index + 1))113                }114                labelled(L("Probabilities")) {115                    TextField(L("e.g. 0.2; 0.5; 0.3 (empty = equal)"), text: $binding.probabilitiesText).textFieldStyle(.roundedBorder).frame(maxWidth: 260)116                        .accessibilityLabel(L("Input %d, probabilities", index + 1))117                }118            }119        } else {120            let names = binding.kind.parameters121            FlowLayout(spacing: 8) {122                ForEach(Array(names.enumerated()), id: \.offset) { i, name in123                    labelled(name) {124                        NumberField(label: L("Input %d, %@", index + 1, name), value: parameter(i), identifier: "montecarlo.input\(index).p\(i + 1)", width: compact ? 70 : 96)125                    }126                }127            }128        }129    }130131    private func parameter(_ i: Int) -> Binding<Double> {132        switch i {133        case 0: $binding.p1134        case 1: $binding.p2135        default: $binding.p3136        }137    }138139    private func labelled<C: View>(_ label: String, @ViewBuilder _ content: () -> C) -> some View {140        VStack(alignment: .leading, spacing: 2) {141            Text(label).font(.system(size: 10.5, weight: .medium)).foregroundStyle(ORIX.Palette.textTertiary)142            content()143        }144    }145}146
Files main
Menu

Theme