diff --git a/README.md b/README.md index 7c11185..d9c153a 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,8 @@ bundle exec boss help [COMMAND] - `-w`, `--epw_path` (optional): path to a weather `.epw` file, relative to the current working directory or absolute; BOSS stores it as an absolute path in the generated OSW. If omitted, BOSS derives weather from the BuildingSync file when possible - `-v`, `--standard_version` (optional): modeling standard used by BOSS, such as `ASHRAE90.1` or `CaliforniaTitle24` (defaults to `ASHRAE90.1`) - `-r`, `--run` (optional, `write_baseline_osw` only): run the baseline workflow after writing the OSW +- `--require_l200` (optional, `write_baseline_osw` only): fail instead of falling back to `create_typical_building_from_model` HVAC when the BuildingSync HVAC records cannot be mapped to the split HVAC measures +- `--[no-]allow_approximations` (optional, `write_baseline_osw` only, default on): accept HVAC records that BOSS models by policy or as an approximation, such as ComStock heat or energy recovery, and log them as warnings. `--no-allow_approximations` keeps the mapping document's blocking rules for those records. Records that name no separate ventilation equipment or integrate outdoor air with the conditioning system do not block when their `LinkedDeliveryIDs` resolve to conditioned deliveries (mapping document rows 88 and 89). Every note is listed in `baseline/hvac_mapping_report.json`. Combine `--no-allow_approximations --require_l200` for a run that uses the audited HVAC exactly as the mapping document allows, or fails ### CLI Example: Write a baseline OSW diff --git a/lib/BOSS/baseline_hvac_planner.rb b/lib/BOSS/baseline_hvac_planner.rb index 46cea7f..24a625f 100644 --- a/lib/BOSS/baseline_hvac_planner.rb +++ b/lib/BOSS/baseline_hvac_planner.rb @@ -30,12 +30,37 @@ class BaselineHvacPlanner RECOVERY_HOST_MEASURES = ['hvac_packaged_rooftop_ac', 'hvac_packaged_rooftop_heat_pump', 'hvac_warm_air_furnace', 'hvac_packaged_rooftop_vav_hw_reheat', 'hvac_vav_hw_reheat'].freeze - Plan = Struct.new(:status, :steps, :messages, keyword_init: true) do + WARN_BASES = [:policy, :approximation].freeze + + # messages are the fallback reasons (empty on a topology plan). notes are the selector results + # worth reporting on either path: non-blocking records, and matches that carry a basis or a message. + Plan = Struct.new(:status, :steps, :messages, :notes, keyword_init: true) do + def initialize(notes: [], **members) + super(notes:, **members) + end + def topology? = status == :topology + + # Notes deduplicated by configuration, status, basis and text, listing every record ID. + # A match on a fallback plan built nothing, so it is marked as not applied. + # @return [Array] { level: :info | :warn, basis:, applied:, text: } + def note_entries + notes.group_by { |n| [n.configuration || n.hvac_system_id, n.status, n.basis, n.messages] }.map do |(label, status, basis, messages), members| + applied = members.first.status != :match || topology? + kind = [status, basis].compact.join(', ') + ids = members.flat_map(&:record_ids).uniq + text = "#{label} (#{kind}; #{ids.join(', ')}): #{messages.join(' ')}" + text += ' (not applied)' unless applied + { level: WARN_BASES.include?(basis) ? :warn : :info, basis:, applied:, text: } + end + end end - def initialize(selector: HvacTopologySelector.new, binder: HvacTargetBinder.new) - @selector = selector + # @param selector [HvacTopologySelector, nil] defaults to one built with allow_approximations + # @param allow_approximations [Boolean] whether records BOSS accepts by policy or as an + # approximation are allowed; when false they keep the mapping doc's blocking status + def initialize(selector: nil, binder: HvacTargetBinder.new, allow_approximations: true) + @selector = selector || HvacTopologySelector.new(allow_approximations:) @binder = binder end @@ -59,15 +84,21 @@ def plan(hvac_systems, standards_template, operation: 'create', include_system_i end return fallback(['No HVACSystem records.']) if results.empty? - unmatched = results.reject { |result| result.status == :match } - return fallback(unmatched.map { |result| describe(result, result.status, result.messages) }) if !unmatched.empty? + # Notes are collected before merge, which keeps only the first member of a group. + notes = results.select { |result| !result.blocking? || (result.status == :match && (result.basis || !result.messages.empty?)) } + matches = results.select { |result| result.status == :match } + blocking = results.select { |result| result.status != :match && result.blocking? } + return fallback(blocking.map { |result| describe(result, result.status, result.messages) }, notes) if !blocking.empty? - recovery, results = results.partition { |result| result.measure == RECOVERY_MEASURE } + recovery, results = matches.partition { |result| result.measure == RECOVERY_MEASURE } groups = results.group_by { |result| [result.measure, result.measure_arguments || {}] }.values .map { |members| merge(members, hvac_systems) } ventilation, conditioning = groups.partition { |result| VENTILATION_MEASURES.include?(result.measure) } problems = [] - if conditioning.length != 1 + if conditioning.empty? + only_notes = ventilation.empty? && recovery.empty? + problems << "Expected one conditioning configuration, found 0#{'; the HVAC records carry only notes' if only_notes}." + elsif conditioning.length > 1 problems << "Expected one conditioning configuration, found #{conditioning.length}; " \ 'zone-level binding is not supported.' end @@ -77,19 +108,21 @@ def plan(hvac_systems, standards_template, operation: 'create', include_system_i "#{conditioning.first.configuration} air loops." end problems += recovery_problems(recovery, results, conditioning, ventilation, hvac_systems) if !recovery.empty? - return fallback(problems) if !problems.empty? + return fallback(problems, notes) if !problems.empty? bindings = conditioning.map { |result| [result, @binder.bind(result, operation:, standards_template:)] } + ventilation.map { |result| [result, @binder.bind(result, operation: 'create', standards_template:)] } unbound = bindings.reject { |_, binding| binding.status == :bound } - return fallback(unbound.map { |result, binding| describe(result, binding.status, binding.messages) }) if !unbound.empty? + if !unbound.empty? + return fallback(unbound.map { |result, binding| describe(result, binding.status, binding.messages) }, notes) + end sizing_step = { measure_dir_name: SIZING_MEASURE, arguments: { standards_template: } } steps = bindings.map { |_, binding| binding.step } + [sizing_step] steps << { measure_dir_name: RECOVERY_MEASURE, arguments: {} } if !recovery.empty? # ComStock picks HRV or ERV by climate zone; an audited ERV gets ComStock's ERV values. steps << ERV_STEP if recovery.any? { |r| r.measure_arguments['ventilation_type'] == ERV_TYPE } - Plan.new(status: :topology, steps:, messages: (results + recovery).flat_map(&:messages).uniq) + Plan.new(status: :topology, steps:, messages: [], notes:) end # @return [Array] HVACSystem IDs that measures name as alternatives or modified systems @@ -185,8 +218,8 @@ def merge(members, hvac_systems) merged end - def fallback(messages) - Plan.new(status: :fallback, steps: [], messages:) + def fallback(messages, notes = []) + Plan.new(status: :fallback, steps: [], messages:, notes:) end def describe(result, status, messages) diff --git a/lib/BOSS/boss.rb b/lib/BOSS/boss.rb index 0b67214..3547a53 100644 --- a/lib/BOSS/boss.rb +++ b/lib/BOSS/boss.rb @@ -23,8 +23,11 @@ class Boss # @param epw_file_path [String] if provided, full/path/to/my.epw # @param standard_to_be_used [String] # @param require_l200 [Boolean] raise instead of falling back to create_typical HVAC + # @param allow_approximations [Boolean] allow HVAC records BOSS accepts by policy or as an + # approximation (logged at WARN); false keeps the mapping doc's blocking status for them class << self - def write_baseline_osw(xml_file_path, output_dir, epw_file_path, standard_to_be_used, require_l200: false) + def write_baseline_osw(xml_file_path, output_dir, epw_file_path, standard_to_be_used, require_l200: false, + allow_approximations: true) # check file exists if !File.exist?(xml_file_path) message = "File '#{xml_file_path}' does not exist" @@ -37,7 +40,7 @@ def write_baseline_osw(xml_file_path, output_dir, epw_file_path, standard_to_be_ bsync_doc = REXML::Document.new(xml_data, ignore_whitespace_nodes: :all) bsync_reader = BOSS::BuildingSyncReader.new(bsync_doc, epw_file_path, standard_to_be_used) - hvac_plan = plan_baseline_hvac(bsync_reader) + hvac_plan = plan_baseline_hvac(bsync_reader, allow_approximations:) if require_l200 && !hvac_plan.topology? message = "L200 HVAC topology required but the baseline would fall back: #{hvac_plan.messages.join(' ')}" OpenStudio.logFree(OpenStudio::Error, 'BOSS.write_baseline_osw', message) @@ -52,8 +55,9 @@ def write_baseline_osw(xml_file_path, output_dir, epw_file_path, standard_to_be_ File.open(osw_path, 'w') do |file| file << JSON.pretty_generate(baseline_osw) end - report = { status: hvac_plan.status, hvac_steps: hvac_plan.steps.map { |step| step[:measure_dir_name] }, - messages: hvac_plan.messages } + report = { status: hvac_plan.status, allow_approximations:, + hvac_steps: hvac_plan.steps.map { |step| step[:measure_dir_name] }, + messages: hvac_plan.messages, notes: hvac_plan.note_entries } File.write(File.join(workflow_dir, 'hvac_mapping_report.json'), JSON.pretty_generate(report)) osw_path end @@ -81,9 +85,9 @@ def run_baseline_osw(osw_dir) private - def plan_baseline_hvac(bsync_reader) + def plan_baseline_hvac(bsync_reader, allow_approximations: true) hvac_systems = bsync_reader.get_hvac_systems_xml - BaselineHvacPlanner.new + BaselineHvacPlanner.new(allow_approximations:) .plan(hvac_systems, bsync_reader.get_standard_template, exclude_system_ids: BaselineHvacPlanner.proposed_system_ids(hvac_systems)) end @@ -108,6 +112,10 @@ def build_baseline_osw(bsync_reader, hvac_plan: plan_baseline_hvac(bsync_reader) BOSS.BOSS_logger.warn("BOSS.Boss: Keeping create_typical_building_from_model HVAC: #{message}") end end + # Interim note logging; D4 moves this into the planning log block. + hvac_plan.note_entries.each do |note| + BOSS.BOSS_logger.send(note[:level], "BOSS.Boss: HVAC note: #{note[:text]}") + end OSWArgPopulator::populate_set_lighting_loads_by_LPD_args(baseline_osw, bsync_reader) OSWArgPopulator::populate_set_electric_equipment_loads_by_epd_args(baseline_osw, bsync_reader) diff --git a/lib/BOSS/hvac_topology_selector.rb b/lib/BOSS/hvac_topology_selector.rb index 8727a12..bd5fc38 100644 --- a/lib/BOSS/hvac_topology_selector.rb +++ b/lib/BOSS/hvac_topology_selector.rb @@ -19,10 +19,20 @@ module BOSS class HvacTopologySelector STATUSES = [:match, :mapping_gap, :not_mappable, :missing_input, :conflicting_input, :no_hvac, :integrated].freeze + # Why a result may go ahead without being a plain match: + # :doc - the mapping doc says the record does not block the conditioning match (rows 88-89) + # :policy - BOSS accepts something the doc calls not mappable; needs allow_approximations + # :approximation - a match that builds a measure the doc calls a mapping gap; needs allow_approximations + BASES = [:doc, :policy, :approximation].freeze + # measure_arguments holds topology-measure arguments derived from the data (beyond operation, # zones, and template), e.g. { 'supplemental_heating_fuel' => 'NaturalGas' }. + # blocking is nil (blocking) unless a reviewed branch sets it to false; a non-blocking result is a + # note that never stops the plan. basis says why a non-blocking result or a departing match is allowed. Result = Struct.new(:status, :configuration, :measure, :hvac_system_id, :record_ids, :premises, - :group_key, :messages, :measure_arguments, keyword_init: true) + :group_key, :messages, :measure_arguments, :blocking, :basis, keyword_init: true) do + def blocking? = blocking != false + end # Element accessors and predicates for one Delivery. Paths are '/'-separated local names, # so namespace prefixes do not matter. @@ -428,6 +438,13 @@ def conditioned } ].freeze + # A match row without :absent and :guards would raise NoMethodError in _select_delivery. + DELIVERY_RULES.each do |rule| + next if rule[:status] != :match || (rule.key?(:absent) && rule.key?(:guards)) + + raise ArgumentError, "DELIVERY_RULES match row '#{rule[:configuration]}' needs :absent and :guards" + end + # Configurations the gem cannot generate. Each takes a Context and returns true on a hit. NOT_MAPPABLE_DELIVERY = [ ['Split DX air conditioner', ->(x) { x.eq(x.dx, 'DXSystemType', 'Split DX air conditioner') }], @@ -519,6 +536,12 @@ def self.central_air_absent(x) 'electric_baseboard' => 'Electric baseboard with cooling-only PTAC' }.freeze + # @param allow_approximations [Boolean] when false, records BOSS accepts by policy or as an + # approximation keep the mapping doc's blocking status (:not_mappable, :missing_input, :mapping_gap) + def initialize(allow_approximations: true) + @allow_approximations = allow_approximations + end + # @param hvac_systems [REXML::Element] an HVACSystems element (or any parent of HVACSystem elements) # @return [Array] def select(hvac_systems) @@ -560,14 +583,6 @@ def _select_system(sys) open = deliveries.reject { |d| ventilation_links.key?(d.attributes['ID']) || folded.key?(d.attributes['ID']) } pair, paired_ids = _heating_with_terminal_cooling(sys, open, index) paired_ids ||= [] - annotations, others = others.partition do |other| - links = Context.nodes(other, 'LinkedDeliveryIDs/LinkedDeliveryID').map { |l| l.attributes['IDref'] } - !paired_ids.empty? && _ventilation_annotation?(other) && !links.empty? && (links - paired_ids).empty? - end - unless annotations.empty? - pair.record_ids |= annotations.map { |o| o.attributes['ID'] } - pair.messages << 'MechanicalVentilation without a VentilationType names no separate ventilation equipment.' - end results = open.reject { |d| paired_ids.include?(d.attributes['ID']) } .map { |delivery| _select_delivery(sys, delivery, index) } [pair].compact + results + others.map { |other| _select_other(sys, other, index, ventilation_links, folded) } @@ -675,15 +690,33 @@ def _economizer_only?(delivery) names.include?('AirSideEconomizer') && (names - ECONOMIZER_ONLY_CHILDREN).empty? end - # A record whose only content is MechanicalVentilation with VentilationType None or no type - # (optionally DemandControlVentilation) names no ventilation equipment. - def _ventilation_annotation?(other) + # Doc row 89: a MechanicalVentilation record with VentilationType None or no type names no + # ventilation equipment. 'Unknown' is read as untyped (by policy; the doc names only None and + # absent). Every other MechanicalVentilation child (rates, DCV, controls, capacity, makeup-air + # source) is an unmapped property the topology match does not transfer (doc line 101). + # @return [Symbol, nil] :none, :untyped, :unknown, or nil when the record is not a row 89 record + def _row89_type(other) type_node = Context.nodes(other, 'OtherHVACType').first - return false if type_node.nil? || type_node.elements.to_a.map(&:name) != ['MechanicalVentilation'] + return nil if type_node.nil? || type_node.elements.to_a.map(&:name) != ['MechanicalVentilation'] - mv = type_node.elements.to_a.first - (mv.elements.to_a.map(&:name) - ['VentilationType', 'DemandControlVentilation']).empty? && - [[], ['None']].include?(Context.texts(mv, 'VentilationType')) + case Context.texts(type_node.elements.to_a.first, 'VentilationType') + when [] then :untyped + when ['None'] then :none + when ['Unknown'] then :unknown + end + end + + # Unmapped MechanicalVentilation properties, named in a note so the reader sees what was ignored. + def _ignored_ventilation_properties(other) + mv = Context.nodes(other, 'OtherHVACType/MechanicalVentilation').first + return [] if mv.nil? + + (mv.elements.to_a.map(&:name) - ['VentilationType']).uniq + end + + def _ignored_suffix(other) + ignored = _ignored_ventilation_properties(other) + ignored.empty? ? '' : " Not transferred: #{ignored.map { |p| "MV/#{p}" }.join(', ')}." end # Outdoor air delivered through the linked deliveries' own air system, not separate equipment. @@ -753,10 +786,21 @@ def _select_recovery(sys, other, index, linked_ids, premises, folded) failures << 'Guard failed: O/PrimaryFuel' unless x_probe.guard(other, 'PrimaryFuel', ELECTRIC) return _result(:conflicting_input, sys_id, ids, premises, nil, failures, configuration: RECOVERY_CONFIGURATION) unless failures.empty? + # Doc row 83 calls recovery not mappeable in buildingsync-measures-gem; BOSS models it with + # ComStock's upgrade measure by policy. + unless @allow_approximations + return _result(:not_mappable, sys_id, ids, premises, nil, + ["#{RECOVERY_CONFIGURATION}: no buildingsync-measures-gem measure (mapping doc row 83); " \ + 'BOSS models it with ComStock only when approximations are allowed.'], + configuration: RECOVERY_CONFIGURATION) + end + + messages << 'Modeled with the ComStock recovery measure, which buildingsync-measures-gem does not provide ' \ + '(mapping doc row 83).' # ComStock takes no arguments; ventilation_type tells the planner whether to override # ComStock's climate-zone HRV/ERV choice. _result(:match, sys_id, ids, premises, [:recovery, other.attributes['ID']], messages, - configuration: RECOVERY_CONFIGURATION, measure: RECOVERY_MEASURE, + configuration: RECOVERY_CONFIGURATION, measure: RECOVERY_MEASURE, basis: :policy, measure_arguments: { 'ventilation_type' => (Context.texts(mv, 'VentilationType') & RECOVERY_TYPES).first }) end @@ -764,14 +808,21 @@ def _explicit_no_hvac?(x) !x.d.nil? && x.exists(x.h, 'NoHeating') && x.exists(x.c, 'NoCooling') && x.absent(x.d, 'DeliveryType') end - # Ventilation annotations own their linked deliveries only when every one is explicitly - # unconditioned; otherwise those deliveries are still evaluated as conditioning deliveries. + # Row 89 records own their linked deliveries only when every one is explicitly unconditioned; + # otherwise those deliveries are still evaluated as conditioning deliveries, so a record with + # extra MechanicalVentilation children cannot hide the conditioning match. Integrated and + # recovery records never own their deliveries. Other equipment records (spot exhaust, air + # cleaners, ...) still do; their results block, so the plan falls back either way. + # TODO: when those become non-blocking notes (D1 cheap win 8), apply the row 89 rule to them too. def _consumes_deliveries?(sys, other, index) return false if _integrated?(other) || _recovery?(sys, other, index) - return true unless _ventilation_annotation?(other) + return true if _row89_type(other).nil? ids = Context.nodes(other, 'LinkedDeliveryIDs/LinkedDeliveryID').map { |l| l.attributes['IDref'] } - !ids.empty? && ids.all? { |id| _explicit_no_hvac?(Context.new(sys, index[:delivery][id], index)) } + !ids.empty? && ids.all? do |id| + delivery = index[:delivery][id] + !delivery.nil? && _explicit_no_hvac?(Context.new(sys, delivery, index)) + end end def _index(sys) @@ -866,16 +917,21 @@ def _select_other(sys, other, index, ventilation_links, folded = {}) end x_probe = Context.new(sys, other, index) - ventilation_type = Context.texts(x_probe.mv(other), 'VentilationType') - if ventilation_type.empty? + mv = x_probe.mv(other) + ventilation_types = Context.texts(mv, 'VentilationType') + if ventilation_types.length > 1 + return _result(:conflicting_input, sys_id, ids, premises, nil, ['Multiple VentilationType values.']) + end + + if mv.nil? return _result(:missing_input, sys_id, ids, premises, nil, ['OtherHVACSystem does not identify a supported ventilation configuration.']) end - if ventilation_type.length > 1 - return _result(:conflicting_input, sys_id, ids, premises, nil, ['Multiple VentilationType values.']) - end - ventilation_type = ventilation_type.first + ventilation_type = ventilation_types.first + # Order matters: recovery and exhaust-only come before the integrated check, so an integrated + # HRV/ERV keeps its own rules (ComStock recovery or a blocking result) and is never reduced to + # an integrated-outdoor-air note that drops the heat recovery. return _select_recovery(sys, other, index, linked_ids, premises, folded) if RECOVERY_TYPES.include?(ventilation_type) if NOT_MAPPABLE_OTHER.key?(ventilation_type) @@ -885,14 +941,21 @@ def _select_other(sys, other, index, ventilation_links, folded = {}) configuration: configuration) end - if _integrated?(other) - return _result(:integrated, sys_id, ids, premises, nil, - ['Outdoor air is integrated with the linked deliveries; they are selected as conditioning deliveries.'], - configuration: 'Integrated outdoor air') + return _select_integrated(sys_id, other, ids, premises, linked_ids, index, ventilation_type) if _integrated?(other) + + row89 = _row89_type(other) + return _select_row89(sys, other, ids, premises, linked_ids, index, ventilation_links, row89) if row89 + + if ventilation_type.nil? + return _result(:missing_input, sys_id, ids, premises, nil, + ['OtherHVACSystem does not identify a supported ventilation configuration.']) end return _result(:missing_input, sys_id, ids, premises, nil, ['Missing LinkedDeliveryIDs.']) if linked_ids.empty? + # Row 89 records on conditioned deliveries never register in ventilation_links (see + # _consumes_deliveries?), so several of them on one conditioned delivery are not a shared-link + # conflict, the same as row 88. This check fires only for deliveries that consuming records share. shared = linked_ids.select { |id| ventilation_links[id].length > 1 } broken = linked_ids.reject { |id| index[:delivery].key?(id) } conflicts = broken.map { |id| "LinkedDeliveryID '#{id}' does not resolve to a Delivery" } + @@ -903,22 +966,6 @@ def _select_other(sys, other, index, ventilation_links, folded = {}) linked_conflicts = contexts.flat_map(&:conflicts) return _result(:conflicting_input, sys_id, ids, premises, nil, linked_conflicts) unless linked_conflicts.empty? - if ventilation_type == 'None' - explicit = contexts.all? do |x| - x.exists(x.h, 'NoHeating') && x.exists(x.c, 'NoCooling') && x.absent(x.d, 'DeliveryType') - end - return _result(:no_hvac, sys_id, ids, premises, nil, [], configuration: 'Explicitly no HVAC') if explicit - - if _ventilation_annotation?(other) && contexts.none? { |x| _explicit_no_hvac?(x) } - return _result(:no_hvac, sys_id, ids, premises, nil, - ['VentilationType None names no ventilation equipment; linked deliveries are selected as conditioning deliveries.'], - configuration: 'No separate ventilation equipment') - end - - return _result(:missing_input, sys_id, ids, premises, nil, - ['VentilationType None requires linked deliveries with NoHeating, NoCooling, and no DeliveryType.']) - end - configuration, measure = VENTILATION_MEASURES[ventilation_type] if configuration.nil? return _result(:missing_input, sys_id, ids, premises, nil, @@ -953,6 +1000,106 @@ def _select_other(sys, other, index, ventilation_links, folded = {}) _result(:match, sys_id, ids, premises, [:other, other_id], [], configuration: configuration, measure: measure) end + INTEGRATED_CONFIGURATION = 'Integrated outdoor air' + NO_VENTILATION_CONFIGURATION = 'No separate ventilation equipment' + + # Doc row 88: outdoor air integrated with the linked deliveries' own air system, for any + # VentilationType except DOAS, does not block the conditioning match. Links, if any, must resolve. + # Integrated records never register links, so the shared-link check does not apply to them. + def _select_integrated(sys_id, other, ids, premises, linked_ids, index, ventilation_type) + if ventilation_type == 'Dedicated outdoor air system' + return _result(:conflicting_input, sys_id, ids, premises, nil, + ['A dedicated outdoor air system is separate equipment, so it cannot be integrated with ' \ + 'the linked deliveries (mapping doc row 88 excludes it).'], + configuration: INTEGRATED_CONFIGURATION) + end + + broken = linked_ids.reject { |id| index[:delivery].key?(id) } + unless broken.empty? + return _result(:conflicting_input, sys_id, ids, premises, nil, + broken.map { |id| "LinkedDeliveryID '#{id}' does not resolve to a Delivery" }, + configuration: INTEGRATED_CONFIGURATION) + end + + text = if linked_ids.empty? + "Outdoor air is integrated with the conditioning equipment's air system; no separate ventilation equipment is modeled." + else + "Outdoor air is integrated with the linked deliveries' air system; they are selected as conditioning deliveries." + end + _result(:integrated, sys_id, ids, premises, nil, ["#{text}#{_ignored_suffix(other)}"], + configuration: INTEGRATED_CONFIGURATION, blocking: false, basis: :doc) + end + + # Doc row 89: VentilationType None or untyped on conditioned deliveries names no ventilation + # equipment and does not block the conditioning match. Doc row 87: None on deliveries that are + # all explicitly unconditioned is explicit no HVAC, which blocks, because the whole-building + # HVAC steps would condition those zones. + def _select_row89(sys, other, ids, premises, linked_ids, index, ventilation_links, row89) + sys_id = sys.attributes['ID'] + return _result(:missing_input, sys_id, ids, premises, nil, ['Missing LinkedDeliveryIDs.']) if linked_ids.empty? + + # Row 89 records on conditioned deliveries never register in ventilation_links (see + # _consumes_deliveries?), so several of them on one conditioned delivery are not a shared-link + # conflict, the same as row 88. This check fires only for deliveries that consuming records share. + shared = linked_ids.select { |id| ventilation_links[id].length > 1 } + broken = linked_ids.reject { |id| index[:delivery].key?(id) } + conflicts = broken.map { |id| "LinkedDeliveryID '#{id}' does not resolve to a Delivery" } + + shared.map { |id| "Delivery '#{id}' is linked by more than one OtherHVACSystem" } + return _result(:conflicting_input, sys_id, ids, premises, nil, conflicts) unless conflicts.empty? + + contexts = linked_ids.map { |id| Context.new(sys, index[:delivery][id], index) } + linked_conflicts = contexts.flat_map(&:conflicts) + return _result(:conflicting_input, sys_id, ids, premises, nil, linked_conflicts) unless linked_conflicts.empty? + + explicit = contexts.select { |x| _explicit_no_hvac?(x) } + if explicit.length == contexts.length + if row89 == :none + return _result(:no_hvac, sys_id, ids, premises, nil, + ["Deliveries #{linked_ids.join(', ')} are explicitly unconditioned (NoHeating, NoCooling, " \ + 'no DeliveryType), but the baseline HVAC steps apply to all model zones and would condition them.'], + configuration: 'Explicitly no HVAC') + end + + return _result(:missing_input, sys_id, ids, premises, nil, + ['MechanicalVentilation without VentilationType None on explicitly unconditioned deliveries ' \ + "#{linked_ids.join(', ')}; VentilationType None marks them as having no HVAC (mapping doc row 87)."]) + end + unless explicit.empty? + return _result(:missing_input, sys_id, ids, premises, nil, + ['MechanicalVentilation links both explicitly unconditioned deliveries ' \ + "(#{explicit.map { |x| x.d.attributes['ID'] }.join(', ')}) and conditioned deliveries."]) + end + # Doc row 89 applies only when at least one linked delivery is not marked both NoHeating and + # NoCooling. Deliveries with both markers and a DeliveryType are ventilation deliveries. + if contexts.all? { |x| x.exists(x.h, 'NoHeating') && x.exists(x.c, 'NoCooling') } + return _result(:conflicting_input, sys_id, ids, premises, nil, + ["MechanicalVentilation links only unconditioned ventilation deliveries (#{linked_ids.join(', ')}); " \ + 'mapping doc row 89 needs at least one conditioned delivery.']) + end + + suffix = _ignored_suffix(other) + selected = 'the linked deliveries are selected as conditioning deliveries.' + case row89 + when :none + _result(:no_hvac, sys_id, ids, premises, nil, + ["VentilationType None names no ventilation equipment; #{selected}#{suffix}"], + configuration: NO_VENTILATION_CONFIGURATION, blocking: false, basis: :doc) + when :untyped + _result(:missing_input, sys_id, ids, premises, nil, + ["MechanicalVentilation has no VentilationType, so it names no separate ventilation equipment; #{selected}#{suffix}"], + configuration: NO_VENTILATION_CONFIGURATION, blocking: false, basis: :doc) + when :unknown + unless @allow_approximations + return _result(:missing_input, sys_id, ids, premises, nil, + ["VentilationType 'Unknown' does not identify a supported configuration."]) + end + + _result(:missing_input, sys_id, ids, premises, nil, + ["VentilationType Unknown is read as untyped, so it names no separate ventilation equipment; #{selected}#{suffix}"], + configuration: NO_VENTILATION_CONFIGURATION, blocking: false, basis: :policy) + end + end + def _group_key(group, x) case group when :delivery then [:delivery, x.d.attributes['ID']] @@ -979,10 +1126,27 @@ def _linked_premises(record) end end - def _result(status, sys_id, ids, premises, group_key, messages, configuration: nil, measure: nil, measure_arguments: {}) - Result.new(status: status, configuration: configuration, measure: measure, hvac_system_id: sys_id, - record_ids: ids.compact.uniq, premises: premises, group_key: group_key, messages: messages, - measure_arguments: measure_arguments) + def _result(status, sys_id, ids, premises, group_key, messages, configuration: nil, measure: nil, measure_arguments: {}, + blocking: nil, basis: nil) + _check_result(status, measure, messages, blocking, basis) + Result.new(status:, configuration:, measure:, hvac_system_id: sys_id, record_ids: ids.compact.uniq, + premises:, group_key:, messages:, measure_arguments:, blocking:, basis:) + end + + # Catches selector branches that would build nothing, or wave a record through silently. + def _check_result(status, measure, messages, blocking, basis) + raise ArgumentError, "Unknown status #{status.inspect}" unless STATUSES.include?(status) + raise ArgumentError, "Unknown basis #{basis.inspect}" unless basis.nil? || BASES.include?(basis) + raise ArgumentError, 'blocking must be nil or false' unless blocking.nil? || blocking == false + + if status == :match + raise ArgumentError, 'A match must name a measure' if measure.nil? + raise ArgumentError, 'A match cannot be non-blocking' if blocking == false + elsif basis == :approximation + raise ArgumentError, 'Only a match can be an approximation' + end + raise ArgumentError, 'A non-blocking result needs a basis' if blocking == false && basis.nil? + raise ArgumentError, 'A result with a basis needs a message' if !basis.nil? && messages.empty? end end end diff --git a/lib/boss_cli.rb b/lib/boss_cli.rb index cb8fb98..99dbd2a 100755 --- a/lib/boss_cli.rb +++ b/lib/boss_cli.rb @@ -17,10 +17,14 @@ class CLI < Thor option :standard_version, :aliases => "-v", :desc => "building standard to use (eg ASHRAE90.1 or CaliforniaTitle24). Defaults to ASHRAE90.1" option :run, :aliases => "-r", :desc => "if set, will also run the baseline" option :require_l200, :type => :boolean, :default => false, :desc => "fail instead of falling back to create_typical_building_from_model HVAC" + option :allow_approximations, :type => :boolean, :default => true, + :desc => "allow HVAC records BOSS accepts by policy or as an approximation (logged as warnings); " \ + "--no-allow_approximations keeps the mapping doc's blocking rules" def write_baseline_osw(buildingsync_file) standard_version = options[:standard_version] || ASHRAE90_1 osw_path = BOSS::Boss.write_baseline_osw(buildingsync_file, options[:output_path], options[:epw_path], standard_version, - require_l200: options[:require_l200]) + require_l200: options[:require_l200], + allow_approximations: options[:allow_approximations]) puts "Baseline OSW written to: #{osw_path}" if options[:run] puts "running!" diff --git a/spec/tests/unit/baseline_hvac_planner_spec.rb b/spec/tests/unit/baseline_hvac_planner_spec.rb index cb4ef1c..a6e6d4b 100644 --- a/spec/tests/unit/baseline_hvac_planner_spec.rb +++ b/spec/tests/unit/baseline_hvac_planner_spec.rb @@ -219,6 +219,116 @@ def plan_for(results, systems, template = '90.1-2019') end end + describe 'notes' do + ptac_path = File.expand_path('../../files/v2.7.0/l200_hvac/l200_ptac.xml', __dir__) + # l200_ptac.xml plus one OtherHVACSystem linked to its only delivery. + ptac_with = lambda do |other_xml| + text = File.read(ptac_path) + prefix = text[/<(\w+:)?HVACSystem ID="HVACSystem-1"/, 1].to_s + xml = "#{other_xml}".gsub(%r{<(/?)([A-Za-z])}, "<\\1#{prefix}\\2") + doc = REXML::Document.new(text.sub("", "#{xml}"), ignore_whitespace_nodes: :all) + REXML::XPath.first(doc, "//*[local-name()='HVACSystems']") + end + record = lambda do |ventilation, integration: 'Stand-alone'| + "#{ventilation}" \ + "#{integration}" \ + '' + end + + { + 'integrated outdoor air' => [record.call('Supply only', + integration: 'Integrated with central air distribution'), 'integrated'], + 'VentilationType None' => [record.call('None'), 'no_hvac'], + 'untyped MechanicalVentilation' => [record.call('false'), 'missing_input'] + }.each do |label, (other_xml, status)| + it "plans topology for l200_ptac.xml plus #{label}, with one note" do + plan = described_class.new.plan(ptac_with.call(other_xml), '90.1-2013') + + expect(plan.status).to eq(:topology), plan.messages.join("\n") + expect(plan.messages).to eq([]) + expect(plan.steps.first[:arguments][:topology_measure]).to eq('hvac_ptac') + expect(plan.note_entries.length).to eq(1) + expect(plan.note_entries.first).to include(level: :info, basis: :doc, applied: true) + expect(plan.note_entries.first[:text]).to include("(#{status}, doc; O-1, Delivery-1)") + end + end + + it 'keeps recovery on topology when the ERV file also has an integrated outdoor-air note' do + path = File.expand_path('../../files/v2.7.0/Example_ASHRAE_L2_Report_l200_erv.xml', __dir__) + integrated = '' \ + 'Supply only' \ + 'Integrated with central air distribution' \ + '' + doc = REXML::Document.new(File.read(path).sub('', "#{integrated}"), + ignore_whitespace_nodes: :all) + reader = BOSS::BuildingSyncReader.new(doc, nil, ASHRAE90_1) + plan = described_class.new.plan(reader.get_hvac_systems_xml, reader.get_standard_template) + + expect(plan.status).to eq(:topology), plan.messages.join("\n") + expect(plan.steps.last[:measure_dir_name]).to eq('modify_existing_heat_recovery') + expect(plan.note_entries.map { |n| n.slice(:level, :basis, :applied) }) + .to eq([{ level: :warn, basis: :policy, applied: true }, { level: :info, basis: :doc, applied: true }]) + expect(plan.note_entries.last[:text]).to include('(integrated, doc; O-INT, Delivery-45022120)') + end + + it 'falls back on a blocking record and keeps the notes' do + note = result.call(status: :no_hvac, configuration: 'None', messages: ['names nothing'], record_ids: ['O-1']) + note.blocking = false + note.basis = :doc + plan = plan_for([result.call, note, + result.call(status: :not_mappable, configuration: 'Humidifier', messages: ['no measure'])], hvac_systems) + + expect(plan.status).to eq(:fallback) + expect(plan.messages).to eq(['Humidifier (not_mappable): no measure']) + expect(plan.note_entries.map { |n| n[:text] }).to eq(['None (no_hvac, doc; O-1): names nothing']) + end + + it 'falls back with found 0 when every record is a note' do + note = result.call(status: :integrated, configuration: 'Integrated', messages: ['integrated'], record_ids: ['O-1']) + note.blocking = false + note.basis = :doc + plan = plan_for([note], hvac_systems) + + expect(plan.status).to eq(:fallback) + expect(plan.messages.join).to match(/found 0; the HVAC records carry only notes/) + expect(plan.notes).to eq([note]) + end + + it 'deduplicates notes by configuration and text, and marks policy matches not applied on fallback' do + notes = ['O-1', 'O-2'].map do |id| + note = result.call(status: :integrated, configuration: 'Integrated', messages: ['integrated'], record_ids: [id]) + note.blocking = false + note.basis = :doc + note + end + recovery = result.call(measure: 'upgrade_hvac_exhaust_air_energy_or_heat_recovery', configuration: 'Recovery', + messages: ['ComStock'], record_ids: ['O-3'], group_key: [:recovery, 'O-3']) + recovery.basis = :policy + recovery.measure_arguments = { 'ventilation_type' => 'Heat recovery ventilator' } + plan = plan_for(notes + [recovery, result.call(premises: [{ type: 'ThermalZone', id: 'TZ-1' }])], hvac_systems) + + expect(plan.status).to eq(:fallback) + expect(plan.note_entries).to eq( + [{ level: :info, basis: :doc, applied: true, text: 'Integrated (integrated, doc; O-1, O-2): integrated' }, + { level: :warn, basis: :policy, applied: false, text: 'Recovery (match, policy; O-3): ComStock (not applied)' }] + ) + end + + it 'defaults notes to empty for plans built without them' do + expect(described_class::Plan.new(status: :fallback, steps: [], messages: []).note_entries).to eq([]) + end + + it 'falls back for ComStock recovery when approximations are off' do + path = File.expand_path('../../files/v2.7.0/Example_ASHRAE_L2_Report_l200_erv.xml', __dir__) + doc = REXML::Document.new(File.read(path), ignore_whitespace_nodes: :all) + reader = BOSS::BuildingSyncReader.new(doc, nil, ASHRAE90_1) + plan = described_class.new(allow_approximations: false).plan(reader.get_hvac_systems_xml, reader.get_standard_template) + + expect(plan.status).to eq(:fallback) + expect(plan.messages.join).to match(/Exhaust air heat .* row 83/) + end + end + describe '.proposed_system_ids' do def systems_with_measures(measure_xml) xml = <<~XML diff --git a/spec/tests/unit/boss_spec.rb b/spec/tests/unit/boss_spec.rb index f9b7491..c779dd3 100644 --- a/spec/tests/unit/boss_spec.rb +++ b/spec/tests/unit/boss_spec.rb @@ -179,6 +179,29 @@ def common_steps(climate_zone) end end + describe '.write_baseline_osw allow_approximations' do + erv_path = File.join(BOSS_SPEC_FILES_DIR, 'v2.7.0', 'Example_ASHRAE_L2_Report_l200_erv.xml') + + { true => ['topology', []], false => ['fallback', [/row 83/]] }.each do |allow, (status, messages)| + it "passes allow_approximations: #{allow} through to the planner and the report" do + Dir.mktmpdir do |output_dir| + described_class.write_baseline_osw(erv_path, output_dir, nil, ASHRAE90_1, allow_approximations: allow) + report = JSON.parse(File.read(File.join(output_dir, 'baseline', 'hvac_mapping_report.json'))) + expect(report).to include('status' => status, 'allow_approximations' => allow) + expect(report['messages']).to match(messages.map { |m| a_string_matching(m) }) + end + end + end + + it 'maps --no-allow_approximations on the CLI to allow_approximations: false' do + require 'boss_cli' + expect(described_class).to receive(:write_baseline_osw) + .with(erv_path, 'out', nil, ASHRAE90_1, require_l200: false, allow_approximations: false).and_return('out/baseline/in.osw') + expect { BOSS::CLI.start(['write_baseline_osw', erv_path, '-o', 'out', '--no-allow_approximations']) } + .to output(%r{Baseline OSW written to: out/baseline/in.osw}).to_stdout + end + end + describe '.build_baseline_osw' do before do stub_measure_dirs(local: [LOCAL_MEASURES_DIR], external: [external_measure_dir], discovered: [gem_measure_dir]) @@ -189,7 +212,7 @@ def common_steps(climate_zone) expect(described_class.public_methods).to include(:write_baseline_osw, :run_baseline_osw) expect(described_class.method(:write_baseline_osw).parameters).to eq [ [:req, :xml_file_path], [:req, :output_dir], [:req, :epw_file_path], [:req, :standard_to_be_used], - [:key, :require_l200] + [:key, :require_l200], [:key, :allow_approximations] ] expect(described_class.method(:run_baseline_osw).arity).to eq 1 end diff --git a/spec/tests/unit/heating_with_terminal_cooling_spec.rb b/spec/tests/unit/heating_with_terminal_cooling_spec.rb index a8cfb0e..8f41585 100644 --- a/spec/tests/unit/heating_with_terminal_cooling_spec.rb +++ b/spec/tests/unit/heating_with_terminal_cooling_spec.rb @@ -26,16 +26,18 @@ def select(systems) = BOSS::HvacTopologySelector.new.select(systems) def element(systems, id) = REXML::XPath.first(systems, ".//*[@ID='#{id}']") - it 'selects one result from standard elements' do + it 'selects one match from standard elements, plus a non-blocking note for the untyped ventilation record' do results = select(hvac_systems(l200_path)) - expect(results.length).to eq 1 - result = results.first + expect(results.length).to eq 2 + result, note = results expect(result.status).to eq :match expect(result.measure).to eq 'hvac_heating_with_terminal_cooling' expect(result.measure_arguments).to eq('heating_source' => 'central_gas_furnace') expect(result.record_ids).to include('Delivery-44989380', 'Delivery-44989400', 'HeatingSource-44989520', - 'CoolingSource-44989500', 'OtherHVACSystemType-44989440') + 'CoolingSource-44989500') expect(result.messages.join(' ')).to include('CoolingSource-44989500 quantity 4') + expect(note).to have_attributes(status: :missing_input, blocking: false, basis: :doc, + record_ids: ['OtherHVACSystemType-44989440', 'Delivery-44989380', 'Delivery-44989400']) end it 'does not match the original XML, whose sources are shared and DX type is unstated' do @@ -144,7 +146,11 @@ def baseboard_delivery(systems) expect(typical['arguments']['add_hvac']).to be false report = JSON.parse(File.read(File.join(dir, 'baseline', 'hvac_mapping_report.json'))) expect(report['status']).to eq 'topology' + expect(report['allow_approximations']).to be true expect(report['hvac_steps']).to eq ['apply_hvac_topology_to_zone_scope', 'apply_standard_hvac_sizing_and_efficiency'] + expect(report['messages']).to eq [] + expect(report['notes'].map { |n| [n['level'], n['basis'], n['applied']] }).to eq [['info', nil, true], ['info', 'doc', true]] + expect(report['notes'].last['text']).to include('OtherHVACSystemType-44989440', 'no VentilationType') end end diff --git a/spec/tests/unit/hvac_topology_selector_spec.rb b/spec/tests/unit/hvac_topology_selector_spec.rb index a163a3d..617e6a5 100644 --- a/spec/tests/unit/hvac_topology_selector_spec.rb +++ b/spec/tests/unit/hvac_topology_selector_spec.rb @@ -362,35 +362,188 @@ def select_from(body, prefix: nil) end conditioning_link = '' + notes = ->(results) { results.reject(&:blocking?).map { |r| [r.status, r.basis] } } - it 'still selects conditioning deliveries linked by VentilationType None' do + it 'still selects conditioning deliveries linked by VentilationType None, as a non-blocking note' do results = select_from(with_ventilation.call(other.call(mechanical.call('None'), links: conditioning_link))) expect(results.map(&:status)).to eq([:match, :missing_input, :no_hvac]) expect(results.first.measure).to eq('hvac_ptac') - expect(results.last.configuration).to eq('No separate ventilation equipment') + expect(results.last).to have_attributes(configuration: 'No separate ventilation equipment', blocking: false, basis: :doc) + expect(results[1].blocking?).to be true end - it 'still selects conditioning deliveries linked by an untyped ventilation record' do + it 'still selects conditioning deliveries linked by an untyped ventilation record, as a non-blocking note' do untyped = 'false' results = select_from(with_ventilation.call(other.call(untyped, links: conditioning_link))) expect(results.first).to have_attributes(status: :match, measure: 'hvac_ptac') - expect(results.last.status).to eq(:missing_input) + expect(results.last).to have_attributes(status: :missing_input, blocking: false, basis: :doc) + expect(results.last.messages.join).to include('Not transferred: MV/DemandControlVentilation') end - it 'still selects conditioning deliveries linked by integrated outdoor air records' do + it 'reads every MechanicalVentilation child on a None record as an annotation and keeps the conditioning match' do + extra = '500None' \ + '2' + results = select_from(with_ventilation.call(other.call(extra, links: conditioning_link))) + expect(results.first).to have_attributes(status: :match, measure: 'hvac_ptac') + expect(notes.call(results)).to eq([[:no_hvac, :doc]]) + expect(results.last.messages.join).to include('MV/VentilationRate', 'MV/Capacity') + end + + # Appends copies of the first OtherHVACSystem, each with the given ID and inner XML. + add_others = lambda do |xml, *extra| + extra.reduce(xml) { |acc, (id, body)| acc.sub('', "#{body}") } + end + + it 'gives several row 89 records on one conditioned delivery one note each, without a shared-link conflict' do + untyped = '500' + xml = add_others.call(other.call(mechanical.call('None'), links: conditioning_link), + ['O-2', "#{untyped}Stand-alone#{conditioning_link}"]) + results = select_from(with_ventilation.call(xml)) + expect(results.first).to have_attributes(status: :match, measure: 'hvac_ptac') + expect(notes.call(results)).to eq([[:no_hvac, :doc], [:missing_input, :doc]]) + end + + it 'blocks VentilationType None on a ventilation delivery another record owns (doc row 89 needs a conditioned delivery)' do + xml = add_others.call(other.call(mechanical.call('Dedicated outdoor air system')), + ['O-2', "#{mechanical.call('None')}Stand-alone" \ + '']) + results = select_from(with_ventilation.call(xml)) + expect(results.map { |r| [r.status, r.measure] }).to eq([[:match, 'hvac_ptac'], [:match, 'hvac_doas'], [:conflicting_input, nil]]) + expect(results.last.blocking?).to be true + expect(results.last.messages.join).to include('only unconditioned ventilation deliveries (D-V)', 'row 89') + end + + it 'words an unlinked integrated note without naming linked deliveries' do + results = select_from(with_ventilation.call(other.call(mechanical.call('Supply only'), links: '', + integration: 'Integrated with central air distribution'))) + expect(results.last).to have_attributes(status: :integrated, blocking: false, basis: :doc) + expect(results.last.messages.join).to include('no separate ventilation equipment is modeled') + expect(results.last.messages.join).not_to include('linked deliveries') + end + + it 'still selects conditioning deliveries linked by integrated outdoor air records, as non-blocking notes' do integrated = other.call(mechanical.call('Supply only'), links: conditioning_link, integration: 'Integrated with central air distribution') second = integrated[%r{}].sub('O-1', 'O-2') results = select_from(with_ventilation.call(integrated.sub('', "#{second}"))) expect(results.map(&:status)).to eq([:match, :missing_input, :integrated, :integrated]) expect(results.first.measure).to eq('hvac_ptac') + expect(notes.call(results)).to eq([[:integrated, :doc], [:integrated, :doc]]) end - it 'lets VentilationType None own explicitly unconditioned deliveries' do + it 'treats an untyped integrated record as integrated outdoor air, not missing input' do + untyped = 'true' + results = select_from(with_ventilation.call(other.call(untyped, links: conditioning_link, + integration: 'Integrated with local air distribution'))) + expect(results.last).to have_attributes(status: :integrated, blocking: false, basis: :doc) + end + + it 'blocks an integrated record whose link does not resolve' do + broken = '' + record = other.call(mechanical.call('Supply only'), links: broken, integration: 'Integrated with central air distribution') + results = select_from(with_ventilation.call(record)) + expect(results.last).to have_attributes(status: :conflicting_input, blocking: nil) + expect(results.last.messages.join).to include("'Nope' does not resolve") + end + + it 'blocks an integrated DOAS' do + record = other.call(mechanical.call('Dedicated outdoor air system'), links: conditioning_link, + integration: 'Integrated with central air distribution') + results = select_from(with_ventilation.call(record)) + expect(results.last).to have_attributes(status: :conflicting_input, blocking: nil) + expect(results.last.messages.join).to include('row 88') + end + + it 'keeps an integrated ERV on the recovery rules instead of an integrated-outdoor-air note' do + record = other.call(mechanical.call('Energy recovery ventilator'), links: conditioning_link, + integration: 'Integrated with local air distribution') + results = select_from(with_ventilation.call(record)) + expect(results.last).to have_attributes(status: :not_mappable, configuration: 'Exhaust air heat / energy recovery') + expect(results.last.blocking?).to be true + end + + it 'lets VentilationType None own explicitly unconditioned deliveries and blocks with a real message' do body = with_ventilation.call(other.call(mechanical.call('None'))).sub("#{single_zone_cav}", '') results = select_from(body) expect(results.map(&:status)).to eq([:match, :no_hvac]) - expect(results.last.configuration).to eq('Explicitly no HVAC') + expect(results.last).to have_attributes(configuration: 'Explicitly no HVAC', blocking: nil) + expect(results.last.messages.join).to include('D-V', 'would condition them') + end + + it 'blocks an untyped record on explicitly unconditioned deliveries' do + untyped = 'false' + body = with_ventilation.call(other.call(untyped)).sub("#{single_zone_cav}", '') + results = select_from(body) + expect(results.last).to have_attributes(status: :missing_input, blocking: nil) + expect(results.last.messages.join).to include('row 87') + end + + it 'blocks a None record linking both explicitly unconditioned and conditioned deliveries' do + both = '' + body = with_ventilation.call(other.call(mechanical.call('None'), links: both)).sub("#{single_zone_cav}", '') + results = select_from(body) + expect(results.first).to have_attributes(status: :match, measure: 'hvac_ptac') + expect(results.last).to have_attributes(status: :missing_input, blocking: nil) + expect(results.last.messages.join).to include('both explicitly unconditioned') + end + + it 'reads VentilationType Unknown as untyped by policy, and blocks it when approximations are off' do + body = with_ventilation.call(other.call(mechanical.call('Unknown'), links: conditioning_link)) + expect(select_from(body).last).to have_attributes(status: :missing_input, blocking: false, basis: :policy) + doc = REXML::Document.new("#{body}") + strict = described_class.new(allow_approximations: false).select(doc.root.elements.to_a.first) + expect(strict.first).to have_attributes(status: :match, measure: 'hvac_ptac') + expect(strict.last).to have_attributes(status: :missing_input, blocking: nil, basis: nil) + end + + it 'keeps VentilationType Other blocking' do + results = select_from(with_ventilation.call(other.call(mechanical.call('Other'), links: conditioning_link))) + expect(results.last).to have_attributes(status: :missing_input, blocking: nil) + end + + it 'keeps spot exhaust and humidifiers blocking' do + spot = select_from(with_ventilation.call(other.call(''))) + humidifier = select_from(with_ventilation.call(other.call('', links: ''))) + expect([spot.last, humidifier.last].map { |r| [r.status, r.blocking?] }).to eq([[:not_mappable, true], [:not_mappable, true]]) + end + + it 'marks ComStock recovery as a policy match, and not mappable when approximations are off' do + body = with_recovery.call(recovery.call) + expect(select_from(body).last).to have_attributes(status: :match, basis: :policy) + expect(select_from(body).last.messages.join).to include('row 83') + doc = REXML::Document.new("#{body}") + strict = described_class.new(allow_approximations: false).select(doc.root.elements.to_a.first) + expect(strict.map(&:status)).to eq([:match, :not_mappable]) + expect(strict.last.blocking?).to be true + end + end + + describe 'result invariants' do + selector = described_class.new + build = lambda do |status, **options| + selector.send(:_result, status, 'HVAC-1', ['X-1'], [], nil, options.delete(:messages) || ['why'], **options) + end + + it 'rejects a match without a measure, or a non-blocking match' do + expect { build.call(:match) }.to raise_error(ArgumentError, /must name a measure/) + expect { build.call(:match, measure: 'hvac_ptac', blocking: false, basis: :doc) }.to raise_error(ArgumentError, /non-blocking/) + end + + it 'rejects a non-blocking result without a basis, or a basis without a message' do + expect { build.call(:integrated, blocking: false) }.to raise_error(ArgumentError, /needs a basis/) + expect { build.call(:integrated, blocking: false, basis: :doc, messages: []) }.to raise_error(ArgumentError, /needs a message/) + end + + it 'rejects an approximation that is not a match, and unknown values' do + expect { build.call(:not_mappable, blocking: false, basis: :approximation) }.to raise_error(ArgumentError, /Only a match/) + expect { build.call(:maybe) }.to raise_error(ArgumentError, /Unknown status/) + expect { build.call(:integrated, blocking: false, basis: :guess) }.to raise_error(ArgumentError, /Unknown basis/) + expect { build.call(:integrated, blocking: true) }.to raise_error(ArgumentError, /nil or false/) + end + + it 'gives every exact match row the checks the selector calls' do + rows = described_class::DELIVERY_RULES.select { |rule| rule[:status] == :match } + expect(rows.reject { |rule| rule.key?(:absent) && rule.key?(:guards) }).to be_empty end end end